#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
fix(security): stream stored job files instead of loading them into heap (#8688)
Reece Browne21475ce46210
diff --git a/app/common/src/main/java/stirling/software/common/aop/AutoJobAspect.java b/app/common/src/main/java/stirling/software/common/aop/AutoJobAspect.javaindex 6d2da58b58..b22bc9b16e 100644--- a/app/common/src/main/java/stirling/software/common/aop/AutoJobAspect.java+++ b/app/common/src/main/java/stirling/software/common/aop/AutoJobAspect.java@@ -70,7 +70,14 @@ public class AutoJobAspect {trackProgress);// Process arguments in-place to avoid type mismatch issues- Object[] args = processArgsInPlace(joinPoint.getArgs(), async);+ List<String> inputCopies = new ArrayList<>();+ Object[] args;+ try {+ args = processArgsInPlace(joinPoint.getArgs(), async, inputCopies);+ } catch (RuntimeException failure) {+ discardInputCopies(inputCopies);+ throw failure;+ }// Extract queueable and resourceWeight parameters and validateboolean queueable = autoJobPostMapping.queueable();@@ -252,7 +259,8 @@ public class AutoJobAspect {* @param async Whether this is an async operation* @return The original array with processed arguments*/- private Object[] processArgsInPlace(Object[] originalArgs, boolean async) {+ private Object[] processArgsInPlace(+ Object[] originalArgs, boolean async, List<String> inputCopies) {if (originalArgs == null || originalArgs.length == 0) {return originalArgs;}@@ -267,6 +275,14 @@ public class AutoJobAspect {try {log.debug("Using fileId {} to get file content", pdfFile.getFileId());MultipartFile file = fileStorage.retrieveFile(pdfFile.getFileId());+ if (async) {+ // The stored file is read lazily, and the source may expire or be+ // deleted while the job is queued, so the job gets its own copy.+ String copyId = fileStorage.storeFile(file);+ inputCopies.add(copyId);+ recordPendingInputFile(copyId);+ file = fileStorage.retrieveFile(copyId);+ }pdfFile.setFileInput(file);} catch (Exception e) {throw new RuntimeException(@@ -279,6 +295,7 @@ public class AutoJobAspect {log.debug("Making persistent copy of uploaded file for async processing");MultipartFile originalFile = pdfFile.getFileInput();String fileId = fileStorage.storeFile(originalFile);+ inputCopies.add(fileId);// Store the fileId for later referencepdfFile.setFileId(fileId);@@ -300,6 +317,21 @@ public class AutoJobAspect {return originalArgs;}+ private void discardInputCopies(List<String> inputCopies) {+ for (String fileId : inputCopies) {+ try {+ if (!fileStorage.deleteFileAsSystem(fileId)) {+ log.warn("Could not delete failed input copy {}", fileId);+ }+ } catch (RuntimeException cleanupFailure) {+ log.warn(+ "Could not delete failed input copy {}: {}",+ fileId,+ cleanupFailure.getMessage());+ }+ }+ }+/*** Queue an input copy for attribution to the job. The job id does not exist yet at this point,* so {@link JobExecutorService} drains this list once it mints one.diff --git a/app/common/src/main/java/stirling/software/common/service/CustomPDFDocumentFactory.java b/app/common/src/main/java/stirling/software/common/service/CustomPDFDocumentFactory.javaindex 94f3dc9c5e..4be08f2883 100644--- a/app/common/src/main/java/stirling/software/common/service/CustomPDFDocumentFactory.java+++ b/app/common/src/main/java/stirling/software/common/service/CustomPDFDocumentFactory.java@@ -33,6 +33,7 @@ import org.apache.pdfbox.io.RandomAccessStreamCache.StreamCacheCreateFunction;import org.apache.pdfbox.io.ScratchFile;import org.apache.pdfbox.pdmodel.PDDocument;import org.springframework.beans.factory.annotation.Autowired;+import org.springframework.core.io.InputStreamSource;import org.springframework.stereotype.Component;import org.springframework.web.multipart.MultipartFile;@@ -240,7 +241,7 @@ public class CustomPDFDocumentFactory {if (size > 0 && size <= SMALL_FILE_THRESHOLD) {return load(pdfFile.getBytes(), readOnly);}- return streamToTemp(pdfFile.getInputStream(), null, readOnly);+ return streamToTemp(pdfFile, true, null, readOnly);}public PDDocument load(MultipartFile fileInput, String password) throws IOException {@@ -249,7 +250,7 @@ public class CustomPDFDocumentFactory {public PDDocument load(MultipartFile fileInput, String password, boolean readOnly)throws IOException {- return streamToTemp(fileInput.getInputStream(), password, readOnly);+ return streamToTemp(fileInput, true, password, readOnly);}/**@@ -550,10 +551,27 @@ public class CustomPDFDocumentFactory {/** Buffers an {@link InputStream} to a managed temp file then delegates to the core loader. */private PDDocument streamToTemp(InputStream input, String password, boolean readOnly)throws IOException {+ return streamToTemp(() -> input, false, password, readOnly);+ }++ /**+ * With {@code closeInput}, the stream is closed once buffered and before parsing, so a failed+ * close cannot strand an already-loaded document.+ */+ private PDDocument streamToTemp(+ InputStreamSource source, boolean closeInput, String password, boolean readOnly)+ throws IOException {Path tempFile = createTempFilePath("pdf-stream-");boolean success = false;try {- Files.copy(input, tempFile, StandardCopyOption.REPLACE_EXISTING);+ InputStream input = source.getInputStream();+ if (closeInput) {+ try (input) {+ Files.copy(input, tempFile, StandardCopyOption.REPLACE_EXISTING);+ }+ } else {+ Files.copy(input, tempFile, StandardCopyOption.REPLACE_EXISTING);+ }PDDocument doc = loadAdaptively(tempFile.toFile(), Files.size(tempFile), password);try {PDDocument result = maybePostProcess(doc, readOnly);diff --git a/app/common/src/main/java/stirling/software/common/service/FileOrUploadService.java b/app/common/src/main/java/stirling/software/common/service/FileOrUploadService.javaindex 0b72d3dc8e..581ed08dc5 100644--- a/app/common/src/main/java/stirling/software/common/service/FileOrUploadService.java+++ b/app/common/src/main/java/stirling/software/common/service/FileOrUploadService.java@@ -1,10 +1,12 @@package stirling.software.common.service;-import java.io.ByteArrayInputStream;+import java.io.File;import java.io.IOException;+import java.io.InputStream;import java.nio.file.*;import org.springframework.beans.factory.annotation.Value;+import org.springframework.core.io.InputStreamSource;import org.springframework.stereotype.Service;import org.springframework.web.multipart.MultipartFile;@@ -21,18 +23,25 @@ public class FileOrUploadService {return Path.of(tempDirPath).resolve(fileId);}- public MultipartFile toMockMultipartFile(String name, byte[] data) throws IOException {- return new CustomMultipartFile(name, data);+ /**+ * MultipartFile over stored content that is read on demand rather than held in the heap. Each+ * {@code getInputStream()} opens a new stream (a file handle or S3 connection) that the caller+ * must close.+ */+ public MultipartFile toStreamingMultipartFile(+ String name, long size, InputStreamSource source) {+ return new StreamingMultipartFile(name, size, source);}- // Custom implementation of MultipartFile- private static class CustomMultipartFile implements MultipartFile {+ private static class StreamingMultipartFile implements MultipartFile {private final String name;- private final byte[] content;+ private final long size;+ private final InputStreamSource source;- public CustomMultipartFile(String name, byte[] content) {+ StreamingMultipartFile(String name, long size, InputStreamSource source) {this.name = name;- this.content = content;+ this.size = size;+ this.source = source;}@Override@@ -52,27 +61,31 @@ public class FileOrUploadService {@Overridepublic boolean isEmpty() {- return content == null || content.length == 0;+ return size == 0;}@Overridepublic long getSize() {- return content.length;+ return size;}@Overridepublic byte[] getBytes() throws IOException {- return content;+ try (InputStream in = source.getInputStream()) {+ return in.readAllBytes();+ }}@Override- public java.io.InputStream getInputStream() throws IOException {- return new ByteArrayInputStream(content);+ public InputStream getInputStream() throws IOException {+ return source.getInputStream();}@Override- public void transferTo(java.io.File dest) throws IOException, IllegalStateException {- Files.write(dest.toPath(), content);+ public void transferTo(File dest) throws IOException, IllegalStateException {+ try (InputStream in = source.getInputStream()) {+ Files.copy(in, dest.toPath(), StandardCopyOption.REPLACE_EXISTING);+ }}}}diff --git a/app/common/src/main/java/stirling/software/common/service/FileStorage.java b/app/common/src/main/java/stirling/software/common/service/FileStorage.javaindex ec14490e32..6d94b78525 100644--- a/app/common/src/main/java/stirling/software/common/service/FileStorage.java+++ b/app/common/src/main/java/stirling/software/common/service/FileStorage.java@@ -76,8 +76,8 @@ public class FileStorage {public MultipartFile retrieveFile(String fileId) throws IOException {enforceOwnership(fileId);- byte[] fileData = fileStore.retrieveBytes(fileId);- return fileOrUploadService.toMockMultipartFile(fileId, fileData);+ return fileOrUploadService.toStreamingMultipartFile(+ fileId, fileStore.size(fileId), () -> fileStore.retrieve(fileId));}public byte[] retrieveBytes(String fileId) throws IOException {@@ -193,8 +193,8 @@ public class FileStorage {* unauthenticated scheduled task. Routing those through {@link #deleteFile(String)} makes the* ownership check throw and silently orphans the files on disk.*- * <p>Only ever pass file ids read back off a job that the caller has already been authorised- * for; never a caller-supplied id.+ * <p>Only pass file ids from an authorised job, or ids just returned by {@link #storeFile} for+ * trusted pre-submission copies; never a caller-supplied id.*/public boolean deleteFileAsSystem(String fileId) {return fileStore.delete(fileId);diff --git a/app/common/src/main/java/stirling/software/common/service/JobExecutorService.java b/app/common/src/main/java/stirling/software/common/service/JobExecutorService.javaindex 5ea32dbe5b..614091c1d1 100644--- a/app/common/src/main/java/stirling/software/common/service/JobExecutorService.java+++ b/app/common/src/main/java/stirling/software/common/service/JobExecutorService.java@@ -10,6 +10,7 @@ import java.util.Set;import java.util.UUID;import java.util.concurrent.CompletableFuture;import java.util.concurrent.ExecutorService;+import java.util.concurrent.RejectedExecutionException;import java.util.concurrent.TimeUnit;import java.util.concurrent.TimeoutException;import java.util.function.Supplier;@@ -173,6 +174,14 @@ public class JobExecutorService {CompletableFuture<ResponseEntity<?>> future =jobQueue.queueJob(jobId, resourceWeight, wrappedWork, timeoutToUse);+ // A rejected job never runs, so fail its task here; otherwise the client polls+ // forever and the abandoned-task sweep drops it without deleting its input copies.+ future.whenComplete(+ (ignored, failure) -> {+ if (failure instanceof RejectedExecutionException) {+ taskManager.setError(capturedJobIdForQueue, failure.getMessage());+ }+ });return ResponseEntity.ok().body(new JobResponse<>(true, jobId, null));} else if (async) {@@ -181,28 +190,33 @@ public class JobExecutorService {final String capturedJobId = jobId;- executor.execute(- () -> {- try {- log.debug(- "Running async job {} with timeout {} ms",- capturedJobId,- timeoutToUse);-- stirling.software.common.util.JobContext.setJobId(capturedJobId);- stirling.software.common.util.JobContext.setOwner(jobOwner);- Object result = executeWithTimeout(() -> work.get(), timeoutToUse);- processJobResult(capturedJobId, result);- } catch (TimeoutException te) {- log.error("Job {} timed out after {} ms", jobId, timeoutToUse);- taskManager.setError(jobId, "Job timed out");- } catch (Exception e) {- log.error("Error executing job {}: {}", jobId, e.getMessage(), e);- taskManager.setError(jobId, e.getMessage());- } finally {- stirling.software.common.util.JobContext.clear();- }- });+ try {+ executor.execute(+ () -> {+ try {+ log.debug(+ "Running async job {} with timeout {} ms",+ capturedJobId,+ timeoutToUse);++ stirling.software.common.util.JobContext.setJobId(capturedJobId);+ stirling.software.common.util.JobContext.setOwner(jobOwner);+ Object result = executeWithTimeout(() -> work.get(), timeoutToUse);+ processJobResult(capturedJobId, result);+ } catch (TimeoutException te) {+ log.error("Job {} timed out after {} ms", jobId, timeoutToUse);+ taskManager.setError(jobId, "Job timed out");+ } catch (Exception e) {+ log.error("Error executing job {}: {}", jobId, e.getMessage(), e);+ taskManager.setError(jobId, e.getMessage());+ } finally {+ stirling.software.common.util.JobContext.clear();+ }+ });+ } catch (RejectedExecutionException e) {+ // Executor shut down: fail the task so its input copies are cleaned up.+ taskManager.setError(capturedJobId, "Job rejected: " + e.getMessage());+ }return ResponseEntity.ok().body(new JobResponse<>(true, jobId, null));} else {diff --git a/app/common/src/main/java/stirling/software/common/service/JobQueue.java b/app/common/src/main/java/stirling/software/common/service/JobQueue.javaindex 38d393b053..a786a7c217 100644--- a/app/common/src/main/java/stirling/software/common/service/JobQueue.java+++ b/app/common/src/main/java/stirling/software/common/service/JobQueue.java@@ -206,7 +206,8 @@ public class JobQueue implements SmartLifecycle {log.warn("Queue full, rejecting job {}", jobId);rejectedJobs++;future.completeExceptionally(- new RuntimeException("Job queue full, please try again later"));+ new RejectedExecutionException(+ "Job queue full, please try again later"));jobMap.remove(jobId);return future;}@@ -220,7 +221,8 @@ public class JobQueue implements SmartLifecycle {return future;} catch (InterruptedException e) {Thread.currentThread().interrupt();- future.completeExceptionally(new RuntimeException("Job queue interrupted"));+ future.completeExceptionally(+ new RejectedExecutionException("Job queue interrupted", e));jobMap.remove(jobId);return future;}diff --git a/app/common/src/test/java/stirling/software/common/annotations/AutoJobPostMappingIntegrationTest.java b/app/common/src/test/java/stirling/software/common/annotations/AutoJobPostMappingIntegrationTest.javaindex 4e7b983046..2b9b80bdf1 100644--- a/app/common/src/test/java/stirling/software/common/annotations/AutoJobPostMappingIntegrationTest.java+++ b/app/common/src/test/java/stirling/software/common/annotations/AutoJobPostMappingIntegrationTest.java@@ -5,11 +5,17 @@ import static org.mockito.ArgumentMatchers.any;import static org.mockito.ArgumentMatchers.anyBoolean;import static org.mockito.ArgumentMatchers.anyInt;import static org.mockito.ArgumentMatchers.anyLong;+import static org.mockito.ArgumentMatchers.anyString;+import static org.mockito.ArgumentMatchers.eq;import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.never;import static org.mockito.Mockito.times;import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.verifyNoInteractions;import static org.mockito.Mockito.when;+import java.io.IOException;+import java.util.List;import java.util.Optional;import java.util.concurrent.CompletableFuture;import java.util.function.Supplier;@@ -81,7 +87,10 @@ class AutoJobPostMappingIntegrationTest {when(autoJobPostMapping.resourceWeight()).thenReturn(75);MultipartFile mockFile = mock(MultipartFile.class);+ MultipartFile copy = mock(MultipartFile.class);when(fileStorage.retrieveFile("test-file-id")).thenReturn(mockFile);+ when(fileStorage.storeFile(mockFile)).thenReturn("copy-id");+ when(fileStorage.retrieveFile("copy-id")).thenReturn(copy);when(jobExecutorService.runJobGeneric(anyBoolean(), any(Supplier.class), anyLong(), anyBoolean(), anyInt()))@@ -106,8 +115,148 @@ class AutoJobPostMappingIntegrationTest {assertTrue(queueableCaptor.getValue(), "Queueable should be true");assertEquals(75, resourceWeightCaptor.getValue(), "Resource weight should be 75");- // Test that file was resolved- assertNotNull(pdfFile.getFileInput(), "File input should be set");+ // The queued job reads its own copy, which is cleaned up with the job+ assertSame(copy, pdfFile.getFileInput());+ verify(request)+ .setAttribute(+ eq(JobExecutorService.PENDING_INPUT_FILE_IDS_ATTR), eq(List.of("copy-id")));+ }++ @Test+ void syncFileIdInputReadsStoredFileWithoutCopy() throws Throwable {+ PDFFile pdfFile = new PDFFile();+ pdfFile.setFileId("test-file-id");+ when(joinPoint.getArgs()).thenReturn(new Object[] {pdfFile});+ when(request.getParameter("async")).thenReturn("false");+ when(autoJobPostMapping.retryCount()).thenReturn(1);+ MultipartFile stored = mock(MultipartFile.class);+ when(fileStorage.retrieveFile("test-file-id")).thenReturn(stored);+ when(jobExecutorService.runJobGeneric(+ anyBoolean(), any(Supplier.class), anyLong(), anyBoolean(), anyInt()))+ .thenReturn(ResponseEntity.ok("success"));++ autoJobAspect.wrapWithJobExecution(joinPoint, autoJobPostMapping);++ assertSame(stored, pdfFile.getFileInput());+ verify(fileStorage, never()).storeFile(any(MultipartFile.class));+ }++ @Test+ void failedCopyRetrievalDeletesOnlyTheNewCopy() throws Exception {+ PDFFile input = new PDFFile();+ input.setFileId("source-id");+ MultipartFile source = mock(MultipartFile.class);+ IOException failure = new IOException("copy retrieval failed");+ when(joinPoint.getArgs()).thenReturn(new Object[] {input});+ when(request.getParameter("async")).thenReturn("true");+ when(fileStorage.retrieveFile("source-id")).thenReturn(source);+ when(fileStorage.storeFile(source)).thenReturn("copy-id");+ when(fileStorage.retrieveFile("copy-id")).thenThrow(failure);+ when(fileStorage.deleteFileAsSystem("copy-id")).thenReturn(true);++ RuntimeException result =+ assertThrows(+ RuntimeException.class,+ () -> autoJobAspect.wrapWithJobExecution(joinPoint, autoJobPostMapping));++ assertSame(failure, result.getCause());+ verify(fileStorage).deleteFileAsSystem("copy-id");+ verify(fileStorage, never()).deleteFileAsSystem("source-id");+ verifyNoInteractions(jobExecutorService);+ }++ @Test+ void cleanupFailureDoesNotHideTheRetrievalFailure() throws Exception {+ PDFFile input = new PDFFile();+ input.setFileId("source-id");+ MultipartFile source = mock(MultipartFile.class);+ IOException failure = new IOException("copy retrieval failed");+ when(joinPoint.getArgs()).thenReturn(new Object[] {input});+ when(request.getParameter("async")).thenReturn("true");+ when(fileStorage.retrieveFile("source-id")).thenReturn(source);+ when(fileStorage.storeFile(source)).thenReturn("copy-id");+ when(fileStorage.retrieveFile("copy-id")).thenThrow(failure);+ when(fileStorage.deleteFileAsSystem("copy-id"))+ .thenThrow(new IllegalStateException("cleanup failed"));++ RuntimeException result =+ assertThrows(+ RuntimeException.class,+ () -> autoJobAspect.wrapWithJobExecution(joinPoint, autoJobPostMapping));++ assertSame(failure, result.getCause());+ verify(fileStorage).deleteFileAsSystem("copy-id");+ verifyNoInteractions(jobExecutorService);+ }++ @Test+ void failedUploadCopyRetrievalDeletesTheCopy() throws Exception {+ PDFFile input = new PDFFile();+ MultipartFile upload = mock(MultipartFile.class);+ input.setFileInput(upload);+ IOException failure = new IOException("upload copy retrieval failed");+ when(joinPoint.getArgs()).thenReturn(new Object[] {input});+ when(request.getParameter("async")).thenReturn("true");+ when(fileStorage.storeFile(upload)).thenReturn("upload-copy");+ when(fileStorage.retrieveFile("upload-copy")).thenThrow(failure);+ when(fileStorage.deleteFileAsSystem("upload-copy")).thenReturn(true);++ RuntimeException result =+ assertThrows(+ RuntimeException.class,+ () -> autoJobAspect.wrapWithJobExecution(joinPoint, autoJobPostMapping));++ assertSame(failure, result.getCause());+ verify(fileStorage).deleteFileAsSystem("upload-copy");+ verifyNoInteractions(jobExecutorService);+ }++ @Test+ void laterInputFailureRollsBackAllCopiesMadeForTheRequest() throws Exception {+ PDFFile first = new PDFFile();+ PDFFile second = new PDFFile();+ first.setFileId("source-one");+ second.setFileId("source-two");+ MultipartFile sourceOne = mock(MultipartFile.class);+ MultipartFile sourceTwo = mock(MultipartFile.class);+ when(joinPoint.getArgs()).thenReturn(new Object[] {first, second});+ when(request.getParameter("async")).thenReturn("true");+ when(fileStorage.retrieveFile("source-one")).thenReturn(sourceOne);+ when(fileStorage.retrieveFile("source-two")).thenReturn(sourceTwo);+ when(fileStorage.storeFile(sourceOne)).thenReturn("copy-one");+ when(fileStorage.storeFile(sourceTwo)).thenReturn("copy-two");+ when(fileStorage.retrieveFile("copy-one")).thenReturn(mock(MultipartFile.class));+ when(fileStorage.retrieveFile("copy-two"))+ .thenThrow(new IOException("second input failed"));+ when(fileStorage.deleteFileAsSystem("copy-one")).thenReturn(true);+ when(fileStorage.deleteFileAsSystem("copy-two")).thenReturn(true);++ assertThrows(+ RuntimeException.class,+ () -> autoJobAspect.wrapWithJobExecution(joinPoint, autoJobPostMapping));++ verify(fileStorage).deleteFileAsSystem("copy-one");+ verify(fileStorage).deleteFileAsSystem("copy-two");+ verify(fileStorage, never()).deleteFileAsSystem("source-one");+ verify(fileStorage, never()).deleteFileAsSystem("source-two");+ verifyNoInteractions(jobExecutorService);+ }++ @Test+ void sourceRetrievalFailureDoesNotDeleteTheSource() throws Exception {+ PDFFile input = new PDFFile();+ input.setFileId("source-id");+ when(joinPoint.getArgs()).thenReturn(new Object[] {input});+ when(request.getParameter("async")).thenReturn("true");+ when(fileStorage.retrieveFile("source-id"))+ .thenThrow(new IOException("source unavailable"));++ assertThrows(+ RuntimeException.class,+ () -> autoJobAspect.wrapWithJobExecution(joinPoint, autoJobPostMapping));++ verify(fileStorage, never()).deleteFileAsSystem(anyString());+ verifyNoInteractions(jobExecutorService);}@Testdiff --git a/app/common/src/test/java/stirling/software/common/service/CustomPDFDocumentFactoryMoreTest.java b/app/common/src/test/java/stirling/software/common/service/CustomPDFDocumentFactoryMoreTest.javaindex 1c5a0d2dff..0126e48536 100644--- a/app/common/src/test/java/stirling/software/common/service/CustomPDFDocumentFactoryMoreTest.java+++ b/app/common/src/test/java/stirling/software/common/service/CustomPDFDocumentFactoryMoreTest.java@@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat;import static org.assertj.core.api.Assertions.assertThatThrownBy;import static org.mockito.Mockito.mock;import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.when;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;@@ -12,6 +13,9 @@ import java.io.IOException;import java.io.InputStream;import java.nio.file.Files;import java.nio.file.Path;+import java.util.ArrayList;+import java.util.List;+import java.util.concurrent.atomic.AtomicInteger;import org.apache.pdfbox.io.MemoryUsageSetting;import org.apache.pdfbox.io.RandomAccessStreamCache.StreamCacheCreateFunction;@@ -26,6 +30,7 @@ import org.junit.jupiter.api.Test;import org.junit.jupiter.api.io.TempDir;import org.springframework.http.MediaType;import org.springframework.mock.web.MockMultipartFile;+import org.springframework.web.multipart.MultipartFile;class CustomPDFDocumentFactoryMoreTest {@@ -177,4 +182,78 @@ class CustomPDFDocumentFactoryMoreTest {return out.toByteArray();}}++ @Nested+ @DisplayName("MultipartFile streams")+ class MultipartStreams {++ @Test+ @DisplayName("closes the stream it opens for large and password-protected loads")+ void closesOpenedStream() throws IOException {+ List<ClosingTracker> opened = new ArrayList<>();+ MultipartFile file = mock(MultipartFile.class);+ when(file.getSize()).thenReturn(CustomPDFDocumentFactory.SMALL_FILE_THRESHOLD + 1);+ when(file.getInputStream())+ .thenAnswer(+ invocation -> {+ ClosingTracker in = new ClosingTracker(basePdfBytes);+ opened.add(in);+ return in;+ });++ try (PDDocument doc = factory.load(file, false)) {+ assertThat(doc.getNumberOfPages()).isPositive();+ }+ try (PDDocument doc = factory.load(file, (String) null)) {+ assertThat(doc.getNumberOfPages()).isPositive();+ }++ assertThat(opened).hasSize(2).allMatch(in -> in.closed);+ }++ @Test+ @DisplayName("fails before parsing when closing the stream fails")+ void closeFailureLeavesNoDocument() throws IOException {+ AtomicInteger parses = new AtomicInteger();+ CustomPDFDocumentFactory countingFactory =+ new CustomPDFDocumentFactory(mock(PdfMetadataService.class)) {+ @Override+ protected StreamCacheCreateFunction getStreamCacheFunction(+ long contentSize, MemorySnapshot mem) {+ parses.incrementAndGet();+ return super.getStreamCacheFunction(contentSize, mem);+ }+ };+ MultipartFile file = mock(MultipartFile.class);+ when(file.getSize()).thenReturn(CustomPDFDocumentFactory.SMALL_FILE_THRESHOLD + 1);+ when(file.getInputStream())+ .thenAnswer(+ invocation ->+ new ByteArrayInputStream(basePdfBytes) {+ @Override+ public void close() throws IOException {+ throw new IOException("close failed");+ }+ });++ assertThatThrownBy(() -> countingFactory.load(file, false)).hasMessage("close failed");+ assertThatThrownBy(() -> countingFactory.load(file, (String) null))+ .hasMessage("close failed");+ assertThat(parses).hasValue(0);+ }+ }++ private static final class ClosingTracker extends ByteArrayInputStream {+ boolean closed;++ ClosingTracker(byte[] bytes) {+ super(bytes);+ }++ @Override+ public void close() throws IOException {+ closed = true;+ super.close();+ }+ }}diff --git a/app/common/src/test/java/stirling/software/common/service/FileStorageTest.java b/app/common/src/test/java/stirling/software/common/service/FileStorageTest.javaindex 32a3cb65de..80b08214b6 100644--- a/app/common/src/test/java/stirling/software/common/service/FileStorageTest.java+++ b/app/common/src/test/java/stirling/software/common/service/FileStorageTest.java@@ -88,16 +88,26 @@ class FileStorageTest {Path filePath = tempDir.resolve(fileId);Files.write(filePath, fileContent);- MultipartFile expectedFile = mock(MultipartFile.class);- when(fileOrUploadService.toMockMultipartFile(eq(fileId), eq(fileContent)))- .thenReturn(expectedFile);+ when(fileOrUploadService.toStreamingMultipartFile(eq(fileId), anyLong(), any()))+ .thenCallRealMethod();// ActMultipartFile result = fileStorage.retrieveFile(fileId);// Assert- assertSame(expectedFile, result);- verify(fileOrUploadService).toMockMultipartFile(eq(fileId), eq(fileContent));+ assertEquals(fileContent.length, result.getSize());+ for (int i = 0; i < 2; i++) {+ try (InputStream in = result.getInputStream()) {+ assertArrayEquals(fileContent, in.readAllBytes());+ }+ }+ assertArrayEquals(fileContent, result.getBytes());+ Path copy = tempDir.resolve("copy.pdf");+ result.transferTo(copy);+ assertArrayEquals(fileContent, Files.readAllBytes(copy));+ Path fileCopy = tempDir.resolve("file-copy.pdf");+ result.transferTo(fileCopy.toFile());+ assertArrayEquals(fileContent, Files.readAllBytes(fileCopy));}@Testdiff --git a/app/common/src/test/java/stirling/software/common/service/JobExecutorServiceTest.java b/app/common/src/test/java/stirling/software/common/service/JobExecutorServiceTest.javaindex e0b7366df3..9f54c13055 100644--- a/app/common/src/test/java/stirling/software/common/service/JobExecutorServiceTest.java+++ b/app/common/src/test/java/stirling/software/common/service/JobExecutorServiceTest.java@@ -20,6 +20,7 @@ import java.net.URI;import java.nio.charset.StandardCharsets;import java.util.Map;import java.util.concurrent.CompletableFuture;+import java.util.concurrent.RejectedExecutionException;import java.util.concurrent.TimeoutException;import java.util.function.Supplier;@@ -312,6 +313,34 @@ class JobExecutorServiceTest {verify(taskManager).createTask(anyString());}+ @Test+ void rejectedQueuedJobFailsItsTask() {+ when(resourceMonitor.shouldQueueJob(80)).thenReturn(true);+ when(jobQueue.queueJob(anyString(), eq(80), any(), anyLong()))+ .thenReturn(+ CompletableFuture.failedFuture(+ new RejectedExecutionException("Job queue full")));++ ResponseEntity<?> response =+ jobExecutorService.runJobGeneric(true, () -> "unused", 5000, true, 80);++ String jobId = ((JobResponse<?>) response.getBody()).getJobId();+ verify(taskManager).setError(jobId, "Job queue full");+ }++ @Test+ void failedQueuedJobIsNotTreatedAsRejected() {+ when(resourceMonitor.shouldQueueJob(80)).thenReturn(true);+ when(jobQueue.queueJob(anyString(), eq(80), any(), anyLong()))+ .thenReturn(+ CompletableFuture.failedFuture(+ new RuntimeException("Job cancelled by user")));++ jobExecutorService.runJobGeneric(true, () -> "unused", 5000, true, 80);++ verify(taskManager, never()).setError(anyString(), anyString());+ }+@Testvoid shouldUseCustomTimeoutWhenProvided() throws Exception {// Givendiff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/SplitPDFController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/SplitPDFController.javaindex 712a123581..cba2d6fdd7 100644--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/SplitPDFController.java+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/SplitPDFController.java@@ -2,6 +2,7 @@ package stirling.software.SPDF.controller.api;import java.io.File;import java.io.IOException;+import java.io.InputStream;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.StandardCopyOption;@@ -69,10 +70,9 @@ public class SplitPDFController {TempFile outputTempFile = new TempFile(tempFileManager, ".zip");try {try (TempFile sourceTempFile = new TempFile(tempFileManager, ".pdf")) {- Files.copy(- file.getInputStream(),- sourceTempFile.getPath(),- StandardCopyOption.REPLACE_EXISTING);+ try (InputStream in = file.getInputStream()) {+ Files.copy(in, sourceTempFile.getPath(), StandardCopyOption.REPLACE_EXISTING);+ }int totalPages;List<Integer> pageNumbers;diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/SplitPdfByChaptersController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/SplitPdfByChaptersController.javaindex 06bc684c04..3508c67b0e 100644--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/SplitPdfByChaptersController.java+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/SplitPdfByChaptersController.java@@ -2,6 +2,7 @@ package stirling.software.SPDF.controller.api;import java.io.File;import java.io.IOException;+import java.io.InputStream;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.StandardCopyOption;@@ -112,10 +113,9 @@ public class SplitPdfByChaptersController {}try (TempFile sourceTempFile = new TempFile(tempFileManager, ".pdf")) {- Files.copy(- file.getInputStream(),- sourceTempFile.getPath(),- StandardCopyOption.REPLACE_EXISTING);+ try (InputStream in = file.getInputStream()) {+ Files.copy(in, sourceTempFile.getPath(), StandardCopyOption.REPLACE_EXISTING);+ }List<Bookmark> bookmarks = new ArrayList<>();int totalPages;diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/SplitPdfBySizeController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/SplitPdfBySizeController.javaindex becf119130..2d662d2a44 100644--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/SplitPdfBySizeController.java+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/SplitPdfBySizeController.java@@ -2,6 +2,7 @@ package stirling.software.SPDF.controller.api;import java.io.File;import java.io.IOException;+import java.io.InputStream;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.StandardCopyOption;@@ -77,10 +78,9 @@ public class SplitPdfBySizeController {try (TempFile sourceTempFile = new TempFile(tempFileManager, ".pdf");ZipOutputStream zipOut =new ZipOutputStream(Files.newOutputStream(zipTempFile.getPath()))) {- Files.copy(- file.getInputStream(),- sourceTempFile.getPath(),- StandardCopyOption.REPLACE_EXISTING);+ try (InputStream in = file.getInputStream()) {+ Files.copy(in, sourceTempFile.getPath(), StandardCopyOption.REPLACE_EXISTING);+ }boolean hasForm;try (PDDocument acroDoc = pdfDocumentFactory.load(sourceTempFile.getFile(), true)) {diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/AutoSplitPdfController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/AutoSplitPdfController.javaindex ecf1aa2960..4b1a641acd 100644--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/AutoSplitPdfController.java+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/AutoSplitPdfController.java@@ -3,6 +3,7 @@ package stirling.software.SPDF.controller.api.misc;import java.awt.Graphics2D;import java.awt.image.BufferedImage;import java.io.IOException;+import java.io.InputStream;import java.io.OutputStream;import java.nio.file.Files;import java.util.ArrayList;@@ -297,7 +298,8 @@ public class AutoSplitPdfController {List<PDDocument> splitDocuments = new ArrayList<>();TempFile outputTempFile = new TempFile(tempFileManager, ".zip");- try (PDDocument document = pdfDocumentFactory.load(file.getInputStream())) {+ try (InputStream in = file.getInputStream();+ PDDocument document = pdfDocumentFactory.load(in)) {int totalPages = document.getNumberOfPages();log.info("PDF loaded, totalPages={}", totalPages);diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/PrintFileController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/PrintFileController.javaindex 82184b68ba..8274eda4ca 100644--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/PrintFileController.java+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/PrintFileController.java@@ -7,6 +7,7 @@ import java.awt.print.Printable;import java.awt.print.PrinterException;import java.awt.print.PrinterJob;import java.io.IOException;+import java.io.InputStream;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.StandardCopyOption;@@ -82,8 +83,9 @@ public class PrintFileController {// Use Stream-to-File pattern: write to temp file first, then load from filePath tempFile = Files.createTempFile("print-", ".pdf");try {- Files.copy(- file.getInputStream(), tempFile, StandardCopyOption.REPLACE_EXISTING);+ try (InputStream in = file.getInputStream()) {+ Files.copy(in, tempFile, StandardCopyOption.REPLACE_EXISTING);+ }try (PDDocument document = Loader.loadPDF(tempFile.toFile())) {PrinterJob job = PrinterJob.getPrinterJob();job.setPrintService(selectedService);diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/security/GetInfoOnPDF.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/security/GetInfoOnPDF.javaindex 564e787fe2..d44427073b 100644--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/security/GetInfoOnPDF.java+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/security/GetInfoOnPDF.java@@ -2,6 +2,7 @@ package stirling.software.SPDF.controller.api.security;import java.io.ByteArrayOutputStream;import java.io.IOException;+import java.io.InputStream;import java.nio.charset.StandardCharsets;import java.time.Instant;import java.time.ZoneId;@@ -1127,7 +1128,9 @@ public class GetInfoOnPDF {List<PDFVerificationResult> verificationResults = null;try {- verificationResults = veraPDFService.validatePDF(inputFile.getInputStream());+ try (InputStream in = inputFile.getInputStream()) {+ verificationResults = veraPDFService.validatePDF(in);+ }} catch (Exception e) {log.error("VeraPDF validation failed", e);}diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/security/ValidateSignatureController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/security/ValidateSignatureController.javaindex c807a68bc8..7fb5a01d5f 100644--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/security/ValidateSignatureController.java+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/security/ValidateSignatureController.java@@ -3,6 +3,7 @@ package stirling.software.SPDF.controller.api.security;import java.beans.PropertyEditorSupport;import java.io.ByteArrayInputStream;import java.io.IOException;+import java.io.InputStream;import java.security.cert.CertificateException;import java.security.cert.CertificateFactory;import java.security.cert.PKIXCertPathBuilderResult;@@ -107,7 +108,8 @@ public class ValidateSignatureController {}}- try (PDDocument document = pdfDocumentFactory.load(file.getInputStream())) {+ try (InputStream in = file.getInputStream();+ PDDocument document = pdfDocumentFactory.load(in)) {List<PDSignature> signatures = document.getSignatureDictionaries();// Detect content appended outside every signature's ByteRange (added after signing). A@@ -133,8 +135,16 @@ public class ValidateSignatureController {result.setCoversEntireDocument(documentCovered);try {- byte[] signedContent = sig.getSignedContent(file.getInputStream());- byte[] signatureBytes = sig.getContents(file.getInputStream());+ // Opened one after the other: an S3 stream left unread while the other is+ // consumed can be aborted by the SDK's idle timeout.+ byte[] signedContent;+ try (InputStream signedIn = file.getInputStream()) {+ signedContent = sig.getSignedContent(signedIn);+ }+ byte[] signatureBytes;+ try (InputStream contentsIn = file.getInputStream()) {+ signatureBytes = sig.getContents(contentsIn);+ }// An RFC 3161 document timestamp (PAdES-LTV) carries its signed content// *inside* the CMS - a TSTInfo - rather than being detached over the document.diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/security/VerifyPDFController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/security/VerifyPDFController.javaindex 4226005c8e..5c7bcde521 100644--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/security/VerifyPDFController.java+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/security/VerifyPDFController.java@@ -1,6 +1,7 @@package stirling.software.SPDF.controller.api.security;import java.io.IOException;+import java.io.InputStream;import java.util.List;import org.springframework.http.MediaType;@@ -57,7 +58,10 @@ public class VerifyPDFController {try {log.info("Detecting and verifying standards in PDF '{}'", file.getOriginalFilename());- List<PDFVerificationResult> results = veraPDFService.validatePDF(file.getInputStream());+ List<PDFVerificationResult> results;+ try (InputStream in = file.getInputStream()) {+ results = veraPDFService.validatePDF(in);+ }log.info("Verification complete for '{}': {} standard(s) checked",diff --git a/app/core/src/main/java/stirling/software/common/controller/JobController.java b/app/core/src/main/java/stirling/software/common/controller/JobController.javaindex c6fec4b92b..f4527bc82f 100644--- a/app/core/src/main/java/stirling/software/common/controller/JobController.java+++ b/app/core/src/main/java/stirling/software/common/controller/JobController.java@@ -7,6 +7,7 @@ import java.util.Map;import java.util.Optional;import org.springframework.beans.factory.annotation.Autowired;+import org.springframework.core.io.InputStreamResource;import org.springframework.http.MediaType;import org.springframework.http.ResponseEntity;import org.springframework.web.bind.annotation.DeleteMapping;@@ -140,13 +141,15 @@ public class JobController {List<ResultFile> files = result.getAllResultFiles();ResultFile singleFile = files.getFirst();- byte[] fileContent = fileStorage.retrieveBytes(singleFile.getFileId());return ResponseEntity.ok().header("Content-Type", singleFile.getContentType()).header("Content-Disposition",createContentDispositionHeader(singleFile.getFileName()))- .body(fileContent);+ .contentLength(fileStorage.getFileSize(singleFile.getFileId()))+ .body(+ new InputStreamResource(+ fileStorage.retrieveInputStream(singleFile.getFileId())));} catch (Exception e) {log.error("Error retrieving file for job {}: {}", jobId, e.getMessage(), e);return ResponseEntity.internalServerError()@@ -182,13 +185,13 @@ public class JobController {log.info("Cancelled queued job: {} (was at position {})", jobId, queuePosition);}- if (!cancelled) {- JobResult result = taskManager.getJobResult(jobId);- if (result != null && !result.isComplete()) {- taskManager.setError(jobId, "Job was cancelled by user");- cancelled = true;- log.info("Marked job as cancelled in TaskManager: {}", jobId);- }+ // Also for a job just removed from the queue: a task left incomplete is later swept+ // without deleting its input copies.+ JobResult result = taskManager.getJobResult(jobId);+ if (result != null && !result.isComplete()) {+ taskManager.setError(jobId, "Job was cancelled by user");+ cancelled = true;+ log.info("Marked job as cancelled in TaskManager: {}", jobId);}if (cancelled) {@@ -201,7 +204,6 @@ public class JobController {"queuePosition",queuePosition >= 0 ? queuePosition : "n/a"));} else {- JobResult result = taskManager.getJobResult(jobId);if (result == null) {return ResponseEntity.notFound().build();} else if (result.isComplete()) {@@ -368,12 +370,11 @@ public class JobController {? resultFile.getContentType(): MediaType.APPLICATION_OCTET_STREAM_VALUE;- byte[] fileContent = fileStorage.retrieveBytes(fileId);-return ResponseEntity.ok().header("Content-Type", contentType).header("Content-Disposition", createContentDispositionHeader(fileName))- .body(fileContent);+ .contentLength(fileStorage.getFileSize(fileId))+ .body(new InputStreamResource(fileStorage.retrieveInputStream(fileId)));} catch (Exception e) {log.error("Error retrieving file {}: {}", fileId, e.getMessage(), e);return ResponseEntity.internalServerError().body("Error retrieving file");diff --git a/app/core/src/test/java/stirling/software/common/controller/JobControllerOwnershipTest.java b/app/core/src/test/java/stirling/software/common/controller/JobControllerOwnershipTest.javaindex 040f729201..02331865db 100644--- a/app/core/src/test/java/stirling/software/common/controller/JobControllerOwnershipTest.java+++ b/app/core/src/test/java/stirling/software/common/controller/JobControllerOwnershipTest.java@@ -12,6 +12,7 @@ import static org.mockito.Mockito.times;import static org.mockito.Mockito.verify;import static org.mockito.Mockito.when;+import java.io.ByteArrayInputStream;import java.time.Instant;import java.util.List;import java.util.Map;@@ -129,7 +130,7 @@ class JobControllerOwnershipTest {assertNull(body.get("internalSecret"));assertNull(body.get("filePath"));verify(stickyMissRecorder).recordStickyMiss();- verify(fileStorage, never()).retrieveBytes(FILE_ID);+ verify(fileStorage, never()).retrieveInputStream(FILE_ID);}private static Stream<Arguments> downloadHappyPathScenarios() {@@ -148,12 +149,13 @@ class JobControllerOwnershipTest {when(jobStore.get(JOB_ID)).thenReturn(entryPresent ? Optional.of(entryOwnedBy(ownerNodeId)) : Optional.empty());- when(fileStorage.retrieveBytes(FILE_ID)).thenReturn("payload".getBytes());+ when(fileStorage.retrieveInputStream(FILE_ID))+ .thenReturn(new ByteArrayInputStream("payload".getBytes()));ResponseEntity<?> response = makeController().downloadFile(FILE_ID);assertEquals(HttpStatus.OK, response.getStatusCode(), scenario);- verify(fileStorage).retrieveBytes(FILE_ID);+ verify(fileStorage).retrieveInputStream(FILE_ID);verify(stickyMissRecorder, never()).recordStickyMiss();}@@ -163,7 +165,8 @@ class JobControllerOwnershipTest {when(clusterBackplane.localNodeId()).thenReturn(LOCAL_NODE);when(taskManager.getJobResult(JOB_ID)).thenReturn(completedJobWithFile());when(jobStore.get(JOB_ID)).thenReturn(Optional.of(entryOwnedBy(LOCAL_NODE)));- when(fileStorage.retrieveBytes(FILE_ID)).thenReturn("payload".getBytes());+ when(fileStorage.retrieveInputStream(FILE_ID))+ .thenReturn(new ByteArrayInputStream("payload".getBytes()));ResponseEntity<?> response = makeController().getJobResult(JOB_ID);@@ -222,7 +225,7 @@ class JobControllerOwnershipTest {assertEquals(PEER_NODE, body.get("ownedBy"));assertEquals(LOCAL_NODE, body.get("currentNode"));verify(stickyMissRecorder).recordStickyMiss();- verify(fileStorage, never()).retrieveBytes(FILE_ID);+ verify(fileStorage, never()).retrieveInputStream(FILE_ID);if (endpoint == Endpoint.CANCEL_JOB) {verify(taskManager, never()).setError(JOB_ID, "Job was cancelled by user");}@@ -256,24 +259,26 @@ class JobControllerOwnershipTest {@DisplayName("Single-instance install (no ClusterBackplane bean): no 410, no NPE")void singleInstance_noClusterBackplane_noGoneResponse() throws Exception {when(taskManager.findJobKeyByFileId(FILE_ID)).thenReturn(JOB_ID);- when(fileStorage.retrieveBytes(FILE_ID)).thenReturn("payload".getBytes());+ when(fileStorage.retrieveInputStream(FILE_ID))+ .thenReturn(new ByteArrayInputStream("payload".getBytes()));ResponseEntity<?> response = makeController(null, jobStore).downloadFile(FILE_ID);assertEquals(HttpStatus.OK, response.getStatusCode());- verify(fileStorage).retrieveBytes(FILE_ID);+ verify(fileStorage).retrieveInputStream(FILE_ID);}@Test@DisplayName("Single-instance install (no JobStore bean): no 410, no NPE")void singleInstance_noJobStore_noGoneResponse() throws Exception {when(taskManager.findJobKeyByFileId(FILE_ID)).thenReturn(JOB_ID);- when(fileStorage.retrieveBytes(FILE_ID)).thenReturn("payload".getBytes());+ when(fileStorage.retrieveInputStream(FILE_ID))+ .thenReturn(new ByteArrayInputStream("payload".getBytes()));ResponseEntity<?> response = makeController(clusterBackplane, null).downloadFile(FILE_ID);assertEquals(HttpStatus.OK, response.getStatusCode());- verify(fileStorage).retrieveBytes(FILE_ID);+ verify(fileStorage).retrieveInputStream(FILE_ID);}@Test@@ -282,7 +287,8 @@ class JobControllerOwnershipTest {when(clusterBackplane.localNodeId()).thenReturn(LOCAL_NODE);when(taskManager.findJobKeyByFileId(FILE_ID)).thenReturn(JOB_ID);when(jobStore.get(JOB_ID)).thenReturn(Optional.of(entryOwnedBy(LOCAL_NODE)));- when(fileStorage.retrieveBytes(FILE_ID)).thenReturn("payload".getBytes());+ when(fileStorage.retrieveInputStream(FILE_ID))+ .thenReturn(new ByteArrayInputStream("payload".getBytes()));JobController c = makeController();ReflectionTestUtils.setField(c, "stickyMissRecorder", null);@@ -343,7 +349,7 @@ class JobControllerOwnershipTest {assertEquals(HttpStatus.GONE, response.getStatusCode());Map<?, ?> body = (Map<?, ?>) response.getBody();assertEquals(PEER_NODE, body.get("ownedBy"));- verify(fileStorage, never()).retrieveBytes(FILE_ID);+ verify(fileStorage, never()).retrieveInputStream(FILE_ID);}@Test@@ -392,7 +398,8 @@ class JobControllerOwnershipTest {when(clusterBackplane.localNodeId()).thenReturn(LOCAL_NODE);when(taskManager.findJobKeyByFileId(FILE_ID)).thenReturn(JOB_ID);when(jobStore.get(JOB_ID)).thenReturn(Optional.of(entryOwnedBy(LOCAL_NODE)));- when(fileStorage.retrieveBytes(FILE_ID)).thenReturn("payload".getBytes());+ when(fileStorage.retrieveInputStream(FILE_ID))+ .thenReturn(new ByteArrayInputStream("payload".getBytes()));JobController c = makeController();c.downloadFile(FILE_ID);@@ -410,12 +417,13 @@ class JobControllerOwnershipTest {when(taskManager.findJobKeyByFileId(FILE_ID)).thenReturn(JOB_ID);when(jobStore.get(JOB_ID)).thenThrow(new RuntimeException("Valkey command timeout"));when(taskManager.getJobResult(JOB_ID)).thenReturn(completedJobWithFile());- when(fileStorage.retrieveBytes(FILE_ID)).thenReturn("payload".getBytes());+ when(fileStorage.retrieveInputStream(FILE_ID))+ .thenReturn(new ByteArrayInputStream("payload".getBytes()));ResponseEntity<?> response = makeController().downloadFile(FILE_ID);assertEquals(HttpStatus.OK, response.getStatusCode());- verify(fileStorage).retrieveBytes(FILE_ID);+ verify(fileStorage).retrieveInputStream(FILE_ID);verify(stickyMissRecorder, never()).recordStickyMiss();}@@ -457,7 +465,7 @@ class JobControllerOwnershipTest {assertEquals("1", response.getHeaders().getFirst("Retry-After"));Map<?, ?> body = (Map<?, ?>) response.getBody();assertTrue(((String) body.get("message")).toLowerCase().contains("unavailable"));- verify(fileStorage, never()).retrieveBytes(FILE_ID);+ verify(fileStorage, never()).retrieveInputStream(FILE_ID);}@Test@@ -474,6 +482,6 @@ class JobControllerOwnershipTest {assertEquals("1", response.getHeaders().getFirst("Retry-After"));Map<?, ?> body = (Map<?, ?>) response.getBody();assertTrue(((String) body.get("message")).toLowerCase().contains("unavailable"));- verify(fileStorage, never()).retrieveBytes(FILE_ID);+ verify(fileStorage, never()).retrieveInputStream(FILE_ID);}}diff --git a/app/core/src/test/java/stirling/software/common/controller/JobControllerTest.java b/app/core/src/test/java/stirling/software/common/controller/JobControllerTest.javaindex 2083e7339b..22bafa6246 100644--- a/app/core/src/test/java/stirling/software/common/controller/JobControllerTest.java+++ b/app/core/src/test/java/stirling/software/common/controller/JobControllerTest.java@@ -1,9 +1,9 @@package stirling.software.common.controller;import static org.junit.jupiter.api.Assertions.*;-import static org.mockito.ArgumentMatchers.anyString;import static org.mockito.Mockito.*;+import java.io.ByteArrayInputStream;import java.util.Map;import java.util.function.Predicate;@@ -13,6 +13,7 @@ import org.mockito.ArgumentCaptor;import org.mockito.InjectMocks;import org.mockito.Mock;import org.mockito.MockitoAnnotations;+import org.springframework.core.io.InputStreamResource;import org.springframework.http.HttpStatus;import org.springframework.http.MediaType;import org.springframework.http.ResponseEntity;@@ -149,7 +150,9 @@ class JobControllerTest {fileId, originalFileName, contentType, fileContent.length);when(taskManager.getJobResult(jobId)).thenReturn(mockResult);- when(fileStorage.retrieveBytes(fileId)).thenReturn(fileContent);+ when(fileStorage.retrieveInputStream(fileId))+ .thenReturn(new ByteArrayInputStream(fileContent));+ when(fileStorage.getFileSize(fileId)).thenReturn((long) fileContent.length);// ActResponseEntity<?> response = controller.getJobResult(jobId);@@ -159,7 +162,10 @@ class JobControllerTest {assertEquals(contentType, response.getHeaders().getFirst("Content-Type"));assertTrue(response.getHeaders().getFirst("Content-Disposition").contains(originalFileName));- assertEquals(fileContent, response.getBody());+ assertEquals(fileContent.length, response.getHeaders().getContentLength());+ assertArrayEquals(+ fileContent,+ ((InputStreamResource) response.getBody()).getInputStream().readAllBytes());}@Test@@ -227,7 +233,8 @@ class JobControllerTest {mockResult.completeWithSingleFile(fileId, originalFileName, contentType, 1024L);when(taskManager.getJobResult(jobId)).thenReturn(mockResult);- when(fileStorage.retrieveBytes(fileId)).thenThrow(new RuntimeException("File not found"));+ when(fileStorage.retrieveInputStream(fileId))+ .thenThrow(new RuntimeException("File not found"));// ActResponseEntity<?> response = controller.getJobResult(jobId);@@ -289,6 +296,7 @@ class JobControllerTest {when(jobQueue.isJobQueued(jobId)).thenReturn(true);when(jobQueue.getJobPosition(jobId)).thenReturn(2);when(jobQueue.cancelJob(jobId)).thenReturn(true);+ when(taskManager.getJobResult(jobId)).thenReturn(new JobResult());// ActResponseEntity<?> response = controller.cancelJob(jobId);@@ -303,7 +311,7 @@ class JobControllerTest {assertEquals(2, responseBody.get("queuePosition"));verify(jobQueue).cancelJob(jobId);- verify(taskManager, never()).setError(anyString(), anyString());+ verify(taskManager).setError(jobId, "Job was cancelled by user");}@Testdiff --git a/app/core/src/test/java/stirling/software/common/controller/JobControllerUserAccessTest.java b/app/core/src/test/java/stirling/software/common/controller/JobControllerUserAccessTest.javaindex ea1c1ce93e..c28d633244 100644--- a/app/core/src/test/java/stirling/software/common/controller/JobControllerUserAccessTest.java+++ b/app/core/src/test/java/stirling/software/common/controller/JobControllerUserAccessTest.java@@ -4,8 +4,10 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals;import static org.junit.jupiter.api.Assertions.assertEquals;import static org.mockito.Mockito.mock;import static org.mockito.Mockito.when;+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;import java.io.ByteArrayInputStream;+import java.io.InputStream;import java.nio.file.Path;import java.util.List;import java.util.Optional;@@ -15,8 +17,14 @@ import org.junit.jupiter.api.Test;import org.junit.jupiter.api.io.TempDir;import org.junit.jupiter.params.ParameterizedTest;import org.junit.jupiter.params.provider.ValueSource;+import org.springframework.core.io.InputStreamResource;+import org.springframework.http.HttpHeaders;import org.springframework.http.HttpStatus;+import org.springframework.http.ResponseEntity;import org.springframework.test.util.ReflectionTestUtils;+import org.springframework.test.web.servlet.MockMvc;+import org.springframework.test.web.servlet.MvcResult;+import org.springframework.test.web.servlet.setup.MockMvcBuilders;import jakarta.servlet.http.HttpServletRequest;@@ -112,17 +120,44 @@ class JobControllerUserAccessTest {when(users.getCurrentUsername()).thenReturn("source-owner");var response = controller.downloadFile(fileId);assertEquals(HttpStatus.OK, response.getStatusCode());- assertArrayEquals(OUTPUT, (byte[]) response.getBody());+ assertArrayEquals(OUTPUT, readBody(response));assertEquals(HttpStatus.OK, controller.getFileMetadata(fileId).getStatusCode());assertEquals(HttpStatus.OK, controller.getJobStatus(runId).getStatusCode());}+ @Test+ void downloadsStreamWholeFileWithLengthAndIgnoreRange() throws Exception {+ storeOutput(false);+ MockMvc mvc = MockMvcBuilders.standaloneSetup(controller).build();++ for (String path :+ List.of(+ "/api/v1/general/files/" + fileId,+ "/api/v1/general/job/" + runId + "/result")) {+ MvcResult result =+ mvc.perform(get(path).header(HttpHeaders.RANGE, "bytes=0-3")).andReturn();++ assertEquals(HttpStatus.OK.value(), result.getResponse().getStatus(), path);+ assertEquals(+ String.valueOf(OUTPUT.length),+ result.getResponse().getHeader(HttpHeaders.CONTENT_LENGTH),+ path);+ assertArrayEquals(OUTPUT, result.getResponse().getContentAsByteArray(), path);+ }+ }+@Testvoid loginDisabledKeepsOutputsAccessible() throws Exception {storeOutput(false);assertEquals("run", runId);var response = controller.downloadFile(fileId);assertEquals(HttpStatus.OK, response.getStatusCode());- assertArrayEquals(OUTPUT, (byte[]) response.getBody());+ assertArrayEquals(OUTPUT, readBody(response));+ }++ private static byte[] readBody(ResponseEntity<?> response) throws Exception {+ try (InputStream in = ((InputStreamResource) response.getBody()).getInputStream()) {+ return in.readAllBytes();+ }}}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/service/DocParseService.java b/app/proprietary/src/main/java/stirling/software/proprietary/service/DocParseService.javaindex 378a9225e6..08ce5a19e5 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/service/DocParseService.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/service/DocParseService.java@@ -1,6 +1,7 @@package stirling.software.proprietary.service;import java.io.IOException;+import java.io.InputStream;import java.nio.file.Files;import java.nio.file.StandardCopyOption;import java.util.ArrayList;@@ -143,10 +144,9 @@ public class DocParseService {try (TempFile tempInput = new TempFile(tempFileManager, ".pdf")) {// Copy rather than transferTo: transferTo moves the servlet part's backing file away,// and the controller still reads the upload afterwards to build the export ZIP.- Files.copy(- file.getInputStream(),- tempInput.getPath(),- StandardCopyOption.REPLACE_EXISTING);+ try (InputStream in = file.getInputStream()) {+ Files.copy(in, tempInput.getPath(), StandardCopyOption.REPLACE_EXISTING);+ }try (PdfDocument doc = PdfDocument.open(tempInput.getPath())) {sourcePages = doc.pageCount();all = markdownExtractor.extractBlocks(doc);