refactor(misc): Harden request handling, tighten defaults, and pin CI deps (#2878)

* refactor(misc): Harden request handling, tighten defaults, and pin CI dependencies

* feat(auth): normalize usernames for login rate limiting

* refactor(epub): fix XML document builder creation

* feat(http): enhance image download with redirect handling and DNS rebinding protection

* chore: upgrade Node.js version to 24 and add frontend dependency audit step

* feat(auth): refactor username normalization for login rate limiting and enhance image download security

* fix(metadata): simplify JAXB validation event handling by using direct import

* chore(pipeline): remove unnecessary --force flag from npm ci and format audit step

* chore(pipeline): streamline frontend dependency audits and add validation step

* fix(image): improve error handling for image processing and download, enforce pixel limits

* test(image): update tests

* fix(icon): update DOMPurify import and replace deprecated theme package

* fix(imports): update theme package imports and format code for consistency

* fix(cors): update allowed origins configuration to support wildcard and trim whitespace
This commit is contained in:
Balázs Szücs
2026-02-24 12:43:14 -07:00
committed by GitHub
parent 161c675f74
commit f3fffeadce
31 changed files with 989 additions and 626 deletions
@@ -3,21 +3,26 @@ package org.booklore.config;
import org.booklore.config.security.interceptor.WebSocketAuthInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import java.util.Arrays;
@Slf4j
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
private final WebSocketAuthInterceptor webSocketAuthInterceptor;
private final Environment env;
public WebSocketConfig(WebSocketAuthInterceptor webSocketAuthInterceptor) {
public WebSocketConfig(WebSocketAuthInterceptor webSocketAuthInterceptor, Environment env) {
this.webSocketAuthInterceptor = webSocketAuthInterceptor;
this.env = env;
}
@Override
@@ -29,8 +34,22 @@ public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws").setAllowedOrigins("*");
log.info("WebSocket endpoint registered at /ws");
String allowedOrigins = env.getProperty("app.cors.allowed-origins", "*").trim();
var endpoint = registry.addEndpoint("/ws");
if ("*".equals(allowedOrigins)) {
endpoint.setAllowedOriginPatterns("*");
log.warn("WebSocket endpoint is configured to allow all origins (*). " +
"This is the default for backward compatibility, but it's recommended to set 'app.cors.allowed-origins' to an explicit list.");
} else if (allowedOrigins.isEmpty()) {
// No explicit origins configured: enforce same-origin check (Spring WebSocket default)
log.info("WebSocket endpoint registered at /ws (same-origin only)");
} else {
String[] origins = Arrays.stream(allowedOrigins.split("\\s*,\\s*"))
.filter(s -> !s.isEmpty())
.toArray(String[]::new);
endpoint.setAllowedOriginPatterns(origins);
log.info("WebSocket endpoint registered at /ws with allowed origins: {}", Arrays.toString(origins));
}
}
@Override
@@ -5,9 +5,11 @@ import org.booklore.config.security.service.OpdsUserDetailsService;
import jakarta.servlet.DispatcherType;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import org.booklore.util.FileService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
@@ -19,21 +21,41 @@ import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.header.writers.ReferrerPolicyHeaderWriter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import lombok.extern.slf4j.Slf4j;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SNIHostName;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Collections;
@Slf4j
@AllArgsConstructor
@EnableMethodSecurity
@Configuration
public class SecurityConfig {
private static final Pattern ALLOWED = Pattern.compile("\\s*,\\s*");
private final OpdsUserDetailsService opdsUserDetailsService;
private final DualJwtAuthenticationFilter dualJwtAuthenticationFilter;
private final Environment env;
private static final String[] COMMON_PUBLIC_ENDPOINTS = {
"/ws/**", // WebSocket connections (auth handled in WebSocketAuthInterceptor)
@@ -197,6 +219,10 @@ public class SecurityConfig {
.cors(cors -> cors.configurationSource(corsConfigurationSource()))
.csrf(AbstractHttpConfigurer::disable)
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.headers(headers -> headers
.referrerPolicy(referrer -> referrer.policy(
ReferrerPolicyHeaderWriter.ReferrerPolicy.STRICT_ORIGIN_WHEN_CROSS_ORIGIN))
)
.authorizeHttpRequests(auth -> auth
.dispatcherTypeMatchers(DispatcherType.ASYNC).permitAll()
.requestMatchers(publicEndpoints.toArray(new String[0])).permitAll()
@@ -212,7 +238,11 @@ public class SecurityConfig {
http
.csrf(AbstractHttpConfigurer::disable)
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.headers(headers -> headers.frameOptions(HeadersConfigurer.FrameOptionsConfig::sameOrigin))
.headers(headers -> headers
.frameOptions(HeadersConfigurer.FrameOptionsConfig::sameOrigin)
.referrerPolicy(referrer -> referrer.policy(
ReferrerPolicyHeaderWriter.ReferrerPolicy.STRICT_ORIGIN_WHEN_CROSS_ORIGIN))
)
.authorizeHttpRequests(auth -> auth.anyRequest().permitAll());
return http.build();
}
@@ -224,10 +254,92 @@ public class SecurityConfig {
return auth.build();
}
@Bean("noRedirectRestTemplate")
public RestTemplate noRedirectRestTemplate() {
return new RestTemplate(
new SimpleClientHttpRequestFactory() {
@Override
protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {
super.prepareConnection(connection, httpMethod);
connection.setInstanceFollowRedirects(false);
if (connection instanceof HttpsURLConnection httpsConnection) {
String targetHost = FileService.getTargetHost();
if (targetHost != null) {
// Set original host for SNI (even if connecting to IP)
SSLSocketFactory defaultFactory = httpsConnection.getSSLSocketFactory();
httpsConnection.setSSLSocketFactory(new SniSSLSocketFactory(defaultFactory, targetHost));
httpsConnection.setHostnameVerifier((hostname, session) -> {
String expectedHost = FileService.getTargetHost();
if (expectedHost != null) {
// Verify certificate against the original expected hostname, even if connecting via IP
return HttpsURLConnection.getDefaultHostnameVerifier().verify(expectedHost, session);
}
// Fallback: use default verifier for the hostname we connected to
return HttpsURLConnection.getDefaultHostnameVerifier().verify(hostname, session);
});
}
}
}
}
);
}
private static class SniSSLSocketFactory extends SSLSocketFactory {
private final SSLSocketFactory delegate;
private final String targetHost;
public SniSSLSocketFactory(SSLSocketFactory delegate, String targetHost) {
this.delegate = delegate;
this.targetHost = targetHost;
}
@Override
public String[] getDefaultCipherSuites() { return delegate.getDefaultCipherSuites(); }
@Override
public String[] getSupportedCipherSuites() { return delegate.getSupportedCipherSuites(); }
@Override
public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
// Pass targetHost instead of host (which is the IP) so the internal SSLSession gets the correct peer host
Socket socket = delegate.createSocket(s, targetHost, port, autoClose);
if (socket instanceof SSLSocket sslSocket) {
SNIHostName serverName = new SNIHostName(targetHost);
SSLParameters params = sslSocket.getSSLParameters();
params.setServerNames(Collections.singletonList(serverName));
// Explicitly set EndpointIdentificationAlgorithm so Java verifies the certificate against targetHost
params.setEndpointIdentificationAlgorithm("HTTPS");
sslSocket.setSSLParameters(params);
}
return socket;
}
@Override public Socket createSocket(String host, int port) throws IOException { return delegate.createSocket(host, port); }
@Override public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException { return delegate.createSocket(host, port, localHost, localPort); }
@Override public Socket createSocket(InetAddress host, int port) throws IOException { return delegate.createSocket(host, port); }
@Override public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException { return delegate.createSocket(address, port, localAddress, localPort); }
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOriginPatterns(List.of("*"));
String allowedOriginsStr = env.getProperty("app.cors.allowed-origins", "*").trim();
if ("*".equals(allowedOriginsStr) || allowedOriginsStr.isEmpty()) {
log.warn(
"CORS is configured to allow all origins (*) because 'app.cors.allowed-origins' is '{}'. " +
"This maintains backward compatibility, but it's recommended to set it to an explicit origin list.",
allowedOriginsStr.isEmpty() ? "empty" : "*"
);
configuration.setAllowedOriginPatterns(List.of("*"));
} else {
List<String> origins = Arrays.stream(ALLOWED.split(allowedOriginsStr))
.filter(s -> !s.isEmpty())
.map(String::trim)
.toList();
configuration.setAllowedOriginPatterns(origins);
}
configuration.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"));
configuration.setAllowedHeaders(List.of("Authorization", "Cache-Control", "Content-Type", "Range", "If-None-Match"));
configuration.setExposedHeaders(List.of("Content-Disposition", "Accept-Ranges", "Content-Range", "Content-Length", "ETag", "Date"));
@@ -238,4 +350,4 @@ public class SecurityConfig {
return source;
}
}
}
@@ -23,6 +23,7 @@ public class AuthRateLimitService {
public AuthRateLimitService(AuditService auditService) {
this.auditService = auditService;
this.attemptCache = Caffeine.newBuilder()
.maximumSize(10000)
.expireAfterWrite(Duration.ofMinutes(15))
.build();
}
@@ -30,15 +31,30 @@ public class AuthRateLimitService {
// --- Login rate limiting ---
public void checkLoginRateLimit(String ip) {
checkRateLimit("login:" + ip, AuditAction.LOGIN_RATE_LIMITED, "Login rate limited for IP: " + ip);
checkRateLimit("login:ip:" + ip, AuditAction.LOGIN_RATE_LIMITED, "Login rate limited for IP: " + ip);
}
public void checkLoginRateLimitByUsername(String username) {
String normalizedUsername = normalizeUsername(username);
checkRateLimit("login:user:" + normalizedUsername, AuditAction.LOGIN_RATE_LIMITED, "Login rate limited for username: " + normalizedUsername);
}
public void recordFailedLoginAttempt(String ip) {
recordFailedAttempt("login:" + ip);
recordFailedAttempt("login:ip:" + ip);
}
public void recordFailedLoginAttemptByUsername(String username) {
String normalizedUsername = normalizeUsername(username);
recordFailedAttempt("login:user:" + normalizedUsername);
}
public void resetLoginAttempts(String ip) {
resetAttempts("login:" + ip);
resetAttempts("login:ip:" + ip);
}
public void resetLoginAttemptsByUsername(String username) {
String normalizedUsername = normalizeUsername(username);
resetAttempts("login:user:" + normalizedUsername);
}
// --- Refresh token rate limiting ---
@@ -72,4 +88,8 @@ public class AuthRateLimitService {
private void resetAttempts(String key) {
attemptCache.invalidate(key);
}
private String normalizeUsername(String username) {
return username != null ? username.trim().toLowerCase() : "";
}
}
@@ -1,6 +1,7 @@
package org.booklore.config.security.service;
import lombok.AllArgsConstructor;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.booklore.config.AppProperties;
import org.booklore.config.security.JwtUtils;
@@ -31,10 +32,12 @@ import org.booklore.service.audit.AuditService;
import org.booklore.util.RequestUtils;
@Slf4j
@AllArgsConstructor
@RequiredArgsConstructor
@Service
public class AuthenticationService {
private String dummyPasswordHash;
private final AppProperties appProperties;
private final UserRepository userRepository;
private final RefreshTokenRepository refreshTokenRepository;
@@ -45,6 +48,11 @@ public class AuthenticationService {
private final AuditService auditService;
private final AuthRateLimitService authRateLimitService;
@PostConstruct
void initDummyHash() {
this.dummyPasswordHash = passwordEncoder.encode("_dummy_placeholder_for_timing_equalization_");
}
public BookLoreUser getAuthenticatedUser() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null) {
@@ -93,21 +101,31 @@ public class AuthenticationService {
public ResponseEntity<Map<String, String>> loginUser(UserLoginRequest loginRequest) {
String ip = RequestUtils.getCurrentRequest().getRemoteAddr();
String username = loginRequest.getUsername();
authRateLimitService.checkLoginRateLimit(ip);
authRateLimitService.checkLoginRateLimitByUsername(username);
BookLoreUserEntity user = userRepository.findByUsername(loginRequest.getUsername()).orElseThrow(() -> {
auditService.log(AuditAction.LOGIN_FAILED, "Login failed for unknown user: " + loginRequest.getUsername());
BookLoreUserEntity user = userRepository.findByUsername(username).orElse(null);
if (user == null) {
// Constant-time dummy BCrypt check prevents timing-based user enumeration:
// without this, unknown-user responses are ~3x faster than wrong-password responses.
passwordEncoder.matches(loginRequest.getPassword(), dummyPasswordHash);
auditService.log(AuditAction.LOGIN_FAILED, "Login failed for unknown user: " + username);
authRateLimitService.recordFailedLoginAttempt(ip);
return ApiError.USER_NOT_FOUND.createException(loginRequest.getUsername());
});
authRateLimitService.recordFailedLoginAttemptByUsername(username);
throw ApiError.INVALID_CREDENTIALS.createException();
}
if (!passwordEncoder.matches(loginRequest.getPassword(), user.getPasswordHash())) {
auditService.log(AuditAction.LOGIN_FAILED, "Login failed for user: " + loginRequest.getUsername());
auditService.log(AuditAction.LOGIN_FAILED, "Login failed for user: " + username);
authRateLimitService.recordFailedLoginAttempt(ip);
authRateLimitService.recordFailedLoginAttemptByUsername(username);
throw ApiError.INVALID_CREDENTIALS.createException();
}
authRateLimitService.resetLoginAttempts(ip);
authRateLimitService.resetLoginAttemptsByUsername(username);
return loginUser(user);
}
@@ -22,7 +22,7 @@ public class OpdsUserDetailsService implements UserDetailsService {
@Override
public OpdsUserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
OpdsUserV2Entity userV2 = opdsUserV2Repository.findByUsername(username)
.orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(username));
.orElseThrow(() -> new UsernameNotFoundException("Invalid credentials"));
OpdsUserV2 mappedCredential = opdsUserV2Mapper.toDto(userV2);
return new OpdsUserDetails(mappedCredential);
}
@@ -1,6 +1,7 @@
package org.booklore.controller;
import org.booklore.service.AuthorMetadataService;
import org.booklore.config.security.annotation.CheckBookAccess;
import org.booklore.service.book.BookService;
import org.booklore.service.bookdrop.BookDropService;
import org.booklore.service.reader.CbxReaderService;
@@ -32,6 +33,7 @@ public class BookMediaController {
@Operation(summary = "Get book thumbnail", description = "Retrieve the thumbnail image for a specific book.")
@ApiResponse(responseCode = "200", description = "Book thumbnail returned successfully")
@GetMapping("/book/{bookId}/thumbnail")
@CheckBookAccess(bookIdParam = "bookId")
public ResponseEntity<Resource> getBookThumbnail(@Parameter(description = "ID of the book") @PathVariable long bookId) {
return ResponseEntity.ok(bookService.getBookThumbnail(bookId));
}
@@ -39,6 +41,7 @@ public class BookMediaController {
@Operation(summary = "Get book cover", description = "Retrieve the cover image for a specific book.")
@ApiResponse(responseCode = "200", description = "Book cover returned successfully")
@GetMapping("/book/{bookId}/cover")
@CheckBookAccess(bookIdParam = "bookId")
public ResponseEntity<Resource> getBookCover(@Parameter(description = "ID of the book") @PathVariable long bookId) {
return ResponseEntity.ok(bookService.getBookCover(bookId));
}
@@ -46,6 +49,7 @@ public class BookMediaController {
@Operation(summary = "Get audiobook thumbnail", description = "Retrieve the audiobook thumbnail image for a specific book.")
@ApiResponse(responseCode = "200", description = "Audiobook thumbnail returned successfully")
@GetMapping("/book/{bookId}/audiobook-thumbnail")
@CheckBookAccess(bookIdParam = "bookId")
public ResponseEntity<Resource> getAudiobookThumbnail(@Parameter(description = "ID of the book") @PathVariable long bookId) {
return ResponseEntity.ok(bookService.getAudiobookThumbnail(bookId));
}
@@ -53,6 +57,7 @@ public class BookMediaController {
@Operation(summary = "Get audiobook cover", description = "Retrieve the audiobook cover image for a specific book.")
@ApiResponse(responseCode = "200", description = "Audiobook cover returned successfully")
@GetMapping("/book/{bookId}/audiobook-cover")
@CheckBookAccess(bookIdParam = "bookId")
public ResponseEntity<Resource> getAudiobookCover(@Parameter(description = "ID of the book") @PathVariable long bookId) {
return ResponseEntity.ok(bookService.getAudiobookCover(bookId));
}
@@ -60,6 +65,7 @@ public class BookMediaController {
@Operation(summary = "Get CBX page as image", description = "Retrieve a specific page from a CBX book as an image.")
@ApiResponse(responseCode = "200", description = "CBX page image returned successfully")
@GetMapping("/book/{bookId}/cbx/pages/{pageNumber}")
@CheckBookAccess(bookIdParam = "bookId")
public void getCbxPage(
@Parameter(description = "ID of the book") @PathVariable Long bookId,
@Parameter(description = "Page number to retrieve") @PathVariable int pageNumber,
@@ -1,5 +1,6 @@
package org.booklore.controller;
import jakarta.validation.Valid;
import org.booklore.exception.ErrorResponse;
import org.booklore.model.dto.request.InitialUserRequest;
import org.booklore.model.dto.response.SuccessResponse;
@@ -35,7 +36,7 @@ public class SetupController {
@ApiResponse(responseCode = "200", description = "Admin user created successfully")
@PostMapping
public ResponseEntity<?> setupFirstUser(
@Parameter(description = "Initial user request") @RequestBody InitialUserRequest request) {
@Parameter(description = "Initial user request") @RequestBody @Valid InitialUserRequest request) {
if (userProvisioningService.isInitialUserAlreadyProvisioned()) {
return ResponseEntity.status(403).body(new ErrorResponse(403, "Setup is disabled after the first user is created."));
}
@@ -1,14 +1,27 @@
package org.booklore.model.dto;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import lombok.Data;
import java.util.Set;
@Data
public class UserCreateRequest {
@NotBlank
private String username;
@NotBlank
@Size(min = 8, max = 72, message = "Password must be at least 8 characters long")
private String password;
@NotBlank
private String name;
@NotBlank
@Email
private String email;
private boolean permissionUpload;
@@ -2,6 +2,7 @@ package org.booklore.model.dto.request;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import lombok.Data;
@Data
@@ -17,5 +18,6 @@ public class InitialUserRequest {
private String name;
@NotBlank
@Size(min = 8, max = 72, message = "Password must be between 8 and 72 characters long")
private String password;
}
@@ -1,6 +1,7 @@
package org.booklore.service.metadata.extractor;
import org.booklore.model.dto.BookMetadata;
import org.booklore.util.SecureXmlUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
@@ -9,7 +10,6 @@ import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
@@ -37,9 +37,7 @@ public class Fb2MetadataExtractor implements FileMetadataExtractor {
@Override
public byte[] extractCover(File file) {
try (InputStream inputStream = getInputStream(file)) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
DocumentBuilderFactory dbf = SecureXmlUtils.createSecureDocumentBuilderFactory(true);
DocumentBuilder builder = dbf.newDocumentBuilder();
Document doc = builder.parse(inputStream);
@@ -93,9 +91,7 @@ public class Fb2MetadataExtractor implements FileMetadataExtractor {
@Override
public BookMetadata extractMetadata(File file) {
try (InputStream inputStream = getInputStream(file)) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
DocumentBuilderFactory dbf = SecureXmlUtils.createSecureDocumentBuilderFactory(true);
DocumentBuilder builder = dbf.newDocumentBuilder();
Document doc = builder.parse(inputStream);
@@ -5,6 +5,12 @@ import com.github.junrar.rarfile.FileHeader;
import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.Marshaller;
import jakarta.xml.bind.Unmarshaller;
import jakarta.xml.bind.ValidationEvent;
import javax.xml.XMLConstants;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.sax.SAXSource;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry;
@@ -47,10 +53,6 @@ public class CbxMetadataWriter implements MetadataWriter {
private static final JAXBContext JAXB_CONTEXT;
static {
// XXE protection: Disable external DTD and Schema access for security
System.setProperty("javax.xml.accessExternalDTD", "");
System.setProperty("javax.xml.accessExternalSchema", "");
try {
JAXB_CONTEXT = JAXBContext.newInstance(ComicInfo.class);
} catch (jakarta.xml.bind.JAXBException e) {
@@ -447,20 +449,32 @@ public class CbxMetadataWriter implements MetadataWriter {
}
private ComicInfo parseComicInfo(InputStream xmlStream) throws Exception {
// Use a SAXSource with an explicitly secured XMLReader to prevent XXE injection.
// This is more robust than System.setProperty() because it is per-instance and
// cannot be inadvertently disabled by other code running in the same JVM.
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
spf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
spf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
spf.setFeature("http://xml.org/sax/features/external-general-entities", false);
spf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
XMLReader xmlReader = spf.newSAXParser().getXMLReader();
SAXSource saxSource = new SAXSource(xmlReader, new InputSource(xmlStream));
Unmarshaller unmarshaller = JAXB_CONTEXT.createUnmarshaller();
unmarshaller.setEventHandler(event -> {
if (event.getSeverity() == jakarta.xml.bind.ValidationEvent.WARNING ||
event.getSeverity() == jakarta.xml.bind.ValidationEvent.ERROR) {
log.warn("JAXB Parsing Issue: {} [Line: {}, Col: {}]",
event.getMessage(),
event.getLocator().getLineNumber(),
if (event.getSeverity() == ValidationEvent.WARNING ||
event.getSeverity() == ValidationEvent.ERROR) {
log.warn("JAXB Parsing Issue: {} [Line: {}, Col: {}]",
event.getMessage(),
event.getLocator().getLineNumber(),
event.getLocator().getColumnNumber());
}
return true; // Continue processing
});
ComicInfo result = (ComicInfo) unmarshaller.unmarshal(xmlStream);
log.debug("CbxMetadataWriter: Parsed ComicInfo - Title: {}, Summary length: {}",
result.getTitle(),
ComicInfo result = (ComicInfo) unmarshaller.unmarshal(saxSource);
log.debug("CbxMetadataWriter: Parsed ComicInfo - Title: {}, Summary length: {}",
result.getTitle(),
result.getSummary() != null ? result.getSummary().length() : 0);
return result;
}
@@ -703,8 +717,12 @@ public class CbxMetadataWriter implements MetadataWriter {
if (entryName == null || entryName.isBlank()) return false;
String normalized = entryName.replace('\\', '/');
if (normalized.startsWith("/")) return false;
if (normalized.contains("../")) 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;
}
return true;
}
@@ -16,6 +16,7 @@ import org.springframework.stereotype.Service;
import java.io.File;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@@ -472,7 +473,7 @@ public class OpdsFeedService {
String queryString = request.getQueryString();
if (queryString != null) {
java.util.Arrays.stream(queryString.split("&"))
Arrays.stream(queryString.split("&"))
.filter(param -> !param.startsWith("page=") && !param.startsWith("size="))
.forEach(param -> result.append(param).append("&"));
}
@@ -437,6 +437,13 @@ public class CbxReaderService {
if (normalized.startsWith("__MACOSX/") || normalized.contains("/__MACOSX/")) {
return false;
}
// Prevent path traversal: reject any entry whose path contains ".." as a component.
// Checks split-by-/ to catch "foo/..", ".." alone, and not just "../" (with trailing slash).
for (String component : normalized.split("/", -1)) {
if ("..".equals(component)) {
return false;
}
}
String baseName = baseName(normalized).toLowerCase();
if (baseName.startsWith("._") || baseName.startsWith(".")) {
return false;
@@ -20,11 +20,13 @@ import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipFile;
import org.apache.pdfbox.io.IOUtils;
import org.booklore.util.SecureXmlUtils;
import org.springframework.stereotype.Service;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
@@ -63,12 +65,7 @@ public class EpubReaderService {
private static final ThreadLocal<DocumentBuilder> DOCUMENT_BUILDER = ThreadLocal.withInitial(() -> {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
return factory.newDocumentBuilder();
return SecureXmlUtils.createSecureDocumentBuilder(true);
} catch (ParserConfigurationException e) {
throw new RuntimeException("Failed to create DocumentBuilder", e);
}
@@ -1,5 +1,6 @@
package org.booklore.service.upload;
import lombok.RequiredArgsConstructor;
import org.booklore.config.AppProperties;
import org.booklore.exception.ApiError;
import org.booklore.mapper.AdditionalFileMapper;
@@ -21,7 +22,7 @@ import org.booklore.service.file.FileMovingHelper;
import org.booklore.service.monitoring.MonitoringRegistrationService;
import org.booklore.service.metadata.extractor.MetadataExtractorFactory;
import org.booklore.util.PathPatternResolver;
import lombok.RequiredArgsConstructor;
import org.springframework.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@@ -262,7 +263,13 @@ public class FileUploadService {
if (originalFileName == null) {
throw new IllegalArgumentException("File must have a name");
}
return originalFileName;
// Prevent Path Traversal by extracting only the base file name
String cleanPath = StringUtils.cleanPath(originalFileName);
String baseFileName = StringUtils.getFilename(cleanPath);
if (baseFileName == null || baseFileName.isEmpty() || baseFileName.equals("..")) {
throw new IllegalArgumentException("Invalid filename");
}
return baseFileName;
}
private BookFileExtension getFileExtension(String fileName) {
@@ -11,22 +11,30 @@ import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URI;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Set;
import java.util.stream.Stream;
@@ -35,9 +43,32 @@ import java.util.stream.Stream;
@Service
public class FileService {
private static final ThreadLocal<String> TARGET_HOST_THREAD_LOCAL = new ThreadLocal<>();
public static String getTargetHost() {
return TARGET_HOST_THREAD_LOCAL.get();
}
public static void setTargetHost(String host) {
TARGET_HOST_THREAD_LOCAL.set(host);
}
public static void clearTargetHost() {
TARGET_HOST_THREAD_LOCAL.remove();
}
static {
// Enable restricted headers to allow 'Host' header override for DNS rebinding protection
System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
}
private final AppProperties appProperties;
private final RestTemplate restTemplate;
private final AppSettingService appSettingService;
private final RestTemplate noRedirectRestTemplate;
private static final int MAX_REDIRECTS = 5;
private static final double TARGET_COVER_ASPECT_RATIO = 1.5;
private static final int SMART_CROP_COLOR_TOLERANCE = 30;
@@ -58,6 +89,8 @@ public class FileService {
private static final String JPEG_MIME_TYPE = "image/jpeg";
private static final String PNG_MIME_TYPE = "image/png";
private static final long MAX_FILE_SIZE_BYTES = 5L * 1024 * 1024;
// 20 MP covers legitimate book covers and author photos with a comfortable safety margin.
private static final long MAX_IMAGE_PIXELS = 20_000_000L;
private static final int THUMBNAIL_WIDTH = 250;
private static final int THUMBNAIL_HEIGHT = 350;
private static final int SQUARE_THUMBNAIL_SIZE = 250;
@@ -137,6 +170,7 @@ public class FileService {
return Paths.get(appProperties.getPathConfig(), "tools", "kepubify").toString();
}
// ========================================
// VALIDATION
// ========================================
@@ -170,18 +204,34 @@ public class FileService {
if (imageData == null || imageData.length == 0) {
throw new IOException("Image data is null or empty");
}
try (InputStream is = new ByteArrayInputStream(imageData)) {
BufferedImage image = ImageIO.read(is);
if (image != null) {
return image;
try (ImageInputStream iis = ImageIO.createImageInputStream(new ByteArrayInputStream(imageData))) {
Iterator<ImageReader> readers = ImageIO.getImageReaders(iis);
if (readers.hasNext()) {
ImageReader reader = readers.next();
try {
reader.setInput(iis);
int width = reader.getWidth(0);
int height = reader.getHeight(0);
long pixelCount = (long) width * height;
if (pixelCount > MAX_IMAGE_PIXELS) {
throw new IOException(String.format("Rejected image: dimensions %dx%d (%d pixels) exceed limit %d — possible decompression bomb",
width, height, pixelCount, MAX_IMAGE_PIXELS));
}
return reader.read(0);
} finally {
reader.dispose();
}
}
} catch (IOException e) {
throw e;
} catch (Exception e) {
log.warn("ImageIO/TwelveMonkeys decode failed (possibly unsupported format like AVIF/HEIC): {}", e.getMessage());
return null;
throw new IOException("ImageIO decode failed (possibly unsupported format): " + e.getMessage(), e);
}
log.warn("Unable to decode image - likely unsupported format (AVIF, HEIC, or SVG)");
return null;
throw new IOException("Unable to decode image, likely unsupported format");
}
public static BufferedImage resizeImage(BufferedImage originalImage, int width, int height) {
@@ -217,31 +267,138 @@ public class FileService {
public BufferedImage downloadImageFromUrl(String imageUrl) throws IOException {
try {
HttpHeaders headers = new HttpHeaders();
headers.set(HttpHeaders.USER_AGENT, "BookLore/1.0 (Book and Comic Metadata Fetcher; +https://github.com/booklore-app/booklore)");
headers.set(HttpHeaders.ACCEPT, "image/*");
HttpEntity<String> entity = new HttpEntity<>(headers);
ResponseEntity<byte[]> response = restTemplate.exchange(
imageUrl,
HttpMethod.GET,
entity,
byte[].class
);
// Validate and convert
if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
return readImage(response.getBody());
} else {
throw new IOException("Failed to download image. HTTP Status: " + response.getStatusCode());
}
return downloadImageFromUrlInternal(imageUrl);
} catch (Exception e) {
log.error("Failed to download image from URL: {} - {}", imageUrl, e.getMessage());
throw new IOException("Failed to download image from URL: " + imageUrl + " - " + e.getMessage(), e);
log.warn("Failed to download image from {}: {}", imageUrl, e.getMessage());
if (e instanceof IOException ioException) {
throw ioException;
}
throw new IOException("Failed to download image from " + imageUrl + ": " + e.getMessage(), e);
}
}
private BufferedImage downloadImageFromUrlInternal(String imageUrl) throws IOException {
String currentUrl = imageUrl;
int redirectCount = 0;
try {
while (redirectCount <= MAX_REDIRECTS) {
URI uri = URI.create(currentUrl);
// Protocol validation
if (!"http".equalsIgnoreCase(uri.getScheme()) && !"https".equalsIgnoreCase(uri.getScheme())) {
throw new IOException("Only HTTP and HTTPS protocols are allowed");
}
String host = uri.getHost();
if (host == null) {
throw new IOException("Invalid URL: no host found in " + currentUrl);
}
// Resolve host to IP to prevent DNS rebinding (TOCTOU)
InetAddress[] inetAddresses = InetAddress.getAllByName(host);
if (inetAddresses.length == 0) {
throw new IOException("Could not resolve host: " + host);
}
for (InetAddress inetAddress : inetAddresses) {
if (isInternalAddress(inetAddress)) {
throw new SecurityException("URL points to a local or private internal network address: " + host + " (" + inetAddress.getHostAddress() + ")");
}
}
String ipAddress = inetAddresses[0].getHostAddress();
// Set target host for SNI / Hostname verification in RestTemplate/SSLSocketFactory
setTargetHost(host);
// Build request URL with IP address to ensure we connect to the validated address.
// We keep the original URI's path and query.
String portSuffix = (uri.getPort() != -1) ? ":" + uri.getPort() : "";
String path = uri.getRawPath();
if (path == null || path.isEmpty()) path = "/";
String query = uri.getRawQuery();
// Handle IPv6 address formatting in URL
String hostInUrl = ipAddress;
if (ipAddress.contains(":")) {
hostInUrl = "[" + ipAddress + "]";
}
String requestUrl = uri.getScheme() + "://" + hostInUrl + portSuffix + path + (query != null ? "?" + query : "");
HttpHeaders headers = new HttpHeaders();
// Set original 'Host' header for server-side virtual hosting
headers.set(HttpHeaders.HOST, host);
headers.set(HttpHeaders.USER_AGENT, "BookLore/1.0 (Book and Comic Metadata Fetcher; +https://github.com/booklore-app/booklore)");
headers.set(HttpHeaders.ACCEPT, "image/*");
HttpEntity<String> entity = new HttpEntity<>(headers);
log.debug("Downloading image via IP-based URL: {} (Original host: {})", requestUrl, host);
ResponseEntity<byte[]> response = noRedirectRestTemplate.exchange(
requestUrl,
HttpMethod.GET,
entity,
byte[].class
);
if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
return readImage(response.getBody());
} else if (response.getStatusCode().is3xxRedirection()) {
String location = response.getHeaders().getFirst(HttpHeaders.LOCATION);
if (location == null) {
throw new IOException("Redirection response without Location header");
}
// Resolve location against CURRENT URL (which has the hostname)
currentUrl = uri.resolve(location).toString();
redirectCount++;
} else {
throw new IOException("Failed to download image. HTTP Status: " + response.getStatusCode());
}
}
} finally {
// Ensure thread-local is cleared to prevent leakage to subsequent requests (container thread reuse)
clearTargetHost();
}
throw new IOException("Too many redirects (max " + MAX_REDIRECTS + ")");
}
private boolean isInternalAddress(InetAddress address) {
if (address.isLoopbackAddress() || address.isLinkLocalAddress() ||
address.isSiteLocalAddress() || address.isAnyLocalAddress()) {
return true;
}
byte[] addr = address.getAddress();
// Check for IPv6 Unique Local Address (fc00::/7)
if (addr.length == 16) {
if ((addr[0] & 0xFE) == (byte) 0xFC) {
return true;
}
}
// Handle IPv4-mapped IPv6 addresses (::ffff:127.0.0.1)
if (isIpv4MappedAddress(addr)) {
try {
byte[] ipv4Bytes = new byte[4];
System.arraycopy(addr, 12, ipv4Bytes, 0, 4);
InetAddress ipv4Addr = InetAddress.getByAddress(ipv4Bytes);
return isInternalAddress(ipv4Addr);
} catch (java.net.UnknownHostException e) {
return false;
}
}
return false;
}
private boolean isIpv4MappedAddress(byte[] addr) {
if (addr.length != 16) return false;
for (int i = 0; i < 10; i++) {
if (addr[i] != 0) return false;
}
return (addr[10] == (byte) 0xFF) && (addr[11] == (byte) 0xFF);
}
// ========================================
// COVER OPERATIONS
// ========================================
@@ -12,7 +12,7 @@ import javax.xml.parsers.ParserConfigurationException;
@UtilityClass
public class SecureXmlUtils {
public static DocumentBuilderFactory createSecureDocumentBuilderFactory(boolean namespaceAware) {
public static DocumentBuilderFactory createSecureDocumentBuilderFactory(boolean namespaceAware) throws ParserConfigurationException {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(namespaceAware);
@@ -27,10 +27,8 @@ public class SecureXmlUtils {
return factory;
} catch (ParserConfigurationException e) {
log.warn("Failed to configure secure XML parser, using defaults: {}", e.getMessage());
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(namespaceAware);
return factory;
log.error("CRITICAL: Failed to configure secure XML parser: {}", e.getMessage());
throw e;
}
}
@@ -2,6 +2,13 @@ app:
path-config: '/app/data'
bookdrop-folder: '/bookdrop'
version: 'development'
cors:
# Comma-separated list of allowed CORS origins.
# Leave empty (default) to allow same-origin requests only.
# Example: ALLOWED_ORIGINS=https://app.example.com,https://mobile.example.com
allowed-origins: ${ALLOWED_ORIGINS:*}
remote-auth:
enabled: ${REMOTE_AUTH_ENABLED:false}
create-new-users: ${REMOTE_AUTH_CREATE_NEW_USERS:true}