Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

Harden Office and PDF conversion input handling (#8717)

EthanHealy014577916c853a
diff --git a/app/common/src/main/java/stirling/software/common/util/PdfUtils.java b/app/common/src/main/java/stirling/software/common/util/PdfUtils.java
index 575d1bec51..683155f567 100644
--- a/app/common/src/main/java/stirling/software/common/util/PdfUtils.java
+++ b/app/common/src/main/java/stirling/software/common/util/PdfUtils.java
@@ -103,6 +103,33 @@ public class PdfUtils {
}
}
+ /**
+ * Rejects, before rendering, any embedded image whose decoded raster exceeds the limit. The
+ * page render bounds the output canvas, not the intermediate raster PDFBox decodes each image
+ * into, so each image is sized here (soft masks and self-sizing codecs included) up front.
+ */
+ private void requireEmbeddedImagesFit(PDDocument document) throws IOException {
+ Set<COSDictionary> visited = Collections.newSetFromMap(new IdentityHashMap<>());
+ for (PDPage page : document.getPages()) {
+ requireImagesFit(page.getResources(), visited);
+ }
+ }
+
+ private void requireImagesFit(PDResources resources, Set<COSDictionary> visited)
+ throws IOException {
+ if (resources == null || !visited.add(resources.getCOSObject())) {
+ return;
+ }
+ for (COSName name : resources.getXObjectNames()) {
+ PDXObject object = resources.getXObject(name);
+ if (object instanceof PDImageXObject image) {
+ ImageMemoryLimit.requireEmbeddedImageFits(image);
+ } else if (object instanceof PDFormXObject form) {
+ requireImagesFit(form.getResources(), visited);
+ }
+ }
+ }
+
private boolean containsImage(PDResources resources, Set<COSDictionary> visited)
throws IOException {
if (resources == null || !visited.add(resources.getCOSObject())) {
@@ -203,6 +230,7 @@ public class PdfUtils {
try (PDDocument document = pdfDocumentFactory.load(inputStream);
ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
+ requireEmbeddedImagesFit(document);
PDFRenderer pdfRenderer = new LimitedPDFRenderer(document);
pdfRenderer.setSubsamplingAllowed(true);
if (!includeAnnotations) {
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertOfficeController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertOfficeController.java
index 8d5ce09fd5..5d37957fca 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertOfficeController.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertOfficeController.java
@@ -2,11 +2,13 @@ package stirling.software.SPDF.controller.api.converters;
import java.io.File;
import java.io.IOException;
+import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.List;
import java.util.Locale;
@@ -118,8 +120,19 @@ public class ConvertOfficeController {
Path inputPath = workDir.resolve(baseName + "." + extensionLower);
Path outputPath = workDir.resolve(baseName + ".pdf");
- if (officeToPdfService.handles(extensionLower, useStirlingOfficeConvert)) {
- if (convertInProcess(inputFile, extensionLower, inputPath, outputPath)) {
+ // OLE2 compound binaries are never ZIP archives, so the OOXML/ODF sanitizer cannot read
+ // them; their preprocessing copies the bytes as-is whatever the filename extension says.
+ boolean legacyBinary = isLegacyBinaryOffice(inputFile);
+
+ boolean inProcess = officeToPdfService.handles(extensionLower, useStirlingOfficeConvert);
+ if (inProcess && legacyBinary && officeConversionService.libreOfficeAvailable()) {
+ // Legacy binary Office documents (OLE2) are converted by LibreOffice rather than the
+ // in-process converter, chosen by content signature so the engine follows what the
+ // file is rather than its extension.
+ inProcess = false;
+ }
+ if (inProcess) {
+ if (convertInProcess(inputFile, extensionLower, legacyBinary, inputPath, outputPath)) {
return outputPath.toFile();
}
} else if (!officeConversionService.libreOfficeAvailable()) {
@@ -131,12 +144,15 @@ public class ConvertOfficeController {
String htmlContent = new String(inputFile.getBytes(), StandardCharsets.UTF_8);
String sanitizedHtml = customHtmlSanitizer.sanitize(htmlContent);
Files.writeString(inputPath, sanitizedHtml, StandardCharsets.UTF_8);
- } else if (officeDocumentSanitizer.isSanitizableExtension(extensionLower)) {
+ } else if (!legacyBinary
+ && officeDocumentSanitizer.isSanitizableExtension(extensionLower)) {
byte[] sanitized =
officeDocumentSanitizer.sanitize(inputFile.getBytes(), extensionLower);
Files.write(inputPath, sanitized);
} else {
- Files.copy(inputFile.getInputStream(), inputPath, StandardCopyOption.REPLACE_EXISTING);
+ try (InputStream in = inputFile.getInputStream()) {
+ Files.copy(in, inputPath, StandardCopyOption.REPLACE_EXISTING);
+ }
}
Path libreOfficeProfile = null;
@@ -241,14 +257,21 @@ public class ConvertOfficeController {
/** False when LibreOffice should retry the file; the original upload is converted as is. */
private boolean convertInProcess(
- MultipartFile inputFile, String extension, Path inputPath, Path outputPath)
+ MultipartFile inputFile,
+ String extension,
+ boolean legacyBinary,
+ Path inputPath,
+ Path outputPath)
throws IOException {
// Same sanitizing and ZIP budget as the LibreOffice path; a refused file never falls back.
- if (officeDocumentSanitizer.isSanitizableExtension(extension)) {
+ // OLE2 binaries are copied as-is: the ZIP sanitizer cannot read a compound file.
+ if (!legacyBinary && officeDocumentSanitizer.isSanitizableExtension(extension)) {
Files.write(
inputPath, officeDocumentSanitizer.sanitize(inputFile.getBytes(), extension));
} else {
- Files.copy(inputFile.getInputStream(), inputPath, StandardCopyOption.REPLACE_EXISTING);
+ try (InputStream in = inputFile.getInputStream()) {
+ Files.copy(in, inputPath, StandardCopyOption.REPLACE_EXISTING);
+ }
}
try {
officeToPdfService.convert(inputPath, outputPath);
@@ -275,6 +298,18 @@ public class ConvertOfficeController {
.matches();
}
+ // OLE2 compound-file signature: the start of every legacy binary Office document (.doc, .xls,
+ // .ppt and their variants).
+ private static final byte[] OLE2_SIGNATURE = {
+ (byte) 0xD0, (byte) 0xCF, 0x11, (byte) 0xE0, (byte) 0xA1, (byte) 0xB1, 0x1A, (byte) 0xE1
+ };
+
+ private static boolean isLegacyBinaryOffice(MultipartFile file) throws IOException {
+ try (InputStream in = file.getInputStream()) {
+ return Arrays.equals(in.readNBytes(OLE2_SIGNATURE.length), OLE2_SIGNATURE);
+ }
+ }
+
@AutoJobPostMapping(
consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
value = "/file/pdf",
diff --git a/app/core/src/main/java/stirling/software/SPDF/service/OfficeConversionService.java b/app/core/src/main/java/stirling/software/SPDF/service/OfficeConversionService.java
index 9cb9898caa..90caf773de 100644
--- a/app/core/src/main/java/stirling/software/SPDF/service/OfficeConversionService.java
+++ b/app/core/src/main/java/stirling/software/SPDF/service/OfficeConversionService.java
@@ -9,6 +9,10 @@ import java.nio.file.Path;
import java.time.Duration;
import java.util.Enumeration;
import java.util.Map;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.FutureTask;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
@@ -19,13 +23,14 @@ import lombok.RequiredArgsConstructor;
import stirling.software.SPDF.config.EndpointConfiguration;
import stirling.software.common.model.ApplicationProperties;
+import stirling.software.common.util.ExceptionUtils;
import stirling.software.officeconvert.OfficeConvert;
import stirling.software.officeconvert.PdfToPptx;
import stirling.software.officeconvert.legacy.PdfToPpt;
/**
* PDF to Office in process through Stirling Office Convert, and the switch between it and the
- * legacy converters. Conversions are stopped at the LibreOffice timeout.
+ * legacy converters. Conversions use the configured LibreOffice timeout.
*/
@Service
@RequiredArgsConstructor
@@ -96,14 +101,92 @@ public class OfficeConversionService {
}
try (OutputStream out = Files.newOutputStream(target)) {
if ("ppt".equals(format)) {
- // Binary PowerPoint comes from the legacy module, outside OfficeConvert's timeout.
- PdfToPpt.convert(document, out, slides(settings));
+ convertToPpt(document, out, settings);
} else {
OfficeConvert.convert(document, out, FORMATS.get(format), settings);
}
}
}
+ /** A .ppt holds one slide per page; the legacy writer creates them up front. */
+ static final int MAX_PPT_SLIDES = 5000;
+
+ /**
+ * Binary PowerPoint comes from the legacy module, which the shared {@link OfficeConvert} path
+ * does not cover, so the page count is bounded and the work runs under {@code
+ * settings.timeout()} like every other format.
+ */
+ private void convertToPpt(
+ PDDocument document, OutputStream out, OfficeConvert.Settings settings)
+ throws IOException {
+ int total = document.getNumberOfPages();
+ int first = settings.firstPage() > 0 ? settings.firstPage() : 1;
+ int last = settings.lastPage() > 0 ? Math.min(settings.lastPage(), total) : total;
+ if (last - first + 1 >= MAX_PPT_SLIDES) {
+ throw ExceptionUtils.createIllegalArgumentException(
+ "error.pptTooManyPages",
+ "A .ppt holds at most {0} pages; convert to .pptx instead.",
+ MAX_PPT_SLIDES);
+ }
+ FutureTask<Void> task =
+ new FutureTask<>(
+ () -> {
+ PdfToPpt.convert(document, out, slides(settings));
+ return null;
+ });
+ Thread worker = Thread.ofPlatform().name("office-convert-ppt").daemon().unstarted(task);
+ worker.start();
+ awaitPptConversion(task, worker, settings.timeout());
+ }
+
+ static void awaitPptConversion(FutureTask<Void> task, Thread worker, Duration timeout)
+ throws IOException {
+ try {
+ task.get(timeout.toNanos(), TimeUnit.NANOSECONDS);
+ } catch (TimeoutException e) {
+ task.cancel(true);
+ awaitWorkerTermination(worker);
+ throw new IOException(
+ "The conversion took longer than "
+ + timeout.toMillis()
+ + " ms and was stopped");
+ } catch (InterruptedException e) {
+ task.cancel(true);
+ awaitWorkerTermination(worker);
+ Thread.currentThread().interrupt();
+ throw new IOException("Conversion interrupted", e);
+ } catch (ExecutionException e) {
+ task.cancel(true);
+ Throwable cause = e.getCause();
+ if (cause instanceof IOException io) {
+ throw io;
+ }
+ if (cause instanceof RuntimeException re) {
+ throw re;
+ }
+ throw new IOException("PDF to .ppt conversion failed", cause);
+ }
+ }
+
+ /**
+ * Waits for the cancelled worker to stop touching {@code out} and the document before the
+ * caller closes them. The legacy writer's final POI write may ignore interruption, so even a
+ * further interruption must not release resources that the worker still owns.
+ */
+ private static void awaitWorkerTermination(Thread worker) {
+ boolean interrupted = false;
+ while (worker.isAlive()) {
+ try {
+ worker.join();
+ } catch (InterruptedException e) {
+ interrupted = true;
+ }
+ }
+ if (interrupted) {
+ Thread.currentThread().interrupt();
+ }
+ }
+
/**
* Whether a workbook holds any cell. With no table found, a sheet-per-table workbook is a
* single empty sheet.
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertOfficeControllerTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertOfficeControllerTest.java
index ec713ccfc7..cee5654550 100644
--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertOfficeControllerTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertOfficeControllerTest.java
@@ -640,4 +640,140 @@ class ConvertOfficeControllerTest {
org.apache.commons.io.FileUtils.deleteDirectory(producedPdf.getParentFile());
}
}
+
+ @Nested
+ @DisplayName("Legacy binary Office routing")
+ class LegacyBinary {
+
+ private static final byte[] OLE2 = {
+ (byte) 0xD0,
+ (byte) 0xCF,
+ 0x11,
+ (byte) 0xE0,
+ (byte) 0xA1,
+ (byte) 0xB1,
+ 0x1A,
+ (byte) 0xE1,
+ 0,
+ 0,
+ 0,
+ 0
+ };
+ private static final byte[] OOXML = {'P', 'K', 0x03, 0x04, 0, 0, 0, 0};
+
+ private MockMultipartFile docFile(byte[] content) {
+ return new MockMultipartFile("fileInput", "report.doc", "application/msword", content);
+ }
+
+ private File runLibreOffice(MockedStatic<ProcessExecutor> pe, MockMultipartFile file)
+ throws Exception {
+ ProcessExecutorResult result = mockExecutor(pe, 0);
+ ProcessExecutor executor = ProcessExecutor.getInstance(Processes.LIBRE_OFFICE);
+ when(executor.runCommandWithOutputHandling(any()))
+ .thenAnswer(
+ inv -> {
+ List<String> command = inv.getArgument(0);
+ Path out = Path.of(command.getLast()).resolveSibling("report.pdf");
+ Files.writeString(out, "%PDF soffice");
+ return result;
+ });
+ return controller.convertToPdf(file, true);
+ }
+
+ @Test
+ @DisplayName("an OLE2 .doc goes to LibreOffice even when in-process is selected")
+ void ole2GoesToLibreOffice() throws Exception {
+ when(officeToPdfService.handles("doc", true)).thenReturn(true);
+ when(officeConversionService.libreOfficeAvailable()).thenReturn(true);
+
+ try (MockedStatic<ProcessExecutor> pe = Mockito.mockStatic(ProcessExecutor.class)) {
+ File pdf = runLibreOffice(pe, docFile(OLE2));
+
+ assertThat(Files.readString(pdf.toPath())).isEqualTo("%PDF soffice");
+ Mockito.verify(officeToPdfService, Mockito.never())
+ .convert(any(Path.class), any(Path.class));
+ deleteWorkdir(pdf);
+ }
+ }
+
+ @Test
+ @DisplayName("a renamed OLE2 file is routed by signature and skips the ZIP sanitizer")
+ void ole2RoutedBySignature() throws Exception {
+ when(officeToPdfService.handles("xlsx", true)).thenReturn(true);
+ when(officeConversionService.libreOfficeAvailable()).thenReturn(true);
+ // The .xlsx name would otherwise select the ZIP sanitizer, which cannot read OLE2.
+ when(officeDocumentSanitizer.isSanitizableExtension("xlsx")).thenReturn(true);
+ MockMultipartFile renamed =
+ new MockMultipartFile("fileInput", "book.xlsx", "application/msword", OLE2);
+
+ try (MockedStatic<ProcessExecutor> pe = Mockito.mockStatic(ProcessExecutor.class)) {
+ ProcessExecutorResult result = mockExecutor(pe, 0);
+ ProcessExecutor executor = ProcessExecutor.getInstance(Processes.LIBRE_OFFICE);
+ when(executor.runCommandWithOutputHandling(any()))
+ .thenAnswer(
+ inv -> {
+ Path out =
+ Path.of(((List<String>) inv.getArgument(0)).getLast())
+ .resolveSibling("book.pdf");
+ assertThat(Files.readAllBytes(out.resolveSibling("book.xlsx")))
+ .isEqualTo(OLE2);
+ Files.writeString(out, "%PDF soffice");
+ return result;
+ });
+
+ File pdf = controller.convertToPdf(renamed, true);
+
+ assertThat(Files.readString(pdf.toPath())).isEqualTo("%PDF soffice");
+ Mockito.verify(officeToPdfService, Mockito.never())
+ .convert(any(Path.class), any(Path.class));
+ Mockito.verify(officeDocumentSanitizer, Mockito.never())
+ .sanitize(any(byte[].class), anyString());
+ deleteWorkdir(pdf);
+ }
+ }
+
+ @Test
+ @DisplayName("an OOXML upload still converts in process")
+ void ooxmlStaysInProcess() throws Exception {
+ when(officeToPdfService.handles("doc", true)).thenReturn(true);
+ when(officeConversionService.libreOfficeAvailable()).thenReturn(true);
+ Mockito.doAnswer(
+ inv -> {
+ Files.writeString(inv.getArgument(1), "%PDF in process");
+ return null;
+ })
+ .when(officeToPdfService)
+ .convert(any(Path.class), any(Path.class));
+
+ try (MockedStatic<ProcessExecutor> pe = Mockito.mockStatic(ProcessExecutor.class)) {
+ File pdf = controller.convertToPdf(docFile(OOXML), true);
+
+ assertThat(Files.readString(pdf.toPath())).isEqualTo("%PDF in process");
+ pe.verifyNoInteractions();
+ deleteWorkdir(pdf);
+ }
+ }
+
+ @Test
+ @DisplayName("without LibreOffice an OLE2 file still uses the in-process converter")
+ void ole2UsesInProcessWithoutLibreOffice() throws Exception {
+ when(officeToPdfService.handles("doc", true)).thenReturn(true);
+ when(officeConversionService.libreOfficeAvailable()).thenReturn(false);
+ Mockito.doAnswer(
+ inv -> {
+ Files.writeString(inv.getArgument(1), "%PDF in process");
+ return null;
+ })
+ .when(officeToPdfService)
+ .convert(any(Path.class), any(Path.class));
+
+ try (MockedStatic<ProcessExecutor> pe = Mockito.mockStatic(ProcessExecutor.class)) {
+ File pdf = controller.convertToPdf(docFile(OLE2), true);
+
+ assertThat(Files.readString(pdf.toPath())).isEqualTo("%PDF in process");
+ pe.verifyNoInteractions();
+ deleteWorkdir(pdf);
+ }
+ }
+ }
}
diff --git a/app/core/src/test/java/stirling/software/SPDF/service/OfficeConversionCancellationTest.java b/app/core/src/test/java/stirling/software/SPDF/service/OfficeConversionCancellationTest.java
new file mode 100644
index 0000000000..607189ff9a
--- /dev/null
+++ b/app/core/src/test/java/stirling/software/SPDF/service/OfficeConversionCancellationTest.java
@@ -0,0 +1,96 @@
+package stirling.software.SPDF.service;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.io.IOException;
+import java.time.Duration;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.FutureTask;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
+
+@Timeout(15)
+class OfficeConversionCancellationTest {
+
+ @Test
+ void timeoutKeepsResourcesOwnedUntilAnUninterruptibleWorkerFinishes() throws Exception {
+ exerciseCancellation(false, Duration.ofMillis(20), 5200);
+ }
+
+ @Test
+ void repeatedInterruptionCannotReleaseResourcesWhileTheWorkerIsRunning() throws Exception {
+ exerciseCancellation(true, Duration.ofSeconds(30), 150);
+ }
+
+ private void exerciseCancellation(boolean interrupt, Duration timeout, long waitMillis)
+ throws Exception {
+ CountDownLatch started = new CountDownLatch(1);
+ CountDownLatch cancelled = new CountDownLatch(1);
+ CountDownLatch finish = new CountDownLatch(1);
+ CountDownLatch returned = new CountDownLatch(1);
+ AtomicBoolean workerFinished = new AtomicBoolean();
+ AtomicBoolean releasedEarly = new AtomicBoolean();
+ AtomicBoolean interruptRestored = new AtomicBoolean();
+ AtomicReference<Throwable> failure = new AtomicReference<>();
+ FutureTask<Void> task =
+ new FutureTask<>(
+ () -> {
+ started.countDown();
+ try {
+ boolean done = false;
+ while (!done) {
+ try {
+ done = finish.await(1, TimeUnit.SECONDS);
+ } catch (InterruptedException ignored) {
+ cancelled.countDown();
+ }
+ }
+ return null;
+ } finally {
+ workerFinished.set(true);
+ }
+ });
+ Thread worker = Thread.ofPlatform().daemon().unstarted(task);
+ Thread caller =
+ Thread.ofPlatform()
+ .daemon()
+ .unstarted(
+ () -> {
+ try {
+ OfficeConversionService.awaitPptConversion(
+ task, worker, timeout);
+ } catch (Throwable exception) {
+ failure.set(exception);
+ } finally {
+ releasedEarly.set(!workerFinished.get());
+ interruptRestored.set(
+ Thread.currentThread().isInterrupted());
+ returned.countDown();
+ }
+ });
+ worker.start();
+ try {
+ assertThat(started.await(2, TimeUnit.SECONDS)).isTrue();
+ caller.start();
+ if (interrupt) caller.interrupt();
+ assertThat(cancelled.await(2, TimeUnit.SECONDS)).isTrue();
+ if (interrupt) caller.interrupt();
+ assertThat(returned.await(waitMillis, TimeUnit.MILLISECONDS)).isFalse();
+ } finally {
+ finish.countDown();
+ worker.join(2000);
+ caller.join(2000);
+ }
+ assertThat(worker.isAlive()).isFalse();
+ assertThat(caller.isAlive()).isFalse();
+ assertThat(releasedEarly).isFalse();
+ assertThat(failure.get())
+ .isInstanceOf(IOException.class)
+ .hasMessageContaining(interrupt ? "interrupted" : "took longer");
+ if (interrupt) assertThat(interruptRestored).isTrue();
+ }
+}
diff --git a/app/core/src/test/java/stirling/software/SPDF/service/OfficeConversionServiceTest.java b/app/core/src/test/java/stirling/software/SPDF/service/OfficeConversionServiceTest.java
index c084ae1314..fbcac8d181 100644
--- a/app/core/src/test/java/stirling/software/SPDF/service/OfficeConversionServiceTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/service/OfficeConversionServiceTest.java
@@ -1,6 +1,7 @@
package stirling.software.SPDF.service;
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.when;
@@ -16,6 +17,8 @@ import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.pdmodel.font.Standard14Fonts;
+import org.apache.poi.hslf.usermodel.HSLFSlideShow;
+import org.apache.poi.hslf.usermodel.HSLFTextParagraph;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -74,6 +77,24 @@ class OfficeConversionServiceTest {
}
}
+ @Test
+ void convertsPdfToLegacyPowerPoint() throws Exception {
+ Path ppt = dir.resolve("out.ppt");
+ try (PDDocument pdf = textPdf("Hello from Stirling")) {
+ service.convert(pdf, ppt, "ppt", service.settings());
+ }
+
+ try (var in = Files.newInputStream(ppt);
+ HSLFSlideShow slides = new HSLFSlideShow(in)) {
+ assertThat(slides.getSlides()).hasSize(1);
+ assertThat(slides.getSlides().getFirst().getTextParagraphs())
+ .anySatisfy(
+ paragraphs ->
+ assertThat(HSLFTextParagraph.getText(paragraphs))
+ .contains("Hello from Stirling"));
+ }
+ }
+
@Test
void convertsWordToPdf() throws Exception {
Path docx = dir.resolve("in.docx");
@@ -117,6 +138,18 @@ class OfficeConversionServiceTest {
assertThat(toPdf.canFallBack(new IOException("bad file"))).isFalse();
}
+ @Test
+ void refusesPptBeyondThePageCap() throws Exception {
+ Path target = dir.resolve("out.ppt");
+ try (PDDocument pdf = new PDDocument()) {
+ for (int i = 0; i < OfficeConversionService.MAX_PPT_SLIDES; i++) {
+ pdf.addPage(new PDPage());
+ }
+ assertThatThrownBy(() -> service.convert(pdf, target, "ppt", service.settings()))
+ .isInstanceOf(IllegalArgumentException.class);
+ }
+ }
+
private static PDDocument textPdf(String text) throws Exception {
PDDocument pdf = new PDDocument();
PDPage page = new PDPage();
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/security/filter/UserAuthenticationFilterTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/security/filter/UserAuthenticationFilterTest.java
index 71486947f5..30c71e44f6 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/security/filter/UserAuthenticationFilterTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/security/filter/UserAuthenticationFilterTest.java
@@ -232,8 +232,8 @@ class UserAuthenticationFilterTest {
request.setRequestURI("/api/v1/auth/me");
User user = enabledUser("blocked");
setAuthentication(user, "blocked");
- when(userService.usernameExistsIgnoreCase("blocked")).thenReturn(true);
- when(userService.isUserDisabled("blocked")).thenReturn(true);
+ user.setEnabled(false);
+ when(userService.findByUsernameIgnoreCase("blocked")).thenReturn(Optional.of(user));
when(sessionPersistentRegistry.getAllSessions(any(), anyBoolean()))
.thenReturn(List.of());
@@ -250,8 +250,7 @@ class UserAuthenticationFilterTest {
request.setRequestURI("/api/v1/auth/me");
User user = enabledUser("ghost");
setAuthentication(user, "ghost");
- when(userService.usernameExistsIgnoreCase("ghost")).thenReturn(false);
- when(userService.isUserDisabled("ghost")).thenReturn(false);
+ when(userService.findByUsernameIgnoreCase("ghost")).thenReturn(Optional.empty());
when(sessionPersistentRegistry.getAllSessions(any(), anyBoolean()))
.thenReturn(List.of());