fix(api): stricter SSRF protections (#2357)

This commit is contained in:
James Ward
2026-08-16 21:30:34 -05:00
committed by GitHub
parent 2a8d8eae14
commit 31b574d3a7
8 changed files with 122 additions and 402 deletions
@@ -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<byte[]> 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<byte[]> 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<byte[]> 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<byte[]> 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<byte[]> redirectResponse = ResponseEntity.status(302)
.header("Location", cdnIpRedirect).build();
ResponseEntity<byte[]> 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<byte[]> redirectResponse = ResponseEntity.status(302)
.header("Location", cdnIpRedirect).build();
ResponseEntity<byte[]> 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<byte[]> redirectResponse = ResponseEntity.status(301)
.header("Location", hostnameRedirect).build();
ResponseEntity<byte[]> 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<byte[]> redirect1 = ResponseEntity.status(301)
.header("Location", hostnameRedirect).build();
ResponseEntity<byte[]> redirect2 = ResponseEntity.status(302)
.header("Location", ipRedirect).build();
ResponseEntity<byte[]> 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<byte[]> 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<byte[]> 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<byte[]> 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, () ->