refactor(file): improve path handling and validation (#82)

* refactor(file): improve path handling and validation

* fix: update XML escaping to use escapeXml10 for improved compatibility

* feat(mime): integrate Apache Tika for content-based MIME detection across services

* test: enhance MultipartFile tests with input stream handling and content type validation
This commit is contained in:
brios
2026-04-22 17:27:08 -04:00
committed by Zach Yale
parent 2ecd35296d
commit cbd04eec8e
20 changed files with 523 additions and 227 deletions
+3
View File
@@ -149,6 +149,9 @@ dependencies {
implementation("org.tukaani:xz:1.12") // Required by commons-compress for 7z support
implementation("org.apache.commons:commons-text:1.15.0")
// --- MIME Detection ---
implementation("org.apache.tika:tika-core:3.3.0")
// --- XML Support (JAXB) ---
implementation("jakarta.xml.bind:jakarta.xml.bind-api:4.0.5")
runtimeOnly("org.glassfish.jaxb:jaxb-runtime:4.0.7")
@@ -10,6 +10,7 @@ import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.booklore.util.FileUtils;
import org.booklore.util.MimeDetector;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.*;
@@ -104,7 +105,7 @@ public class AudiobookReaderController {
return builder
.cacheControl(CacheControl.noCache().cachePrivate())
.contentType(MediaTypeFactory.getMediaType(filePath.toString()).orElse(MediaType.APPLICATION_OCTET_STREAM))
.contentType(MediaType.parseMediaType(MimeDetector.detectSafe(filePath)))
.body(new FileSystemResource(filePath));
}
}
@@ -24,6 +24,8 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.nio.charset.StandardCharsets;
@Tag(name = "OPDS", description = "Endpoints for OPDS catalog feeds, book downloads, covers, and search description")
@Slf4j
@RestController
@@ -135,21 +137,23 @@ public class OpdsController {
@Operation(summary = "Get OPDS catalog feed", description = "Retrieve the OPDS acquisition catalog feed.")
@ApiResponse(responseCode = "200", description = "Catalog feed returned successfully")
@GetMapping(value = "/catalog", produces = OPDS_ACQUISITION_MEDIA_TYPE)
public ResponseEntity<String> getCatalog(@Parameter(hidden = true) HttpServletRequest request) {
public ResponseEntity<byte[]> getCatalog(@Parameter(hidden = true) HttpServletRequest request) {
String feed = opdsFeedService.generateCatalogFeed(request);
byte[] payload = feed.getBytes(StandardCharsets.UTF_8);
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType(OPDS_ACQUISITION_MEDIA_TYPE))
.body(feed);
.body(payload);
}
@Operation(summary = "Get recent books feed", description = "Retrieve the OPDS feed for recently added books.")
@ApiResponse(responseCode = "200", description = "Recent books feed returned successfully")
@GetMapping(value = "/recent", produces = OPDS_ACQUISITION_MEDIA_TYPE)
public ResponseEntity<String> getRecentBooks(@Parameter(hidden = true) HttpServletRequest request) {
public ResponseEntity<byte[]> getRecentBooks(@Parameter(hidden = true) HttpServletRequest request) {
String feed = opdsFeedService.generateRecentFeed(request);
byte[] payload = feed.getBytes(StandardCharsets.UTF_8);
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType(OPDS_ACQUISITION_MEDIA_TYPE))
.body(feed);
.body(payload);
}
@Operation(summary = "Get surprise feed", description = "Retrieve the OPDS feed for surprise/random books.")
@@ -30,7 +30,6 @@ import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Pattern;
@@ -59,7 +58,8 @@ public class BookDownloadService {
if (primaryFile == null) {
throw ApiError.FAILED_TO_DOWNLOAD_FILE.createException(bookId);
}
Path file = FileUtils.getBookFullPath(bookEntity).toAbsolutePath().normalize();
Path libraryRoot = Path.of(bookEntity.getLibraryPath().getPath());
Path file = FileUtils.requirePathWithinBase(primaryFile.getFullFilePath(), libraryRoot);
if (!Files.exists(file)) {
throw ApiError.FAILED_TO_DOWNLOAD_FILE.createException(bookId);
@@ -104,7 +104,8 @@ public class BookDownloadService {
throw ApiError.FILE_NOT_FOUND.createException(fileId);
}
Path file = bookFileEntity.getFullFilePath().toAbsolutePath().normalize();
Path libraryRoot = Path.of(bookFileEntity.getBook().getLibraryPath().getPath());
Path file = FileUtils.requirePathWithinBase(bookFileEntity.getFullFilePath(), libraryRoot);
if (!Files.exists(file)) {
throw ApiError.FAILED_TO_DOWNLOAD_FILE.createException(fileId);
@@ -146,10 +147,12 @@ public class BookDownloadService {
throw ApiError.FILE_NOT_FOUND.createException(bookId);
}
Path libraryRoot = Path.of(bookEntity.getLibraryPath().getPath());
// If only one file and it's not folder-based, download it directly
if (allFiles.size() == 1) {
BookFileEntity singleFile = allFiles.get(0);
Path filePath = singleFile.getFullFilePath();
Path filePath = FileUtils.requirePathWithinBase(singleFile.getFullFilePath(), libraryRoot);
if (!Files.exists(filePath)) {
throw ApiError.FAILED_TO_DOWNLOAD_FILE.createException(bookId);
@@ -183,7 +186,7 @@ public class BookDownloadService {
try (ZipOutputStream zos = new ZipOutputStream(response.getOutputStream())) {
for (BookFileEntity bookFile : allFiles) {
Path filePath = bookFile.getFullFilePath();
Path filePath = FileUtils.requirePathWithinBase(bookFile.getFullFilePath(), libraryRoot);
if (!Files.exists(filePath)) {
log.warn("Skipping missing file during ZIP creation: {}", filePath);
@@ -258,7 +261,9 @@ public class BookDownloadService {
int compressionPercentage = koboSettings.getConversionImageCompressionPercentage();
Path tempDir = null;
try {
File inputFile = FileUtils.getBookFullPath(bookEntity).toFile();
Path libraryRoot = Path.of(bookEntity.getLibraryPath().getPath());
Path normalizedInputPath = FileUtils.requirePathWithinBase(primaryFile.getFullFilePath(), libraryRoot);
File inputFile = normalizedInputPath.toFile();
File fileToSend = inputFile;
if (convertCbxToEpub || convertEpubToKepub) {
@@ -9,6 +9,7 @@ import org.booklore.model.entity.CustomFontEntity;
import org.booklore.model.enums.FontFormat;
import org.booklore.repository.CustomFontRepository;
import org.booklore.repository.UserRepository;
import org.booklore.util.MimeDetector;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.FileSystemResource;
@@ -254,54 +255,42 @@ public class CustomFontService {
}
/**
* Validates font file format by checking magic bytes.
* Validates font file format by detecting MIME type from content via Apache Tika.
* Prevents malicious files from being uploaded with font extensions.
*/
private void validateFontMagicBytes(Path fontPath, FontFormat expectedFormat) throws IOException {
byte[] header = new byte[4];
String detectedMime = MimeDetector.detect(fontPath);
try (var inputStream = Files.newInputStream(fontPath)) {
int bytesRead = inputStream.read(header);
FontFormat detectedFormat = null;
try {
detectedFormat = FontFormat.fromMimeType(detectedMime);
} catch (IllegalArgumentException ignored) {
// Tika may return a generic MIME treated as unknown format below
}
if (bytesRead < 4) {
throw new IllegalArgumentException("Invalid font file: file too small");
// Also accept application/x-font-ttf / application/x-font-otf variants
if (detectedFormat == null) {
if (detectedMime.contains("ttf") || detectedMime.equals("application/x-font-truetype")) {
detectedFormat = FontFormat.TTF;
} else if (detectedMime.contains("otf") || detectedMime.equals("application/x-font-opentype")) {
detectedFormat = FontFormat.OTF;
} else if (detectedMime.contains("woff2")) {
detectedFormat = FontFormat.WOFF2;
} else if (detectedMime.contains("woff")) {
detectedFormat = FontFormat.WOFF;
}
}
boolean isValid = false;
String detectedFormat = "Unknown";
// Check TTF signature: 0x00 0x01 0x00 0x00 or "true" (0x74 0x72 0x75 0x65)
if ((header[0] == 0x00 && header[1] == 0x01 && header[2] == 0x00 && header[3] == 0x00) ||
(header[0] == 0x74 && header[1] == 0x72 && header[2] == 0x75 && header[3] == 0x65)) {
isValid = (expectedFormat == FontFormat.TTF);
detectedFormat = "TTF";
}
// Check OTF signature: "OTTO" (0x4F 0x54 0x54 0x4F)
else if (header[0] == 0x4F && header[1] == 0x54 && header[2] == 0x54 && header[3] == 0x4F) {
isValid = (expectedFormat == FontFormat.OTF);
detectedFormat = "OTF";
}
// Check WOFF signature: "wOFF" (0x77 0x4F 0x46 0x46)
else if (header[0] == 0x77 && header[1] == 0x4F && header[2] == 0x46 && header[3] == 0x46) {
isValid = (expectedFormat == FontFormat.WOFF);
detectedFormat = "WOFF";
}
// Check WOFF2 signature: "wOF2" (0x77 0x4F 0x46 0x32)
else if (header[0] == 0x77 && header[1] == 0x4F && header[2] == 0x46 && header[3] == 0x32) {
isValid = (expectedFormat == FontFormat.WOFF2);
detectedFormat = "WOFF2";
}
if (!isValid) {
log.error("Font file magic bytes validation failed. Expected: {}, Detected: {}", expectedFormat, detectedFormat);
if (detectedFormat != expectedFormat) {
log.error("Font file MIME validation failed. Expected: {}, Detected MIME: {} (mapped: {})",
expectedFormat, detectedMime, detectedFormat);
throw new IllegalArgumentException(
String.format("Invalid font file format. File appears to be %s but extension indicates %s",
detectedFormat, expectedFormat)
String.format("Invalid font file format. File appears to be %s but extension indicates %s",
detectedFormat != null ? detectedFormat : "Unknown", expectedFormat)
);
}
log.debug("Font file magic bytes validated successfully: {}", detectedFormat);
log.debug("Font file validated successfully via Tika: {} (MIME: {})", detectedFormat, detectedMime);
}
/**
@@ -1,5 +1,7 @@
package org.booklore.service.file;
import org.booklore.util.FileUtils;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.file.Files;
@@ -14,8 +16,9 @@ public class FileFingerprint {
public static String generateHash(Path filePath) {
final long base = 1024L;
final int blockSize = 1024;
Path normalizedFilePath = validateReadableFilePath(filePath);
try (RandomAccessFile raf = new RandomAccessFile(filePath.toFile(), "r")) {
try (RandomAccessFile raf = new RandomAccessFile(normalizedFilePath.toFile(), "r")) {
MessageDigest md5 = MessageDigest.getInstance("MD5");
byte[] buffer = new byte[blockSize];
@@ -38,7 +41,7 @@ public class FileFingerprint {
return result.toString();
} catch (IOException | NoSuchAlgorithmException e) {
throw new RuntimeException("Failed to compute partial MD5 hash for: " + filePath, e);
throw new RuntimeException("Failed to compute partial MD5 hash for input file", e);
}
}
@@ -47,22 +50,19 @@ public class FileFingerprint {
* Uses the first audio file's hash combined with the file count.
*/
public static String generateFolderHash(Path folderPath) {
Path normalizedFolderPath = validateReadableFolderPath(folderPath);
try {
if (!Files.exists(folderPath) || !Files.isDirectory(folderPath)) {
throw new RuntimeException("Folder does not exist: " + folderPath);
}
List<Path> audioFiles;
try (var files = Files.list(folderPath)) {
try (var files = Files.list(normalizedFolderPath)) {
audioFiles = files
.filter(Files::isRegularFile)
.filter(p -> isAudioFile(p.getFileName().toString()))
.filter(p -> FileUtils.isAudioFile(p.getFileName().toString()))
.sorted(Comparator.comparing(p -> p.getFileName().toString()))
.toList();
}
if (audioFiles.isEmpty()) {
throw new RuntimeException("No audio files in folder: " + folderPath);
throw new RuntimeException("No audio files found in folder");
}
// Hash first file and combine with file count for a representative hash
@@ -81,13 +81,34 @@ public class FileFingerprint {
return result.toString();
} catch (IOException | NoSuchAlgorithmException e) {
throw new RuntimeException("Failed to compute folder hash for: " + folderPath, e);
throw new RuntimeException("Failed to compute folder hash", e);
}
}
private static boolean isAudioFile(String fileName) {
if (fileName == null) return false;
String lower = fileName.toLowerCase();
return lower.endsWith(".mp3") || lower.endsWith(".m4a") || lower.endsWith(".m4b") || lower.endsWith(".opus");
private static Path validateReadableFilePath(Path filePath) {
if (filePath == null) {
throw new RuntimeException("File path cannot be null");
}
Path normalizedPath = filePath.toAbsolutePath().normalize();
if (!Files.exists(normalizedPath) || !Files.isRegularFile(normalizedPath)) {
throw new RuntimeException("File does not exist or is not a regular file");
}
return normalizedPath;
}
private static Path validateReadableFolderPath(Path folderPath) {
if (folderPath == null) {
throw new RuntimeException("Folder path cannot be null");
}
Path normalizedPath = folderPath.toAbsolutePath().normalize();
if (!Files.exists(normalizedPath) || !Files.isDirectory(normalizedPath)) {
throw new RuntimeException("Folder does not exist or is not a directory");
}
return normalizedPath;
}
}
@@ -6,6 +6,7 @@ import org.springframework.stereotype.Service;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
@@ -23,7 +24,20 @@ public class PathService {
);
public List<String> getFoldersAtPath(String path) {
Path directory = Paths.get(path).toAbsolutePath().normalize();
if (path == null || path.isBlank() || path.indexOf('\0') >= 0) {
log.warn("Blocked invalid path input");
throw ApiError.GENERIC_BAD_REQUEST.createException("Invalid path");
}
final Path rawPath;
try {
rawPath = Paths.get(path.trim());
} catch (InvalidPathException e) {
log.warn("Invalid path syntax: {}", path);
throw ApiError.GENERIC_BAD_REQUEST.createException("Invalid path");
}
Path directory = rawPath.toAbsolutePath().normalize();
String normalized = directory.toString();
if (BLOCKED_PATHS.stream().anyMatch(blocked -> normalized.equals(blocked) || normalized.startsWith(blocked + "/"))) {
@@ -7,6 +7,7 @@ import org.booklore.model.entity.TagEntity;
import org.booklore.service.ArchiveService;
import org.booklore.util.ArchiveUtils;
import org.booklore.util.FileService;
import org.booklore.util.MimeDetector;
import freemarker.cache.ClassTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
@@ -247,14 +248,13 @@ public class CbxConversionService {
}
private boolean isJpegFile(Path path) {
Set<String> jpegExtensions = Set.of(".jpg", ".jpeg");
String fileName = path.getFileName().toString().toLowerCase();
int lastDot = fileName.lastIndexOf('.');
if (lastDot > 0) {
String extension = fileName.substring(lastDot);
return jpegExtensions.contains(extension);
try {
String mime = MimeDetector.detect(path);
return "image/jpeg".equals(mime);
} catch (IOException e) {
log.debug("Failed to detect MIME for {}: {}", path, e.getMessage());
return false;
}
return false;
}
private void addMimetypeEntry(ZipArchiveOutputStream zipOut) throws IOException {
@@ -22,12 +22,14 @@ import org.booklore.service.metadata.writer.MetadataWriter;
import org.booklore.service.metadata.writer.MetadataWriterFactory;
import org.booklore.util.BookCoverUtils;
import org.booklore.util.FileService;
import org.booklore.util.MimeDetector;
import org.booklore.config.AppProperties;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
@@ -492,14 +494,19 @@ public class BookCoverService {
if (file.isEmpty()) {
throw ApiError.INVALID_INPUT.createException("Uploaded file is empty");
}
String contentType = file.getContentType();
if (contentType == null || (!contentType.toLowerCase().startsWith("image/jpeg") && !contentType.toLowerCase().startsWith("image/png"))) {
throw ApiError.INVALID_INPUT.createException("Only JPEG and PNG files are allowed");
}
long maxFileSize = 5L * 1024 * 1024;
if (file.getSize() > maxFileSize) {
throw ApiError.FILE_TOO_LARGE.createException(5);
}
// Detect MIME from content byte never trust the client-supplied Content-Type header
try (var inputStream = file.getInputStream()) {
String detectedMime = MimeDetector.detect(inputStream);
if (!"image/jpeg".equals(detectedMime) && !"image/png".equals(detectedMime)) {
throw ApiError.INVALID_INPUT.createException("Only JPEG and PNG files are allowed (detected: " + detectedMime + ")");
}
} catch (IOException e) {
throw ApiError.INVALID_INPUT.createException("Failed to read uploaded file for MIME detection");
}
}
private byte[] extractBytesFromMultipartFile(MultipartFile file) {
@@ -6,13 +6,11 @@ import org.booklore.model.dto.BookMetadata;
import org.booklore.model.dto.ComicMetadata;
import org.booklore.service.ArchiveService;
import org.springframework.stereotype.Component;
import org.booklore.util.SecureXmlUtils;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import javax.imageio.ImageIO;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
@@ -68,34 +66,8 @@ public class CbxMetadataExtractor implements FileMetadataExtractor {
return BookMetadata.builder().title(baseName).build();
}
/**
* Builds a secure XML document parser with protection against XXE attacks.
* Configures the DocumentBuilderFactory with security features to prevent:
* - External entity injection
* - DTD processing vulnerabilities
* - Schema injection attacks
*
* @param is InputStream containing XML data to parse
* @return Parsed Document object
* @throws Exception if XML parsing fails or security features cannot be configured
*/
private Document buildSecureDocument(InputStream is) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true); // Enable namespace awareness
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
try {
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
} catch (Exception ex) {
log.warn("XML factory secure features not supported, XXE protection may be compromised: {}", ex.getMessage());
throw ex; // Re-throw to fail fast if security features can't be enabled
}
factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
factory.setExpandEntityReferences(false);
DocumentBuilder builder = factory.newDocumentBuilder();
return builder.parse(is);
return SecureXmlUtils.createSecureDocumentBuilder(true).parse(is);
}
/**
@@ -23,6 +23,7 @@ import org.springframework.stereotype.Component;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.Comparator;
@@ -213,7 +214,7 @@ public class CbxMetadataWriter implements MetadataWriter {
// CommunityRating - normalized to 0-5 scale
helper.copyRating(false, rating -> {
if (rating != null) {
double normalized = Math.min(5.0, Math.max(0.0, rating / 2.0));
double normalized = Math.clamp(rating / 2.0, 0.0, 5.0);
info.setCommunityRating(String.format(Locale.US, "%.1f", normalized));
} else {
info.setCommunityRating(null);
@@ -375,7 +376,7 @@ public class CbxMetadataWriter implements MetadataWriter {
info.setAgeRating(mapAgeRatingToComicInfo(metadata.getAgeRating()));
}
info.setNotes(notesBuilder.length() > 0 ? notesBuilder.toString() : null);
info.setNotes(!notesBuilder.isEmpty() ? notesBuilder.toString() : null);
}
private String getCreatorsByRole(ComicMetadataEntity comic, ComicCreatorRole role) {
@@ -528,17 +529,28 @@ public class CbxMetadataWriter implements MetadataWriter {
return comicInfoFilename.equals(normalized) || normalized.endsWith("/" + comicInfoFilename);
}
private static boolean isPathSafe(String entryName) {
/**
* Validates a ZIP entry name is safe against zip-slip attacks.
* Uses {@link Path#normalize()} to collapse traversal segments and rejects entries
* that are absolute or escape the archive root.
*/
static boolean isPathSafe(String entryName) {
if (entryName == null || entryName.isBlank()) return false;
String normalized = entryName.replace('\\', '/');
if (normalized.startsWith("/")) return false;
if (normalized.contains("\0")) return false;
// Check each path component for ".." traversal. Splitting with -1 limit catches
// trailing separators and avoids missing ".." at the end of a path (e.g. "foo/..").
for (String component : normalized.split("/", -1)) {
if ("..".equals(component)) return false;
if (entryName.contains("\0")) return false;
try {
String sanitized = entryName.replace('\\', '/');
// Reject any entry containing ".." as a path segment even if normalization
// would collapse it to something safe, legitimate ZIP entries never use "..".
for (String segment : sanitized.split("/", -1)) {
if ("..".equals(segment)) return false;
}
Path parsed = Path.of(sanitized).normalize();
return !parsed.isAbsolute()
&& !parsed.toString().isEmpty()
&& !parsed.startsWith("..");
} catch (InvalidPathException e) {
return false;
}
return true;
}
private void rebuildArchiveWithNewXml(Path sourceArchive, Path targetZip, byte[] xmlContent) throws Exception {
@@ -632,4 +644,4 @@ public class CbxMetadataWriter implements MetadataWriter {
sb.append("[BookLore:").append(tag).append("] ").append(formatted);
}
}
}
}
@@ -2,6 +2,7 @@ package org.booklore.service.migration.migrations;
import org.booklore.service.migration.Migration;
import org.booklore.util.FileService;
import org.booklore.util.FileUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.Resource;
@@ -41,6 +42,7 @@ public class MoveIconsToDataFolderMigration implements Migration {
String targetFolder = fileService.getIconsSvgFolder();
Path targetDir = Paths.get(targetFolder);
Files.createDirectories(targetDir);
Path normalizedTargetDir = FileUtils.normalizeAbsolutePath(targetDir);
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource[] resources = resolver.getResources("classpath:static/images/icons/svg/*.svg");
@@ -50,7 +52,18 @@ public class MoveIconsToDataFolderMigration implements Migration {
String filename = resource.getFilename();
if (filename == null) continue;
Path targetFile = targetDir.resolve(filename);
if (filename.contains("/") || filename.contains("\\") || filename.contains("..")) {
log.warn("Skipping suspicious icon filename during migration: {}", filename);
continue;
}
Path targetFile;
try {
targetFile = FileUtils.resolvePathWithinBase(normalizedTargetDir, filename);
} catch (IllegalArgumentException ex) {
log.warn("Skipping icon outside target directory: {}", filename);
continue;
}
try (var inputStream = resource.getInputStream()) {
Files.copy(inputStream, targetFile, StandardCopyOption.REPLACE_EXISTING);
@@ -3,6 +3,7 @@ package org.booklore.service.opds;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.text.StringEscapeUtils;
import org.booklore.config.security.service.AuthenticationService;
import org.booklore.exception.ApiError;
import org.booklore.config.security.userdetails.OpdsUserDetails;
@@ -16,8 +17,9 @@ import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import java.io.File;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@@ -29,6 +31,9 @@ public class OpdsFeedService {
private static final int DEFAULT_PAGE_SIZE = 50;
private static final int MAX_PAGE_SIZE = 100;
private static final List<String> PAGINATION_QUERY_WHITELIST = List.of(
"q", "libraryId", "shelfId", "shelfIds", "magicShelfId", "author", "series"
);
private final AuthenticationService authenticationService;
private final OpdsBookService opdsBookService;
@@ -358,7 +363,7 @@ public class OpdsFeedService {
<link rel="start" href="/api/v1/opds" type="application/atom+xml;profile=opds-catalog;kind=navigation"/>
<link rel="search" type="application/opensearchdescription+xml" title="Search" href="/api/v1/opds/search.opds"/>
""".formatted(
feedId,
escapeXml(feedId),
escapeXml(feedTitle),
now(),
booksPage.getTotalElements(),
@@ -472,11 +477,16 @@ public class OpdsFeedService {
String url = request.getRequestURI();
StringBuilder result = new StringBuilder(url).append("?");
String queryString = request.getQueryString();
if (queryString != null) {
Arrays.stream(queryString.split("&"))
.filter(param -> !param.startsWith("page=") && !param.startsWith("size="))
.forEach(param -> result.append(param).append("&"));
for (String key : PAGINATION_QUERY_WHITELIST) {
String value = request.getParameter(key);
if (value == null || value.isBlank()) {
continue;
}
result.append(URLEncoder.encode(key, StandardCharsets.UTF_8))
.append("=")
.append(URLEncoder.encode(value, StandardCharsets.UTF_8))
.append("&");
}
result.append("page=").append(page).append("&size=").append(size);
@@ -694,12 +704,7 @@ public class OpdsFeedService {
}
private String escapeXml(String input) {
return input == null ? "" :
input.replace("&", "&amp;")
.replace("<", "&lt;")
.replace(">", "&gt;")
.replace("\"", "&quot;")
.replace("'", "&apos;");
return input == null ? "" : StringEscapeUtils.escapeXml10(input);
}
private Long parseLongParam(HttpServletRequest request, String name, Long defaultValue) {
@@ -1,6 +1,7 @@
package org.booklore.service.reader;
import lombok.extern.slf4j.Slf4j;
import org.booklore.util.MimeDetector;
import org.springframework.stereotype.Service;
import java.io.IOException;
@@ -49,18 +50,10 @@ public class AudioFileUtilityService {
}
/**
* Get the MIME content type for an audio file.
* Get the MIME content type for an audio file using content-based detection via Apache Tika.
*/
public String getContentType(Path audioPath) {
String fileName = audioPath.getFileName().toString().toLowerCase();
if (fileName.endsWith(".m4b") || fileName.endsWith(".m4a")) {
return "audio/mp4";
} else if (fileName.endsWith(".mp3")) {
return "audio/mpeg";
} else if (fileName.endsWith(".opus")) {
return "audio/opus";
}
return "application/octet-stream";
return MimeDetector.detectSafe(audioPath);
}
/**
@@ -3,6 +3,7 @@ package org.booklore.service.upload;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.booklore.config.AppProperties;
import org.booklore.exception.APIException;
import org.booklore.exception.ApiError;
import org.booklore.mapper.AdditionalFileMapper;
import org.booklore.model.dto.Book;
@@ -21,6 +22,7 @@ import org.booklore.service.appsettings.AppSettingService;
import org.booklore.service.file.FileFingerprint;
import org.booklore.service.file.FileMovingHelper;
import org.booklore.service.metadata.extractor.MetadataExtractorFactory;
import org.booklore.util.FileUtils;
import org.booklore.service.monitoring.MonitoringRegistrationService;
import org.booklore.util.PathPatternResolver;
import org.springframework.util.StringUtils;
@@ -33,7 +35,6 @@ import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant;
import java.util.Optional;
import org.booklore.model.enums.AuditAction;
@@ -66,6 +67,7 @@ public class FileUploadService {
final LibraryEntity libraryEntity = findLibraryById(libraryId);
final LibraryPathEntity libraryPathEntity = findLibraryPathById(libraryEntity, pathId);
final Path libraryRoot = FileUtils.normalizeAbsolutePath(Path.of(libraryPathEntity.getPath()));
final String originalFileName = getValidatedFileName(file);
final BookFileExtension fileExtension = getFileExtension(originalFileName);
validateAllowedFormat(libraryEntity, fileExtension.getType());
@@ -78,10 +80,10 @@ public class FileUploadService {
final String uploadPattern = fileMovingHelper.getFileNamingPattern(libraryEntity);
final String relativePath = PathPatternResolver.resolvePattern(metadata, uploadPattern, originalFileName);
final Path finalPath = Paths.get(libraryPathEntity.getPath(), relativePath);
final Path finalPath = resolvePathWithinRoot(libraryRoot, relativePath);
validateFinalPath(finalPath);
moveFileToFinalLocation(tempPath, finalPath);
validateFinalPath(finalPath, libraryRoot);
moveFileToFinalLocation(tempPath, finalPath, libraryRoot);
log.info("File uploaded to final location: {}", finalPath);
auditService.log(AuditAction.BOOK_UPLOADED, "Library", libraryId, "Uploaded file: " + originalFileName);
@@ -114,6 +116,7 @@ public class FileUploadService {
}
final Path finalPath;
final Path finalRootPath;
final String finalFileName;
final String fileSubPath;
final BookFileType effectiveBookType;
@@ -128,19 +131,23 @@ public class FileUploadService {
String pattern = fileMovingHelper.getFileNamingPattern(book.getLibrary());
String resolvedRelativePath = PathPatternResolver.resolvePattern(book.getMetadata(), pattern, sanitizedFileName);
finalFileName = Paths.get(resolvedRelativePath).getFileName().toString();
fileSubPath = Paths.get(resolvedRelativePath).getParent() != null
? Paths.get(resolvedRelativePath).getParent().toString()
Path safeRelativePath = toSafeRelativePath(resolvedRelativePath);
finalFileName = safeRelativePath.getFileName().toString();
fileSubPath = safeRelativePath.getParent() != null
? safeRelativePath.getParent().toString()
: "";
finalPath = Paths.get(libraryPath.getPath(), resolvedRelativePath);
finalRootPath = FileUtils.normalizeAbsolutePath(Path.of(libraryPath.getPath()));
finalPath = resolvePathWithinRoot(finalRootPath, safeRelativePath.toString());
String extension = sanitizedFileName.substring(sanitizedFileName.lastIndexOf('.') + 1);
effectiveBookType = BookFileType.fromExtension(extension)
.orElseThrow(() -> ApiError.INVALID_FILE_FORMAT.createException("Unsupported book file extension: " + extension));
} else if (isBook) {
String pattern = fileMovingHelper.getFileNamingPattern(book.getLibrary());
String resolvedRelativePath = PathPatternResolver.resolvePattern(book.getMetadata(), pattern, sanitizedFileName);
finalFileName = Paths.get(resolvedRelativePath).getFileName().toString();
Path safeRelativePath = toSafeRelativePath(resolvedRelativePath);
finalFileName = safeRelativePath.getFileName().toString();
fileSubPath = book.getPrimaryBookFile().getFileSubPath();
finalRootPath = FileUtils.normalizeAbsolutePath(Path.of(book.getLibraryPath().getPath()));
finalPath = buildAdditionalFilePath(book, finalFileName);
String extension = sanitizedFileName.substring(sanitizedFileName.lastIndexOf('.') + 1);
effectiveBookType = BookFileType.fromExtension(extension)
@@ -148,17 +155,18 @@ public class FileUploadService {
} else {
finalFileName = sanitizedFileName;
fileSubPath = book.getPrimaryBookFile().getFileSubPath();
finalRootPath = FileUtils.normalizeAbsolutePath(Path.of(book.getLibraryPath().getPath()));
finalPath = buildAdditionalFilePath(book, sanitizedFileName);
effectiveBookType = bookType;
}
validateFinalPath(finalPath);
validateFinalPath(finalPath, finalRootPath);
if (libraryId != null) {
log.debug("Unregistering library {} for monitoring", libraryId);
monitoringRegistrationService.unregisterLibrary(libraryId);
monitoringUnregistered = true;
}
moveFileToFinalLocation(tempPath, finalPath);
moveFileToFinalLocation(tempPath, finalPath, finalRootPath);
log.info("Additional file uploaded to final location: {}", finalPath);
@@ -214,7 +222,7 @@ public class FileUploadService {
public Book uploadFileBookDrop(MultipartFile file) throws IOException {
validateFile(file);
final Path dropFolder = Paths.get(appProperties.getBookdropFolder());
final Path dropFolder = FileUtils.normalizeAbsolutePath(Path.of(appProperties.getBookdropFolder()));
Files.createDirectories(dropFolder);
final String originalFilename = getValidatedFileName(file);
@@ -225,9 +233,9 @@ public class FileUploadService {
tempPath = createTempFile(BOOKDROP_TEMP_PREFIX, sanitizedFilename);
file.transferTo(tempPath);
final Path finalPath = dropFolder.resolve(sanitizedFilename);
validateFinalPath(finalPath);
Files.move(tempPath, finalPath);
final Path finalPath = resolvePathWithinRoot(dropFolder, sanitizedFilename);
validateFinalPath(finalPath, dropFolder);
moveFileToFinalLocation(tempPath, finalPath, dropFolder);
log.info("File moved to book-drop folder: {}", finalPath);
return null;
@@ -283,15 +291,19 @@ public class FileUploadService {
return Files.createTempFile(prefix, suffix);
}
private void validateFinalPath(Path finalPath) {
if (Files.exists(finalPath)) {
private void validateFinalPath(Path finalPath, Path expectedRoot) {
Path safeFinalPath = requirePathWithinRoot(finalPath, expectedRoot, "Invalid upload target path");
if (Files.exists(safeFinalPath)) {
throw ApiError.FILE_ALREADY_EXISTS.createException();
}
}
private void moveFileToFinalLocation(Path sourcePath, Path targetPath) throws IOException {
Files.createDirectories(targetPath.getParent());
Files.move(sourcePath, targetPath);
private void moveFileToFinalLocation(Path sourcePath, Path targetPath, Path expectedRoot) throws IOException {
Path safeSourcePath = requirePathWithinSystemTemp(sourcePath);
Path safeTargetPath = requirePathWithinRoot(targetPath, expectedRoot, "Invalid upload target path");
Files.createDirectories(safeTargetPath.getParent());
Files.move(safeSourcePath, safeTargetPath);
}
private void validateAlternativeFormatDuplicate(String fileHash) {
@@ -303,35 +315,86 @@ public class FileUploadService {
private Path buildAdditionalFilePath(BookEntity book, String fileName) {
final BookFileEntity primaryFile = book.getPrimaryBookFile();
return Paths.get(book.getLibraryPath().getPath(), primaryFile.getFileSubPath(), fileName);
}
private BookFileEntity createAdditionalFileEntity(BookEntity book, String fileName, boolean isBook, BookFileType bookType, long fileSize, String fileHash, String description) {
final BookFileEntity primaryFile = book.getPrimaryBookFile();
return BookFileEntity.builder()
.book(book)
.fileName(fileName)
.fileSubPath(primaryFile.getFileSubPath())
.isBookFormat(isBook)
.bookType(bookType)
.fileSizeKb(fileSize / BYTES_TO_KB_DIVISOR)
.initialHash(fileHash)
.currentHash(fileHash)
.description(description)
.addedOn(Instant.now())
.build();
final Path libraryRoot = FileUtils.normalizeAbsolutePath(Path.of(book.getLibraryPath().getPath()));
final String safeRelativePath = buildSafeRelativePath(primaryFile.getFileSubPath(), fileName);
return resolvePathWithinRoot(libraryRoot, safeRelativePath);
}
private void cleanupTempFile(Path tempPath) {
if (tempPath != null) {
try {
Files.deleteIfExists(tempPath);
Path safeTempPath = requirePathWithinSystemTemp(tempPath);
Files.deleteIfExists(safeTempPath);
} catch (RuntimeException e) {
log.warn("Skipping cleanup for suspicious temp file path: {}", tempPath);
} catch (IOException e) {
log.warn("Failed to cleanup temp file: {}", tempPath, e);
}
}
}
private Path resolvePathWithinRoot(Path rootPath, String relativePath) {
try {
return FileUtils.resolvePathWithinBase(rootPath, relativePath);
} catch (IllegalArgumentException e) {
throw ApiError.GENERIC_BAD_REQUEST.createException("Invalid upload target path");
}
}
private Path toSafeRelativePath(String relativePath) {
if (!StringUtils.hasText(relativePath)) {
throw ApiError.GENERIC_BAD_REQUEST.createException("Invalid upload target path");
}
try {
Path parsed = Path.of(relativePath);
if (parsed.isAbsolute()) {
throw ApiError.GENERIC_BAD_REQUEST.createException("Invalid upload target path");
}
Path normalized = parsed.normalize();
if (normalized.getNameCount() == 0 || normalized.startsWith("..")) {
throw ApiError.GENERIC_BAD_REQUEST.createException("Invalid upload target path");
}
return normalized;
} catch (APIException e) {
throw e;
} catch (RuntimeException e) {
throw ApiError.GENERIC_BAD_REQUEST.createException("Invalid upload target path");
}
}
private String buildSafeRelativePath(String subPath, String fileName) {
Path safeFileNamePath = toSafeRelativePath(fileName);
if (safeFileNamePath.getNameCount() != 1) {
throw ApiError.GENERIC_BAD_REQUEST.createException("Invalid upload target path");
}
if (!StringUtils.hasText(subPath)) {
return safeFileNamePath.toString();
}
Path safeSubPath = toSafeRelativePath(subPath);
Path combined = safeSubPath.resolve(safeFileNamePath).normalize();
if (combined.isAbsolute() || combined.startsWith("..")) {
throw ApiError.GENERIC_BAD_REQUEST.createException("Invalid upload target path");
}
return combined.toString();
}
private Path requirePathWithinRoot(Path candidatePath, Path rootPath, String errorMessage) {
try {
return FileUtils.requirePathWithinBase(candidatePath, rootPath);
} catch (IllegalArgumentException e) {
throw ApiError.GENERIC_BAD_REQUEST.createException(errorMessage);
}
}
private Path requirePathWithinSystemTemp(Path candidatePath) {
Path tempRoot = FileUtils.normalizeAbsolutePath(Path.of(System.getProperty("java.io.tmpdir")));
return requirePathWithinRoot(candidatePath, tempRoot, "Invalid temporary file path");
}
private BookMetadata extractMetadata(BookFileExtension fileExt, File file, String originalFileName) {
BookMetadata metadata = metadataExtractorFactory.extractMetadata(fileExt, file);
@@ -4,6 +4,7 @@ import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import java.io.*;
import java.nio.file.Path;
@Slf4j
@UtilityClass
@@ -16,37 +17,20 @@ public class ArchiveUtils {
UNKNOWN
}
private static final byte[] ZIP_MAGIC = {0x50, 0x4B, 0x03, 0x04};
// RAR 5.0 signature: 0x52 0x61 0x72 0x21 0x1A 0x07 0x01 0x00
private static final byte[] RAR_MAGIC_V5 = {0x52, 0x61, 0x72, 0x21, 0x1A, 0x07, 0x01, 0x00};
// RAR 4.x signature: 0x52 0x61 0x72 0x21 0x1A 0x07 0x00
private static final byte[] RAR_MAGIC_V4 = {0x52, 0x61, 0x72, 0x21, 0x1A, 0x07, 0x00};
// Generic RAR signature (first 4 bytes): 0x52 0x61 0x72 0x21
private static final byte[] SEVEN_ZIP_MAGIC = {0x37, 0x7A, (byte) 0xBC, (byte) 0xAF, 0x27, 0x1C};
/**
* Detects the archive type of a file using content-based MIME detection via Apache Tika.
* Falls back to extension-based detection only when Tika cannot determine the type.
*/
public static ArchiveType detectArchiveType(File file) {
if (file == null || !file.exists() || !file.isFile()) {
return ArchiveType.UNKNOWN;
}
try (InputStream is = new BufferedInputStream(new FileInputStream(file))) {
byte[] buffer = new byte[8];
int bytesRead = is.read(buffer);
if (bytesRead < 4) {
return detectArchiveTypeByExtension(file.getName());
}
if (startsWith(buffer, ZIP_MAGIC)) {
return ArchiveType.ZIP;
}
if (startsWith(buffer, RAR_MAGIC_V5)) {
return ArchiveType.RAR;
}
if (startsWith(buffer, RAR_MAGIC_V4)) {
return ArchiveType.RAR;
}
if (startsWith(buffer, SEVEN_ZIP_MAGIC)) {
return ArchiveType.SEVEN_ZIP;
try {
String mime = MimeDetector.detect(file.toPath());
ArchiveType fromContent = mapMimeToArchiveType(mime);
if (fromContent != ArchiveType.UNKNOWN) {
return fromContent;
}
} catch (IOException e) {
log.warn("Failed to detect archive type by content for file: {}", file.getAbsolutePath());
@@ -55,6 +39,10 @@ public class ArchiveUtils {
return detectArchiveTypeByExtension(file.getName());
}
public static ArchiveType detectArchiveType(Path path) {
return detectArchiveType(path.toFile());
}
public static ArchiveType detectArchiveTypeByExtension(String fileName) {
if (fileName == null) {
return ArchiveType.UNKNOWN;
@@ -72,15 +60,15 @@ public class ArchiveUtils {
return ArchiveType.UNKNOWN;
}
private static boolean startsWith(byte[] buffer, byte[] magic) {
if (buffer.length < magic.length) {
return false;
}
for (int i = 0; i < magic.length; i++) {
if (buffer[i] != magic[i]) {
return false;
}
}
return true;
private static ArchiveType mapMimeToArchiveType(String mime) {
if (mime == null) return ArchiveType.UNKNOWN;
// Tika MIME types:
// ZIP: application/zip
// RAR: application/x-rar-compressed or application/vnd.rar
// 7z: application/x-7z-compressed
if (mime.contains("zip")) return ArchiveType.ZIP;
if (mime.contains("rar")) return ArchiveType.RAR;
if (mime.contains("7z")) return ArchiveType.SEVEN_ZIP;
return ArchiveType.UNKNOWN;
}
}
@@ -24,6 +24,116 @@ public class FileUtils {
private final String FILE_NOT_FOUND_MESSAGE = "File does not exist: ";
/**
* Normalize a path to its absolute form with all {@code .} and {@code ..} segments resolved.
* Delegates to {@link Path#toAbsolutePath()} and {@link Path#normalize()}.
*/
public Path normalizeAbsolutePath(Path path) {
if (path == null) {
throw new IllegalArgumentException("Path cannot be null");
}
return path.toAbsolutePath().normalize();
}
/**
* Require that {@code candidatePath} resolves within {@code basePath}.
* <p>
* Uses the standard JDK approach: {@link Path#normalize()} + {@link Path#startsWith(Path)}
* for logical containment, then {@link Path#toRealPath()} to resolve symlinks on existing
* paths. Rejects null-byte injection via {@link Path#of} (JDK throws InvalidPathException).
*
* @throws IllegalArgumentException if the candidate escapes the base
*/
public Path requirePathWithinBase(Path candidatePath, Path basePath) {
if (basePath == null || candidatePath == null) {
throw new IllegalArgumentException("Base path and candidate path cannot be null");
}
Path normalizedBase = basePath.toAbsolutePath().normalize();
Path normalizedCandidate = candidatePath.toAbsolutePath().normalize();
if (!normalizedCandidate.startsWith(normalizedBase)) {
throw new IllegalArgumentException("Resolved path escapes configured base path");
}
verifyRealPathWithinBase(normalizedCandidate, normalizedBase);
return normalizedCandidate;
}
/**
* Resolve a user-supplied relative path against a trusted base and verify containment.
* <p>
* Uses {@link Path#resolve(Path)} + {@link Path#normalize()} + {@link Path#startsWith(Path)},
* the standard JDK pattern for safe path resolution. Any {@code ..} segments that escape the
* base are caught by the {@code startsWith} check after normalization.
*
* @throws IllegalArgumentException if the relative path is absolute, blank, or escapes the base
*/
public Path resolvePathWithinBase(Path basePath, String relativePath) {
if (relativePath == null || relativePath.isBlank()) {
throw new IllegalArgumentException("Relative path cannot be blank");
}
Path normalizedBase = basePath.toAbsolutePath().normalize();
Path rawRelative = Path.of(relativePath);
if (rawRelative.isAbsolute()) {
throw new IllegalArgumentException("Relative path must not be absolute");
}
Path resolved = normalizedBase.resolve(rawRelative).normalize();
if (!resolved.startsWith(normalizedBase)) {
throw new IllegalArgumentException("Resolved path escapes configured base path");
}
verifyRealPathWithinBase(resolved, normalizedBase);
return resolved;
}
/**
* After the logical {@code startsWith} check passes, resolve symlinks on the nearest existing
* ancestor via {@link Path#toRealPath()} and verify it still falls within the base.
* This prevents symlink-based escapes where a link inside the base points outside it.
*/
private void verifyRealPathWithinBase(Path normalizedCandidate, Path normalizedBase) {
try {
if (!Files.exists(normalizedBase)) {
return;
}
Path realBase = normalizedBase.toRealPath();
// Explicit symlink target check, catches broken symlinks that toRealPath cannot follow
if (Files.isSymbolicLink(normalizedCandidate)) {
Path linkTarget = Files.readSymbolicLink(normalizedCandidate);
Path resolvedTarget = linkTarget.isAbsolute()
? linkTarget.normalize()
: normalizedCandidate.getParent().resolve(linkTarget).normalize();
if (!resolvedTarget.startsWith(realBase)) {
throw new IllegalArgumentException("Symlink target escapes configured base path");
}
}
// Walk up to the first existing ancestor and verify its real path
Path anchor = normalizedCandidate;
while (anchor != null && !Files.exists(anchor)) {
anchor = anchor.getParent();
}
if (anchor == null) {
return;
}
Path realAnchor = anchor.toRealPath();
if (!realAnchor.startsWith(realBase)) {
throw new IllegalArgumentException("Resolved real path escapes configured base path");
}
} catch (IllegalArgumentException e) {
throw e;
} catch (IOException e) {
throw new IllegalArgumentException("Failed to resolve filesystem path for validation", e);
}
}
public Path getBookFullPath(BookEntity bookEntity) {
BookFileEntity bookFile = bookEntity.getPrimaryBookFile();
return getBookFullPath(bookEntity, bookFile);
@@ -0,0 +1,78 @@
package org.booklore.util;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import org.apache.tika.Tika;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
@Slf4j
@UtilityClass
public class MimeDetector {
// Tika is thread-safe one instance for the whole app.
private static final Tika TIKA = new Tika();
/**
* Detects MIME type purely from content bytes, never from the filename.
* Uses buffered stream; reads only the magic-byte prefix.
*
* @return the detected MIME type, or {@code "application/octet-stream"} on failure
*/
public String detect(Path path) throws IOException {
try (InputStream in = Files.newInputStream(path)) {
return TIKA.detect(in);
}
}
/**
* Detects MIME type from an already-open input stream.
* The stream must support mark/reset (buffered streams do).
*/
public String detect(InputStream inputStream) throws IOException {
return TIKA.detect(inputStream); // content-only
}
/**
* Best-effort detection that returns {@code "application/octet-stream"} instead of throwing.
*/
public String detectSafe(Path path) {
try {
return detect(path);
} catch (IOException e) {
log.warn("MIME detection failed for {}: {}", path, e.getMessage());
return "application/octet-stream";
}
}
public boolean isAudio(Path path) throws IOException {
return detect(path).startsWith("audio/");
}
public boolean isImage(Path path) throws IOException {
return detect(path).startsWith("image/");
}
public boolean isImage(String mime) {
return mime != null && mime.startsWith("image/");
}
public boolean isAudio(String mime) {
return mime != null && mime.startsWith("audio/");
}
public boolean isFont(String mime) {
return mime != null && (mime.startsWith("font/") || mime.startsWith("application/font-")
|| "application/vnd.ms-fontobject".equals(mime));
}
public boolean isArchive(String mime) {
if (mime == null) return false;
return mime.contains("zip") || mime.contains("rar")
|| mime.contains("7z") || mime.contains("x-7z")
|| mime.contains("gzip") || mime.contains("tar");
}
}
@@ -28,6 +28,7 @@ import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.multipart.MultipartFile;
import java.io.ByteArrayInputStream;
import java.util.*;
import java.util.concurrent.Executor;
@@ -396,9 +397,9 @@ class BookCoverServiceTest {
MultipartFile file = mock(MultipartFile.class);
when(file.isEmpty()).thenReturn(false);
when(file.getContentType()).thenReturn("image/jpeg");
when(file.getSize()).thenReturn(1024L);
try {
when(file.getInputStream()).thenReturn(new ByteArrayInputStream(new byte[]{(byte) 0xFF, (byte) 0xD8, (byte) 0xFF, (byte) 0xE0})); // JPEG
when(file.getBytes()).thenReturn(new byte[]{1, 2, 3});
} catch (Exception ignored) {}
@@ -422,10 +423,11 @@ class BookCoverServiceTest {
}
@Test
void rejectsNonImageContentType() {
void rejectsNonImageContentType() throws Exception {
MultipartFile file = mock(MultipartFile.class);
when(file.isEmpty()).thenReturn(false);
when(file.getContentType()).thenReturn("application/pdf");
when(file.getSize()).thenReturn(1024L);
when(file.getInputStream()).thenReturn(new java.io.ByteArrayInputStream(new byte[]{1, 2, 3}));
assertThatThrownBy(() -> service.updateCoverFromFileForBooks(Set.of(1L), file))
.isInstanceOf(APIException.class)
@@ -436,7 +438,6 @@ class BookCoverServiceTest {
void rejectsFileLargerThan5MB() {
MultipartFile file = mock(MultipartFile.class);
when(file.isEmpty()).thenReturn(false);
when(file.getContentType()).thenReturn("image/jpeg");
when(file.getSize()).thenReturn(6L * 1024 * 1024);
assertThatThrownBy(() -> service.updateCoverFromFileForBooks(Set.of(1L), file))
@@ -448,9 +449,9 @@ class BookCoverServiceTest {
void acceptsJpegFile() {
MultipartFile file = mock(MultipartFile.class);
when(file.isEmpty()).thenReturn(false);
when(file.getContentType()).thenReturn("image/jpeg");
when(file.getSize()).thenReturn(1024L);
try {
when(file.getInputStream()).thenReturn(new java.io.ByteArrayInputStream(new byte[]{(byte) 0xFF, (byte) 0xD8, (byte) 0xFF, (byte) 0xE0}));
when(file.getBytes()).thenReturn(new byte[]{1, 2, 3});
} catch (Exception ignored) {}
@@ -463,9 +464,9 @@ class BookCoverServiceTest {
void acceptsPngFile() {
MultipartFile file = mock(MultipartFile.class);
when(file.isEmpty()).thenReturn(false);
when(file.getContentType()).thenReturn("image/png");
when(file.getSize()).thenReturn(1024L);
try {
when(file.getInputStream()).thenReturn(new java.io.ByteArrayInputStream(new byte[]{(byte) 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A}));
when(file.getBytes()).thenReturn(new byte[]{1, 2, 3});
} catch (Exception ignored) {}
@@ -475,13 +476,15 @@ class BookCoverServiceTest {
}
@Test
void rejectsNullContentType() {
void rejectsIOExceptionOnRead() throws Exception {
MultipartFile file = mock(MultipartFile.class);
when(file.isEmpty()).thenReturn(false);
when(file.getContentType()).thenReturn(null);
when(file.getSize()).thenReturn(1024L);
when(file.getInputStream()).thenThrow(new java.io.IOException("Test error"));
assertThatThrownBy(() -> service.updateCoverFromFileForBooks(Set.of(1L), file))
.isInstanceOf(APIException.class);
.isInstanceOf(APIException.class)
.hasMessageContaining("Failed to read");
}
}
@@ -710,8 +713,8 @@ class BookCoverServiceTest {
MultipartFile file = mock(MultipartFile.class);
when(file.isEmpty()).thenReturn(false);
when(file.getContentType()).thenReturn("image/png");
when(file.getSize()).thenReturn(1024L);
when(file.getInputStream()).thenReturn(new java.io.ByteArrayInputStream(new byte[]{(byte) 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A}));
when(file.getBytes()).thenReturn(new byte[]{1, 2, 3});
doAnswer(inv -> {
@@ -13,6 +13,9 @@ import java.nio.file.Path;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.mockStatic;
import org.mockito.MockedStatic;
import org.booklore.util.MimeDetector;
class AudioFileUtilityServiceTest {
@@ -161,7 +164,10 @@ class AudioFileUtilityServiceTest {
})
void getContentType_returnsCorrectMimeType(String filename, String expectedMimeType) {
Path file = tempDir.resolve(filename);
assertEquals(expectedMimeType, audioFileUtility.getContentType(file));
try (MockedStatic<MimeDetector> mockedMime = mockStatic(MimeDetector.class)) {
mockedMime.when(() -> MimeDetector.detectSafe(file)).thenReturn(expectedMimeType);
assertEquals(expectedMimeType, audioFileUtility.getContentType(file));
}
}
@ParameterizedTest
@@ -171,19 +177,28 @@ class AudioFileUtilityServiceTest {
})
void getContentType_isCaseInsensitive(String filename, String expectedMimeType) {
Path file = tempDir.resolve(filename);
assertEquals(expectedMimeType, audioFileUtility.getContentType(file));
try (MockedStatic<MimeDetector> mockedMime = mockStatic(MimeDetector.class)) {
mockedMime.when(() -> MimeDetector.detectSafe(file)).thenReturn(expectedMimeType);
assertEquals(expectedMimeType, audioFileUtility.getContentType(file));
}
}
@Test
void getContentType_returnsOctetStreamForUnknownExtension() {
Path file = tempDir.resolve("unknown.xyz");
assertEquals("application/octet-stream", audioFileUtility.getContentType(file));
try (MockedStatic<MimeDetector> mockedMime = mockStatic(MimeDetector.class)) {
mockedMime.when(() -> MimeDetector.detectSafe(file)).thenReturn("application/octet-stream");
assertEquals("application/octet-stream", audioFileUtility.getContentType(file));
}
}
@Test
void getContentType_returnsOctetStreamForNoExtension() {
Path file = tempDir.resolve("noextension");
assertEquals("application/octet-stream", audioFileUtility.getContentType(file));
try (MockedStatic<MimeDetector> mockedMime = mockStatic(MimeDetector.class)) {
mockedMime.when(() -> MimeDetector.detectSafe(file)).thenReturn("application/octet-stream");
assertEquals("application/octet-stream", audioFileUtility.getContentType(file));
}
}
// ==================== getTrackTitleFromFilename tests ====================