diff --git a/backend/build.gradle.kts b/backend/build.gradle.kts index d51c91e64..40902a7c2 100644 --- a/backend/build.gradle.kts +++ b/backend/build.gradle.kts @@ -111,6 +111,7 @@ dependencies { implementation("org.springframework.boot:spring-boot-starter-actuator") implementation("org.springframework.boot:spring-boot-starter-security") implementation("org.springframework.boot:spring-boot-starter-mail") + implementation("org.springframework.boot:spring-boot-http-client") implementation("com.nimbusds:nimbus-jose-jwt:10.9.1") // --- Reactive Streams --- diff --git a/backend/gradle.lockfile b/backend/gradle.lockfile index 6f13a3ad3..bbb0d5629 100644 --- a/backend/gradle.lockfile +++ b/backend/gradle.lockfile @@ -138,6 +138,7 @@ org.springframework.boot:spring-boot-data-jpa:4.1.0=compileClasspath,productionR org.springframework.boot:spring-boot-flyway:4.1.0=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-health:4.1.0=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-hibernate:4.1.0=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-http-client:4.1.0=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-http-converter:4.1.0=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-jackson:4.1.0=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-jdbc:4.1.0=compileClasspath,productionRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath diff --git a/backend/src/main/java/org/booklore/config/AppProperties.java b/backend/src/main/java/org/booklore/config/AppProperties.java index ced784428..58f098042 100644 --- a/backend/src/main/java/org/booklore/config/AppProperties.java +++ b/backend/src/main/java/org/booklore/config/AppProperties.java @@ -4,6 +4,8 @@ import lombok.Getter; import lombok.Setter; import org.springframework.boot.context.properties.ConfigurationProperties; +import java.util.List; + @ConfigurationProperties(prefix = "app") @Getter @Setter @@ -12,6 +14,7 @@ public class AppProperties { private String bookdropFolder; private String version; private RemoteAuth remoteAuth; + private OutboundRequests outbound; private Boolean forceDisableOidc = false; /** @@ -38,4 +41,12 @@ public class AppProperties { private String adminGroup; private String groupsDelimiter = "\\s+"; // Default to whitespace for backward compatibility } + + @Getter + @Setter + public static class OutboundRequests { + private int connectTimeout = 15; + private int readTimeout = 15; + private List restrictedRanges = List.of(); + } } diff --git a/backend/src/main/java/org/booklore/config/RestClientConfig.java b/backend/src/main/java/org/booklore/config/RestClientConfig.java index c11061b31..fbf362063 100644 --- a/backend/src/main/java/org/booklore/config/RestClientConfig.java +++ b/backend/src/main/java/org/booklore/config/RestClientConfig.java @@ -1,36 +1,65 @@ package org.booklore.config; +import lombok.RequiredArgsConstructor; +import org.springframework.boot.http.client.ClientHttpRequestFactoryBuilder; +import org.springframework.boot.http.client.HttpClientSettings; +import org.springframework.boot.http.client.InetAddressFilter; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.http.client.ClientHttpRequestFactory; -import org.springframework.http.client.JdkClientHttpRequestFactory; import org.springframework.http.client.SimpleClientHttpRequestFactory; import org.springframework.web.client.RestClient; import org.springframework.web.client.RestTemplate; -import java.net.http.HttpClient; import java.time.Duration; @Configuration +@RequiredArgsConstructor public class RestClientConfig { - private ClientHttpRequestFactory getRequestFactory(HttpClient httpClient) { - JdkClientHttpRequestFactory factory = new JdkClientHttpRequestFactory(httpClient); - factory.setReadTimeout(Duration.ofSeconds(15)); - return factory; + private final AppProperties appProperties; + + @Bean + public InetAddressFilter outboundInetAddressFilter() { + var filter = InetAddressFilter + .not(InetAddressFilter.multicast()); + + var restrictedRanges = appProperties.getOutbound().getRestrictedRanges(); + + if (!restrictedRanges.isEmpty()) { + filter = filter.andNot(restrictedRanges.toArray(new String[]{})); + } + + return filter; } @Bean - public RestClient restClient(HttpClient httpClient) { + public ClientHttpRequestFactory clientHttpRequestFactory(InetAddressFilter outboundInetAddressFilter) { + var outbound = appProperties.getOutbound(); + int connectTimeout = outbound.getConnectTimeout(); + int readTimeout = outbound.getReadTimeout(); + + HttpClientSettings settings = HttpClientSettings.defaults() + .withConnectTimeout(Duration.ofSeconds(connectTimeout)) + .withReadTimeout(Duration.ofSeconds(readTimeout)) + .withInetAddressFilter(outboundInetAddressFilter); + + return ClientHttpRequestFactoryBuilder + .jdk() + .build(settings); + } + + @Bean + public RestClient restClient(ClientHttpRequestFactory clientHttpRequestFactory) { return RestClient.builder() - .requestFactory(getRequestFactory(httpClient)) + .requestFactory(clientHttpRequestFactory) .build(); } @Bean @Primary - public RestTemplate restTemplate(HttpClient httpClient) { - return new RestTemplate(getRequestFactory(httpClient)); + public RestTemplate restTemplate(ClientHttpRequestFactory clientHttpRequestFactory) { + return new RestTemplate(clientHttpRequestFactory); } @Bean diff --git a/backend/src/main/java/org/booklore/config/security/SecurityConfig.java b/backend/src/main/java/org/booklore/config/security/SecurityConfig.java index 797e9f85c..c99e1decb 100644 --- a/backend/src/main/java/org/booklore/config/security/SecurityConfig.java +++ b/backend/src/main/java/org/booklore/config/security/SecurityConfig.java @@ -328,14 +328,6 @@ public class SecurityConfig { return auth.build(); } - @Bean("noRedirectRestTemplate") - public RestTemplate noRedirectRestTemplate() { - HttpClient httpClient = HttpClient.newBuilder() - .followRedirects(HttpClient.Redirect.NEVER) - .build(); - return new RestTemplate(new JdkClientHttpRequestFactory(httpClient)); - } - @Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration configuration = new CorsConfiguration(); diff --git a/backend/src/main/java/org/booklore/util/FileService.java b/backend/src/main/java/org/booklore/util/FileService.java index e3383b910..1a0949de9 100644 --- a/backend/src/main/java/org/booklore/util/FileService.java +++ b/backend/src/main/java/org/booklore/util/FileService.java @@ -8,12 +8,8 @@ import org.booklore.model.entity.BookMetadataEntity; import org.booklore.service.appsettings.AppSettingService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; -import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; -import org.springframework.web.client.RestTemplate; +import org.springframework.web.client.RestClient; import org.springframework.web.multipart.MultipartFile; import javax.imageio.ImageIO; @@ -25,9 +21,6 @@ import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; -import java.net.InetAddress; -import java.net.URI; -import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; @@ -36,7 +29,6 @@ import java.util.Comparator; import java.util.Iterator; import java.util.Set; import java.util.stream.Stream; -import java.net.UnknownHostException; @Slf4j @RequiredArgsConstructor @@ -44,12 +36,8 @@ import java.net.UnknownHostException; public class FileService { private final AppProperties appProperties; - private final RestTemplate restTemplate; private final AppSettingService appSettingService; - private final RestTemplate noRedirectRestTemplate; - - private static final int MAX_REDIRECTS = 5; - + private final RestClient restClient; private static final double TARGET_COVER_ASPECT_RATIO = 1.5; private static final int SMART_CROP_COLOR_TOLERANCE = 30; @@ -293,7 +281,12 @@ public class FileService { public BufferedImage downloadImageFromUrl(String imageUrl) throws IOException { try { - return downloadImageFromUrlInternal(imageUrl); + return readImage( + restClient.get() + .uri(imageUrl) + .retrieve() + .body(byte[].class) + ); } catch (Exception e) { log.warn("Failed to download image from {}: {}", imageUrl, e.getMessage()); if (e instanceof IOException ioException) { @@ -303,144 +296,6 @@ public class FileService { } } - private BufferedImage downloadImageFromUrlInternal(String imageUrl) throws IOException { - String currentUrl = imageUrl; - int redirectCount = 0; - - while (redirectCount <= MAX_REDIRECTS) { - URI uri = URI.create(currentUrl); - 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); - } - - // Validate resolved IPs to block SSRF against internal networks - 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() + ")"); - } - } - - HttpHeaders headers = new HttpHeaders(); - headers.set(HttpHeaders.USER_AGENT, "Grimmory/1.0 (Book and Comic Metadata Fetcher; +https://github.com/grimmory-tools/grimmory)"); - headers.set(HttpHeaders.ACCEPT, "image/*"); - - HttpEntity entity = new HttpEntity<>(headers); - - log.debug("Downloading image from: {}", currentUrl); - - ResponseEntity response = noRedirectRestTemplate.exchange( - currentUrl, - 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"); - } - URI redirectUri = uri.resolve(location); - - // When a CDN redirects to a raw IP (e.g. CloudFront -> 3.168.64.124), - // the Host header would become the bare IP, which the CDN rejects with - // 400. Rewrite the URL to keep the previous hostname so the JDK - // HttpClient sets the correct Host header automatically. - if (isRawIpAddress(redirectUri.getHost())) { - try { - redirectUri = new URI( - redirectUri.getScheme(), - redirectUri.getUserInfo(), - host, - redirectUri.getPort(), - redirectUri.getPath(), - redirectUri.getQuery(), - redirectUri.getFragment() - ); - } catch (URISyntaxException e) { - throw new IOException("Invalid redirect URI: " + e.getMessage(), e); - } - } - - currentUrl = redirectUri.toString(); - redirectCount++; - } else { - throw new IOException("Failed to download image. HTTP Status: " + response.getStatusCode()); - } - } - - throw new IOException("Too many redirects (max " + MAX_REDIRECTS + ")"); - } - - private boolean isRawIpAddress(String host) { - if (host == null) { - return false; - } - // IPv6 in URI brackets - if (host.startsWith("[")) { - return true; - } - // IPv4: all segments are digits - String[] parts = host.split("\\."); - if (parts.length == 4) { - for (String part : parts) { - if (!part.chars().allMatch(Character::isDigit)) { - return false; - } - } - return true; - } - return false; - } - - 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 (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 // ======================================== diff --git a/backend/src/main/resources/application.yaml b/backend/src/main/resources/application.yaml index fe74dba32..bc504e293 100644 --- a/backend/src/main/resources/application.yaml +++ b/backend/src/main/resources/application.yaml @@ -22,6 +22,40 @@ app: force-disable-oidc: ${FORCE_DISABLE_OIDC:false} disk-type: ${DISK_TYPE:LOCAL} + outbound: + connect-timeout: 15 + read-timeout: 15 + restricted-ranges: + - "0.0.0.0/8" # "This host on this network" - RFC 6890 - https://datatracker.ietf.org/doc/html/rfc6890 + - "10.0.0.0/8" # Private Network Prefix - RFC 1918 - https://datatracker.ietf.org/doc/html/rfc1918 + - "100::/64" # IPv6 Discard Prefix - RFC 6666 - https://datatracker.ietf.org/doc/html/rfc6666 + - "100.64.0.0/10" # Shared Address Space - RFC 6890 - https://datatracker.ietf.org/doc/html/rfc6890 + - "::1/128" # IPv6 Loopback - RFC 4291 - https://datatracker.ietf.org/doc/html/rfc4291 + - "127.0.0.0/8" # Loopback - RFC 6890 - https://datatracker.ietf.org/doc/html/rfc6890 + - "::/128" # "Unspecified" - RFC 4291 - https://datatracker.ietf.org/doc/html/rfc4291 + - "169.254.0.0/16" # Link Local - RFC 6890 - https://datatracker.ietf.org/doc/html/rfc6890 + - "172.16.0.0/12" # Private Use - RFC 6890 - https://datatracker.ietf.org/doc/html/rfc6890 + - "192.0.0.0/24" # IETF Protocol Assignments - RFC 6890 - https://datatracker.ietf.org/doc/html/rfc6890 + - "192.0.0.0/29" # DS-Lite - RFC 6333 - https://datatracker.ietf.org/doc/html/rfc6333 + - "192.0.2.0/24" # TEST-NET-1 - RFC 5737 - https://datatracker.ietf.org/doc/html/rfc5737 + - "192.168.0.0/16" # Private Use - RFC 6890 - https://datatracker.ietf.org/doc/html/rfc6890 + - "192.88.99.0/24" # An Anycast Prefix for 6to4 Relay Routers - RFC 3068 - https://datatracker.ietf.org/doc/html/rfc3068 + - "198.18.0.0/15" # Network Interconnect Device Benchmark Testing - RFC 2544 - https://datatracker.ietf.org/doc/html/rfc2544 + - "198.51.100.0/24" # TEST-NET-2 - RFC 5737 - https://datatracker.ietf.org/doc/html/rfc5737 + - "2001:10::/28" # IPv6 ORCHID Prefix - RFC 7343 - https://datatracker.ietf.org/doc/html/rfc7343 + - "2001::/23" # Initial IPv6 Sub-TLA ID Assignments - RFC 2928 - https://datatracker.ietf.org/doc/html/rfc2928 + - "2001:0200::/48" # IPv6 Benchmarking Prefix - RFC 5180 - https://datatracker.ietf.org/doc/html/rfc5180 + - "2001::/32" # IPv6 Global Teredo Prefix - RFC 4380 - https://datatracker.ietf.org/doc/html/rfc4380 + - "2001:db8::/32" # IPv6 Documentation Prefix - RFC 3849 - https://datatracker.ietf.org/doc/html/rfc3849 + - "2002::/16" # Connection of IPv6 Domains via IPv4 Clouds - RFC 3056 - https://datatracker.ietf.org/doc/html/rfc3056 + - "203.0.113.0/24" # TEST-NET-3 - RFC 5737 - https://datatracker.ietf.org/doc/html/rfc5737 + - "240.0.0.0/4" # Reserved - RFC 6890 - https://datatracker.ietf.org/doc/html/rfc6890 + - "255.255.255.255/32" # Limited Broadcast - RFC 0919 - https://datatracker.ietf.org/doc/html/rfc0919 + - "64:ff9b:1::/48" # Local-Use IPv4/IPv6 Translation Prefix - RFC 8215 - https://datatracker.ietf.org/doc/html/rfc8215 + - "64:ff9b::/96" # IPv6 Addressing of IPv4/IPv6 Translators - RFC 6052 - https://datatracker.ietf.org/doc/html/rfc6052 + - "fc00::/7" # Unique Local IPv6 Unicast Addresses - RFC 4193 - https://datatracker.ietf.org/doc/html/rfc4193 + - "fe80::/10" # Link-Local unicast - RFC 4291 - https://datatracker.ietf.org/doc/html/rfc4291 + server: forward-headers-strategy: native port: ${SERVER_PORT:${BOOKLORE_PORT:6060}} diff --git a/backend/src/test/java/org/booklore/util/FileServiceTest.java b/backend/src/test/java/org/booklore/util/FileServiceTest.java index 81ee2d521..22336173c 100644 --- a/backend/src/test/java/org/booklore/util/FileServiceTest.java +++ b/backend/src/test/java/org/booklore/util/FileServiceTest.java @@ -12,16 +12,13 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.ValueSource; -import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockedStatic; import org.mockito.junit.jupiter.MockitoExtension; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.mock.web.MockMultipartFile; -import org.springframework.test.util.ReflectionTestUtils; -import org.springframework.web.client.RestTemplate; +import org.springframework.web.client.RestClient; import javax.imageio.ImageIO; import java.awt.*; @@ -47,6 +44,10 @@ class FileServiceTest { @Mock private AppSettingService appSettingService; + @Mock + private RestClient restClient; + + @InjectMocks private FileService fileService; @TempDir @@ -63,10 +64,6 @@ class FileServiceTest { .coverCroppingSettings(coverCroppingSettings) .build(); lenient().when(appSettingService.getAppSettings()).thenReturn(appSettings); - - RestTemplate mockRestTemplate = mock(RestTemplate.class); - RestTemplate mockNoRedirectRestTemplate = mock(RestTemplate.class); - fileService = new FileService(appProperties, mockRestTemplate, appSettingService, mockNoRedirectRestTemplate); } @Nested @@ -1216,14 +1213,20 @@ class FileServiceTest { @Nested @DisplayName("Network Operations") class NetworkOperationsTests { + void mockRestClient(String uri, Object response) { + var mockRequestHeadersUriSpec = mock(RestClient.RequestHeadersUriSpec.class); + var mockResponseSpec = mock(RestClient.ResponseSpec.class); - @Mock - private RestTemplate restTemplate; + when(restClient.get()).thenReturn(mockRequestHeadersUriSpec); + when(mockRequestHeadersUriSpec.uri(uri)).thenReturn(mockRequestHeadersUriSpec); + when(mockRequestHeadersUriSpec.retrieve()).thenReturn(mockResponseSpec); - @Mock - private AppSettingService appSettingServiceForNetwork; - - private FileService fileService; + if (response instanceof Exception exception) { + when(mockResponseSpec.body(byte[].class)).thenThrow(exception); + } else if (response instanceof byte[] responseBytes) { + when(mockResponseSpec.body(byte[].class)).thenReturn(responseBytes); + } + } @BeforeEach void setup() { @@ -1237,9 +1240,7 @@ class FileServiceTest { AppSettings appSettings = AppSettings.builder() .coverCroppingSettings(coverCroppingSettings) .build(); - lenient().when(appSettingServiceForNetwork.getAppSettings()).thenReturn(appSettings); - - fileService = new FileService(appProperties, restTemplate, appSettingServiceForNetwork, restTemplate); + lenient().when(appSettingService.getAppSettings()).thenReturn(appSettings); } @Nested @@ -1248,25 +1249,14 @@ class FileServiceTest { @Test @DisplayName("downloads and returns valid image") - @Timeout(5) void downloadImageFromUrl_validImage_returnsBufferedImage() throws IOException { String imageUrl = "http://1.1.1.1/image.jpg"; BufferedImage testImage = createTestImage(100, 100); byte[] imageBytes = imageToBytes(testImage); - RestTemplate mockRestTemplate = mock(RestTemplate.class); - AppSettingService mockAppSettingService = mock(AppSettingService.class); - FileService testFileService = new FileService(appProperties, mockRestTemplate, mockAppSettingService, mockRestTemplate); + mockRestClient(imageUrl, imageBytes); - ResponseEntity responseEntity = ResponseEntity.ok(imageBytes); - when(mockRestTemplate.exchange( - anyString(), - eq(HttpMethod.GET), - any(HttpEntity.class), - eq(byte[].class) - )).thenReturn(responseEntity); - - BufferedImage result = testFileService.downloadImageFromUrl(imageUrl); + BufferedImage result = fileService.downloadImageFromUrl(imageUrl); assertNotNull(result); assertEquals(100, result.getWidth()); @@ -1275,16 +1265,10 @@ class FileServiceTest { @Test @DisplayName("throws exception when response body is null") - @Timeout(5) - void downloadImageFromUrl_nullBody_throwsException() { + void downloadImageFromUrl_nullBody_throwsException() throws Exception { String imageUrl = "http://1.1.1.1/image.jpg"; - ResponseEntity responseEntity = ResponseEntity.ok(null); - when(restTemplate.exchange( - anyString(), - eq(HttpMethod.GET), - any(HttpEntity.class), - eq(byte[].class) - )).thenReturn(responseEntity); + + mockRestClient(imageUrl, null); assertThrows(IOException.class, () -> fileService.downloadImageFromUrl(imageUrl)); @@ -1292,188 +1276,14 @@ class FileServiceTest { @Test @DisplayName("throws IOException when ImageIO cannot read bytes") - @Timeout(5) void downloadImageFromUrl_invalidImageData_throwsException() throws IOException { String imageUrl = "http://1.1.1.1/image.jpg"; byte[] invalidBytes = "not an image".getBytes(); - ResponseEntity responseEntity = ResponseEntity.ok(invalidBytes); - RestTemplate noRedirectMock = (RestTemplate) ReflectionTestUtils.getField(fileService, "noRedirectRestTemplate"); - when(noRedirectMock.exchange( - anyString(), - eq(HttpMethod.GET), - any(HttpEntity.class), - eq(byte[].class) - )).thenReturn(responseEntity); + mockRestClient(imageUrl, invalidBytes); assertThrows(IOException.class, () -> fileService.downloadImageFromUrl(imageUrl)); } - - @Test - @DisplayName("throws exception on HTTP error status") - @Timeout(5) - void downloadImageFromUrl_httpError_throwsException() { - String imageUrl = "http://1.1.1.1/image.jpg"; - ResponseEntity responseEntity = ResponseEntity.notFound().build(); - when(restTemplate.exchange( - anyString(), - eq(HttpMethod.GET), - any(HttpEntity.class), - eq(byte[].class) - )).thenReturn(responseEntity); - - assertThrows(IOException.class, () -> - fileService.downloadImageFromUrl(imageUrl)); - } - - @Test - @DisplayName("rewrites redirect URL to preserve hostname when CDN redirects to raw IP") - @Timeout(5) - void downloadImageFromUrl_redirectToRawIp_rewritesUrlWithOriginalHost() throws IOException { - String originalUrl = "http://example.com/cover.jpg"; - String cdnIpRedirect = "http://3.168.64.124/cover.jpg"; - BufferedImage testImage = createTestImage(100, 100); - byte[] imageBytes = imageToBytes(testImage); - - RestTemplate mockRestTemplate = mock(RestTemplate.class); - FileService testFileService = new FileService(appProperties, mockRestTemplate, appSettingServiceForNetwork, mockRestTemplate); - - ResponseEntity redirectResponse = ResponseEntity.status(302) - .header("Location", cdnIpRedirect).build(); - ResponseEntity imageResponse = ResponseEntity.ok(imageBytes); - - var urlCaptor = ArgumentCaptor.forClass(String.class); - when(mockRestTemplate.exchange( - urlCaptor.capture(), eq(HttpMethod.GET), any(HttpEntity.class), eq(byte[].class) - )).thenReturn(redirectResponse, imageResponse); - - BufferedImage result = testFileService.downloadImageFromUrl(originalUrl); - - assertNotNull(result); - assertEquals(originalUrl, urlCaptor.getAllValues().get(0)); - assertEquals("http://example.com/cover.jpg", urlCaptor.getAllValues().get(1)); - } - - @Test - @DisplayName("preserves redirect path when rewriting raw IP URL back to hostname") - @Timeout(5) - void downloadImageFromUrl_redirectToRawIpDifferentPath_preservesPath() throws IOException { - String originalUrl = "http://example.com/images/cover.jpg"; - String cdnIpRedirect = "http://3.168.64.124/cdn/optimized/cover.jpg?token=abc"; - BufferedImage testImage = createTestImage(100, 100); - byte[] imageBytes = imageToBytes(testImage); - - RestTemplate mockRestTemplate = mock(RestTemplate.class); - FileService testFileService = new FileService(appProperties, mockRestTemplate, appSettingServiceForNetwork, mockRestTemplate); - - ResponseEntity redirectResponse = ResponseEntity.status(302) - .header("Location", cdnIpRedirect).build(); - ResponseEntity imageResponse = ResponseEntity.ok(imageBytes); - - var urlCaptor = ArgumentCaptor.forClass(String.class); - when(mockRestTemplate.exchange( - urlCaptor.capture(), eq(HttpMethod.GET), any(HttpEntity.class), eq(byte[].class) - )).thenReturn(redirectResponse, imageResponse); - - testFileService.downloadImageFromUrl(originalUrl); - - assertEquals("http://example.com/cdn/optimized/cover.jpg?token=abc", urlCaptor.getAllValues().get(1)); - } - - @Test - @DisplayName("does not rewrite URL when redirect target is a hostname") - @Timeout(5) - void downloadImageFromUrl_redirectToHostname_keepsRedirectUrl() throws IOException { - String originalUrl = "http://example.com/cover.jpg"; - String hostnameRedirect = "http://www.example.com/cover.jpg"; - BufferedImage testImage = createTestImage(100, 100); - byte[] imageBytes = imageToBytes(testImage); - - RestTemplate mockRestTemplate = mock(RestTemplate.class); - FileService testFileService = new FileService(appProperties, mockRestTemplate, appSettingServiceForNetwork, mockRestTemplate); - - ResponseEntity redirectResponse = ResponseEntity.status(301) - .header("Location", hostnameRedirect).build(); - ResponseEntity imageResponse = ResponseEntity.ok(imageBytes); - - var urlCaptor = ArgumentCaptor.forClass(String.class); - when(mockRestTemplate.exchange( - urlCaptor.capture(), eq(HttpMethod.GET), any(HttpEntity.class), eq(byte[].class) - )).thenReturn(redirectResponse, imageResponse); - - testFileService.downloadImageFromUrl(originalUrl); - - assertEquals(hostnameRedirect, urlCaptor.getAllValues().get(1)); - } - - @Test - @DisplayName("chain: hostname -> hostname -> raw IP uses last hostname for rewrite") - @Timeout(5) - void downloadImageFromUrl_multipleRedirectsToRawIp_usesLastHostname() throws IOException { - String originalUrl = "http://example.com/cover.jpg"; - String hostnameRedirect = "http://www.example.com/cover.jpg"; - String ipRedirect = "http://52.84.12.99/cover.jpg"; - BufferedImage testImage = createTestImage(100, 100); - byte[] imageBytes = imageToBytes(testImage); - - RestTemplate mockRestTemplate = mock(RestTemplate.class); - FileService testFileService = new FileService(appProperties, mockRestTemplate, appSettingServiceForNetwork, mockRestTemplate); - - ResponseEntity redirect1 = ResponseEntity.status(301) - .header("Location", hostnameRedirect).build(); - ResponseEntity redirect2 = ResponseEntity.status(302) - .header("Location", ipRedirect).build(); - ResponseEntity imageResponse = ResponseEntity.ok(imageBytes); - - var urlCaptor = ArgumentCaptor.forClass(String.class); - when(mockRestTemplate.exchange( - urlCaptor.capture(), eq(HttpMethod.GET), any(HttpEntity.class), eq(byte[].class) - )).thenReturn(redirect1, redirect2, imageResponse); - - testFileService.downloadImageFromUrl(originalUrl); - - assertEquals(originalUrl, urlCaptor.getAllValues().get(0)); - assertEquals(hostnameRedirect, urlCaptor.getAllValues().get(1)); - assertEquals("http://www.example.com/cover.jpg", urlCaptor.getAllValues().get(2)); - } - - @Test - @DisplayName("throws exception when redirect exceeds max limit") - @Timeout(5) - void downloadImageFromUrl_tooManyRedirects_throwsException() { - String imageUrl = "http://1.1.1.1/cover.jpg"; - - RestTemplate mockRestTemplate = mock(RestTemplate.class); - FileService testFileService = new FileService(appProperties, mockRestTemplate, appSettingServiceForNetwork, mockRestTemplate); - - ResponseEntity redirectResponse = ResponseEntity.status(302) - .header("Location", "http://2.2.2.2/cover.jpg") - .build(); - - when(mockRestTemplate.exchange( - anyString(), eq(HttpMethod.GET), any(HttpEntity.class), eq(byte[].class) - )).thenReturn(redirectResponse); - - IOException ex = assertThrows(IOException.class, () -> - testFileService.downloadImageFromUrl(imageUrl)); - assertTrue(ex.getMessage().contains("Too many redirects")); - } - - @Test - @DisplayName("throws exception when redirect has no Location header") - @Timeout(5) - void downloadImageFromUrl_redirectWithoutLocation_throwsException() { - String imageUrl = "http://1.1.1.1/image.jpg"; - - ResponseEntity redirectResponse = ResponseEntity.status(302).build(); - when(restTemplate.exchange( - anyString(), eq(HttpMethod.GET), any(HttpEntity.class), eq(byte[].class) - )).thenReturn(redirectResponse); - - IOException ex = assertThrows(IOException.class, () -> - fileService.downloadImageFromUrl(imageUrl)); - assertTrue(ex.getMessage().contains("Location")); - } } @Nested @@ -1482,20 +1292,13 @@ class FileServiceTest { @Test @DisplayName("downloads and saves cover images successfully") - @Timeout(5) void createThumbnailFromUrl_validImage_createsCoverAndThumbnail() throws IOException { String imageUrl = "http://1.1.1.1/cover.jpg"; long bookId = 42L; BufferedImage testImage = createTestImage(800, 1200); // Portrait image byte[] imageBytes = imageToBytes(testImage); - ResponseEntity responseEntity = ResponseEntity.ok(imageBytes); - when(restTemplate.exchange( - anyString(), - eq(HttpMethod.GET), - any(HttpEntity.class), - eq(byte[].class) - )).thenReturn(responseEntity); + mockRestClient(imageUrl, imageBytes); assertDoesNotThrow(() -> fileService.createThumbnailFromUrl(bookId, imageUrl)); @@ -1511,17 +1314,11 @@ class FileServiceTest { @Test @DisplayName("throws ApiError.FILE_READ_ERROR on download failure") - @Timeout(5) - void createThumbnailFromUrl_downloadFails_throwsApiError() { + void createThumbnailFromUrl_downloadFails_throwsApiError() throws Exception { String imageUrl = "http://example.com/invalid.jpg"; long bookId = 42L; - when(restTemplate.exchange( - anyString(), - eq(HttpMethod.GET), - any(HttpEntity.class), - eq(byte[].class) - )).thenThrow(new RuntimeException("Network error")); + mockRestClient(imageUrl, new RuntimeException("Network error")); // FileService wraps exceptions in RuntimeException via ApiError RuntimeException exception = assertThrows(RuntimeException.class, () ->