Skip to content

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

Add limits to max decode size (#8691)

James Bruntone16a5f92c715
diff --git a/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java b/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java
index e3d13bd91a..ea71baa940 100644
--- a/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java
+++ b/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java
@@ -1338,6 +1338,7 @@ public class ApplicationProperties {
private boolean stirlingOfficeConversion;
private int maxDPI = 500;
private int maxPdfaConversionPages = 20_000;
+ private int maxImageMegapixels;
private boolean enableUrlToPDF;
private Html html = new Html();
private CustomPaths customPaths = new CustomPaths();
diff --git a/app/common/src/main/java/stirling/software/common/util/DecodedStreamLimit.java b/app/common/src/main/java/stirling/software/common/util/DecodedStreamLimit.java
new file mode 100644
index 0000000000..8d6a7a6976
--- /dev/null
+++ b/app/common/src/main/java/stirling/software/common/util/DecodedStreamLimit.java
@@ -0,0 +1,157 @@
+package stirling.software.common.util;
+
+import java.io.FilterOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.lang.reflect.Field;
+import java.util.IdentityHashMap;
+import java.util.Map;
+import java.util.function.LongSupplier;
+
+import org.apache.pdfbox.cos.COSDictionary;
+import org.apache.pdfbox.cos.COSName;
+import org.apache.pdfbox.filter.DecodeOptions;
+import org.apache.pdfbox.filter.DecodeResult;
+import org.apache.pdfbox.filter.Filter;
+import org.apache.pdfbox.filter.FilterFactory;
+import org.springframework.stereotype.Component;
+
+import jakarta.annotation.PostConstruct;
+
+import lombok.extern.slf4j.Slf4j;
+
+/**
+ * Caps how far one PDF stream may decompress. PDFBox decodes every filter stage of a stream
+ * completely into the heap with no bound, so a few kilobytes of Flate can expand past the heap, and
+ * the server runs with ExitOnOutOfMemoryError.
+ *
+ * <p>PDFBox has no hook for this, so {@link #install()} wraps the filters in {@link
+ * FilterFactory#INSTANCE} by reflection; every decode, from xref streams at load to images and
+ * content at render, goes through them. The cap is the largest raster {@link ImageMemoryLimit}
+ * allows, in bytes, so any image within that limit still decodes. It bounds each stream, not a
+ * request: a page drawing one stream many times decodes it many times.
+ */
+@Slf4j
+@Component
+public class DecodedStreamLimit {
+
+ @PostConstruct
+ public void installAtStartup() {
+ install();
+ }
+
+ /** Idempotent. Fails loudly in tests, not at runtime, if PDFBox's internals move. */
+ public static synchronized void install() {
+ Map<COSName, Filter> filters;
+ try {
+ filters = filterRegistry();
+ } catch (ReflectiveOperationException | RuntimeException e) {
+ log.error("Could not cap decoded PDF stream sizes; PDFBox's FilterFactory changed", e);
+ return;
+ }
+ Map<Filter, Filter> bounded = new IdentityHashMap<>();
+ // Values only: the map keeps its structure, so a concurrent lookup sees the old filter or
+ // the new one, never a broken table.
+ filters.replaceAll(
+ (name, filter) ->
+ filter instanceof BoundedFilter
+ ? filter
+ : bounded.computeIfAbsent(
+ filter,
+ original ->
+ new BoundedFilter(
+ original, DecodedStreamLimit::maxBytes)));
+ }
+
+ public static long maxBytes() {
+ return ImageMemoryLimit.maxPixels() * ImageMemoryLimit.BYTES_PER_PIXEL;
+ }
+
+ @SuppressWarnings("unchecked")
+ static Map<COSName, Filter> filterRegistry() throws ReflectiveOperationException {
+ Field field = FilterFactory.class.getDeclaredField("filters");
+ field.setAccessible(true);
+ return (Map<COSName, Filter>) field.get(FilterFactory.INSTANCE);
+ }
+
+ /**
+ * Delegates to a PDFBox filter, refusing output past the cap. One instance stands for each
+ * original, as the original is shared between a name and its abbreviation, so PDFBox's removal
+ * of duplicated filters still recognises them.
+ */
+ static final class BoundedFilter extends Filter {
+
+ private final Filter delegate;
+ private final LongSupplier maxBytes;
+
+ BoundedFilter(Filter delegate, LongSupplier maxBytes) {
+ this.delegate = delegate;
+ this.maxBytes = maxBytes;
+ }
+
+ Filter delegate() {
+ return delegate;
+ }
+
+ @Override
+ public DecodeResult decode(
+ InputStream encoded, OutputStream decoded, COSDictionary parameters, int index)
+ throws IOException {
+ return delegate.decode(encoded, bounded(decoded), parameters, index);
+ }
+
+ @Override
+ public DecodeResult decode(
+ InputStream encoded,
+ OutputStream decoded,
+ COSDictionary parameters,
+ int index,
+ DecodeOptions options)
+ throws IOException {
+ return delegate.decode(encoded, bounded(decoded), parameters, index, options);
+ }
+
+ @Override
+ protected void encode(InputStream input, OutputStream encoded, COSDictionary parameters)
+ throws IOException {
+ // The public encode ignores its index and hands the delegate these same parameters.
+ delegate.encode(input, encoded, parameters, 0);
+ }
+
+ private OutputStream bounded(OutputStream decoded) {
+ return new BoundedOutputStream(decoded, maxBytes.getAsLong());
+ }
+ }
+
+ private static final class BoundedOutputStream extends FilterOutputStream {
+
+ private final long maxBytes;
+ private long written;
+
+ BoundedOutputStream(OutputStream out, long maxBytes) {
+ super(out);
+ this.maxBytes = maxBytes;
+ }
+
+ @Override
+ public void write(int b) throws IOException {
+ count(1);
+ out.write(b);
+ }
+
+ @Override
+ public void write(byte[] b, int off, int len) throws IOException {
+ count(len);
+ out.write(b, off, len);
+ }
+
+ private void count(int bytes) {
+ written += bytes;
+ if (written > maxBytes) {
+ throw ExceptionUtils.createDecodedStreamTooLargeException(
+ Math.ceilDiv(maxBytes, 1024L * 1024));
+ }
+ }
+ }
+}
diff --git a/app/common/src/main/java/stirling/software/common/util/ExceptionUtils.java b/app/common/src/main/java/stirling/software/common/util/ExceptionUtils.java
index f4e401d3b9..fd29bb651c 100644
--- a/app/common/src/main/java/stirling/software/common/util/ExceptionUtils.java
+++ b/app/common/src/main/java/stirling/software/common/util/ExceptionUtils.java
@@ -11,9 +11,6 @@ import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-import org.apache.pdfbox.pdmodel.PDPage;
-import org.apache.pdfbox.pdmodel.common.PDRectangle;
-
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
@@ -202,103 +199,6 @@ public class ExceptionUtils {
return obj;
}
- /**
- * Validates that rendering a PDF page at the given DPI will not exceed safe memory limits. This
- * should be called BEFORE attempting to render to prevent OOM/NegativeArraySizeException.
- *
- * <p>The validation checks if the resulting image dimensions would exceed:
- *
- * <ul>
- * <li>Java's maximum array size (Integer.MAX_VALUE)
- * <li>Practical memory limits (considering bytes per pixel)
- * </ul>
- *
- * <p><strong>Usage Example:</strong>
- *
- * <pre>{@code
- * PDPage page = document.getPage(pageIndex);
- * ExceptionUtils.validateRenderingDimensions(page, pageIndex + 1, dpi);
- * // Only render if validation passes
- * BufferedImage image = renderer.renderImageWithDPI(pageIndex, dpi);
- * }</pre>
- *
- * @param page the PDF page to validate
- * @param pageNumber the page number (1-based, for error messages)
- * @param dpi the DPI value to use for rendering
- * @throws OutOfMemoryDpiException if the dimensions would be too large
- */
- public static void validateRenderingDimensions(PDPage page, int pageNumber, int dpi)
- throws OutOfMemoryDpiException {
- if (page == null) {
- return; // Nothing to validate
- }
-
- PDRectangle mediaBox = page.getMediaBox();
- if (mediaBox == null) {
- return; // Cannot validate without dimensions
- }
-
- // Get page dimensions in points (1 point = 1/72 inch)
- float widthInPoints = mediaBox.getWidth();
- float heightInPoints = mediaBox.getHeight();
-
- // Convert to pixels at the given DPI
- // Formula: pixels = (points / 72) * dpi
- long widthInPixels = Math.round((widthInPoints / 72.0) * dpi);
- long heightInPixels = Math.round((heightInPoints / 72.0) * dpi);
-
- // Check if dimensions exceed Integer.MAX_VALUE
- if (widthInPixels > Integer.MAX_VALUE || heightInPixels > Integer.MAX_VALUE) {
- log.warn(
- "Page {} dimensions too large: {}x{} pixels at {} DPI",
- pageNumber,
- widthInPixels,
- heightInPixels,
- dpi);
- throw createOutOfMemoryDpiException(
- pageNumber,
- dpi,
- new IllegalArgumentException(
- "Dimension exceeds Integer.MAX_VALUE: "
- + widthInPixels
- + "x"
- + heightInPixels));
- }
-
- // Check if total pixel count would exceed safe limits
- // RGB images use 4 bytes per pixel (ARGB), but be conservative
- long totalPixels = widthInPixels * heightInPixels;
- long estimatedBytes = totalPixels * 4; // 4 bytes per pixel for ARGB
-
- // Java array max size is Integer.MAX_VALUE elements
- // For byte array: Integer.MAX_VALUE bytes
- // For int array (image pixels): Integer.MAX_VALUE ints = Integer.MAX_VALUE * 4 bytes
- if (totalPixels > Integer.MAX_VALUE) {
- log.warn(
- "Page {} pixel count too large: {} pixels ({} MB) at {} DPI",
- pageNumber,
- totalPixels,
- estimatedBytes / (1024 * 1024),
- dpi);
- throw createOutOfMemoryDpiException(
- pageNumber,
- dpi,
- new IllegalArgumentException(
- "Total pixel count exceeds safe limit: " + totalPixels));
- }
-
- // Additional safety check: warn about very large images (> 1GB estimated)
- if (estimatedBytes > 1024L * 1024 * 1024) {
- log.warn(
- "Page {} will create a very large image: {}x{} pixels (~{} MB) at {} DPI. This may cause memory issues.",
- pageNumber,
- widthInPixels,
- heightInPixels,
- estimatedBytes / (1024 * 1024),
- dpi);
- }
- }
-
/**
* Execute a PDF rendering operation with automatic OutOfMemory exception handling. This wraps
* any rendering operation and automatically converts OutOfMemoryError or
@@ -1062,6 +962,42 @@ public class ExceptionUtils {
return new IllegalArgumentException(message);
}
+ public static OutOfMemoryDpiException createPageImageTooLargeException(
+ int pageNumber, int dpi, long megapixels, long limitMegapixels) {
+ return new OutOfMemoryDpiException(
+ getMessage(
+ ErrorCode.PAGE_IMAGE_TOO_LARGE,
+ pageNumber,
+ dpi,
+ megapixels,
+ limitMegapixels),
+ null,
+ ErrorCode.PAGE_IMAGE_TOO_LARGE.getCode());
+ }
+
+ public static OutOfMemoryDpiException createCombinedImageTooLargeException(
+ long megapixels, long limitMegapixels) {
+ return new OutOfMemoryDpiException(
+ getMessage(ErrorCode.COMBINED_IMAGE_TOO_LARGE, megapixels, limitMegapixels),
+ null,
+ ErrorCode.COMBINED_IMAGE_TOO_LARGE.getCode());
+ }
+
+ public static DecodedStreamTooLargeException createDecodedStreamTooLargeException(
+ long limitMegabytes) {
+ return new DecodedStreamTooLargeException(
+ getMessage(ErrorCode.DECODED_STREAM_TOO_LARGE, limitMegabytes),
+ ErrorCode.DECODED_STREAM_TOO_LARGE.getCode());
+ }
+
+ public static OutOfMemoryDpiException createEmbeddedImageTooLargeException(
+ long megapixels, long limitMegapixels) {
+ return new OutOfMemoryDpiException(
+ getMessage(ErrorCode.EMBEDDED_IMAGE_TOO_LARGE, megapixels, limitMegapixels),
+ null,
+ ErrorCode.EMBEDDED_IMAGE_TOO_LARGE.getCode());
+ }
+
/**
* Create an OutOfMemoryDpiException for memory/image size errors when rendering PDF images with
* DPI. Handles OutOfMemoryError and related conditions (e.g., NegativeArraySizeException) that
@@ -1374,7 +1310,23 @@ public class ExceptionUtils {
OUT_OF_MEMORY_DPI(
"E081",
"error.outOfMemoryDpi",
- "Out of memory or image-too-large error while rendering PDF page {0} at {1} DPI. This can occur when the resulting image exceeds Java's array/memory limits (e.g., NegativeArraySizeException). Please use a lower DPI value (recommended: 150 or less) or process the document in smaller chunks.");
+ "Out of memory or image-too-large error while rendering PDF page {0} at {1} DPI. This can occur when the resulting image exceeds Java's array/memory limits (e.g., NegativeArraySizeException). Please use a lower DPI value (recommended: 150 or less) or process the document in smaller chunks."),
+ PAGE_IMAGE_TOO_LARGE(
+ "E084",
+ "error.pageImageTooLarge",
+ "Page {0} at {1} DPI needs a {2}-megapixel image, more than this server''s limit of {3} megapixels. Use a lower DPI."),
+ COMBINED_IMAGE_TOO_LARGE(
+ "E085",
+ "error.combinedImageTooLarge",
+ "Joining the pages into one image needs {0} megapixels, more than this server''s limit of {1} megapixels. Use a lower DPI or one image per page."),
+ EMBEDDED_IMAGE_TOO_LARGE(
+ "E086",
+ "error.embeddedImageTooLarge",
+ "An image in this document needs {0} megapixels, more than this server''s limit of {1} megapixels."),
+ DECODED_STREAM_TOO_LARGE(
+ "E087",
+ "error.decodedStreamTooLarge",
+ "Part of this document decompresses to more than this server''s limit of {0} MB.");
private final String code;
private final String messageKey;
@@ -1657,6 +1609,22 @@ public class ExceptionUtils {
}
}
+ /**
+ * A PDF stream decoded past {@code DecodedStreamLimit}. Unchecked on purpose: PDFBox catches an
+ * IOException from a content stream and draws the page blank, which would answer a refused
+ * decode with a successful, empty result.
+ */
+ public static class DecodedStreamTooLargeException extends RuntimeException
+ implements ErrorCodeProvider {
+ @Getter(onMethod_ = {@Override})
+ private final String errorCode;
+
+ public DecodedStreamTooLargeException(String message, String errorCode) {
+ super(message);
+ this.errorCode = errorCode;
+ }
+ }
+
/** Exception thrown when rendering PDF pages causes out-of-memory or array size errors. */
public static class OutOfMemoryDpiException extends BaseAppException {
public OutOfMemoryDpiException(String message, Throwable cause, String errorCode) {
diff --git a/app/common/src/main/java/stirling/software/common/util/FormUtils.java b/app/common/src/main/java/stirling/software/common/util/FormUtils.java
index 9585489af1..8ca5a77d93 100644
--- a/app/common/src/main/java/stirling/software/common/util/FormUtils.java
+++ b/app/common/src/main/java/stirling/software/common/util/FormUtils.java
@@ -749,7 +749,7 @@ public class FormUtils {
}
}
- PDFRenderer renderer = new PDFRenderer(document);
+ PDFRenderer renderer = new LimitedPDFRenderer(document);
renderer.setSubsamplingAllowed(true); // Enable subsampling to reduce memory usage
ApplicationProperties properties =
ApplicationContextProvider.getBean(ApplicationProperties.class);
diff --git a/app/common/src/main/java/stirling/software/common/util/ImageMemoryLimit.java b/app/common/src/main/java/stirling/software/common/util/ImageMemoryLimit.java
new file mode 100644
index 0000000000..df27ab2f59
--- /dev/null
+++ b/app/common/src/main/java/stirling/software/common/util/ImageMemoryLimit.java
@@ -0,0 +1,173 @@
+package stirling.software.common.util;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import javax.imageio.ImageIO;
+import javax.imageio.ImageReader;
+import javax.imageio.stream.ImageInputStream;
+
+import org.apache.pdfbox.cos.COSDictionary;
+import org.apache.pdfbox.cos.COSName;
+import org.apache.pdfbox.pdmodel.PDPage;
+import org.apache.pdfbox.pdmodel.common.PDRectangle;
+import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
+
+import stirling.software.common.model.ApplicationProperties;
+import stirling.software.common.util.ExceptionUtils.OutOfMemoryDpiException;
+
+/**
+ * The largest raster one render or image decode may allocate. The server runs with
+ * ExitOnOutOfMemoryError, so a raster that does not fit the heap ends the whole process rather than
+ * the request: sizes are checked against this limit before anything is allocated.
+ *
+ * <p>The limit is {@code system.maxImageMegapixels}, or when that is 0, enough pixels to fill a
+ * quarter of the heap, at most 1 GiB.
+ */
+public final class ImageMemoryLimit {
+
+ /** ARGB, the widest raster PDFBox renders into. */
+ static final int BYTES_PER_PIXEL = 4;
+
+ private static final long AUTOMATIC_MAX_BYTES = 1L << 30;
+
+ /** Codecs whose decoder sizes its raster from the codec header, whatever the PDF declares. */
+ private static final Map<COSName, String> SELF_SIZING_CODECS =
+ Map.of(COSName.DCT_DECODE, "JPEG", COSName.JPX_DECODE, "JPEG2000");
+
+ private ImageMemoryLimit() {}
+
+ public static long maxPixels() {
+ ApplicationProperties properties =
+ ApplicationContextProvider.getBean(ApplicationProperties.class);
+ int configured =
+ properties == null || properties.getSystem() == null
+ ? 0
+ : properties.getSystem().getMaxImageMegapixels();
+ return maxPixels(configured, Runtime.getRuntime().maxMemory());
+ }
+
+ static long maxPixels(int configuredMegapixels, long maxHeapBytes) {
+ if (configuredMegapixels > 0) {
+ return configuredMegapixels * 1_000_000L;
+ }
+ return Math.min(maxHeapBytes / 4, AUTOMATIC_MAX_BYTES) / BYTES_PER_PIXEL;
+ }
+
+ /**
+ * Rejects a page whose render at {@code scale} would exceed the limit. Sized from the crop box
+ * exactly as {@link org.apache.pdfbox.rendering.PDFRenderer} sizes it.
+ */
+ public static void requirePageFits(PDPage page, int pageNumber, float scale)
+ throws OutOfMemoryDpiException {
+ PDRectangle cropBox = page.getCropBox();
+ long pixels =
+ renderedSide(cropBox.getWidth(), scale) * renderedSide(cropBox.getHeight(), scale);
+ long limit = maxPixels();
+ if (pixels > limit) {
+ throw ExceptionUtils.createPageImageTooLargeException(
+ pageNumber, Math.round(scale * 72), megapixels(pixels), megapixels(limit));
+ }
+ }
+
+ /** Rejects a canvas the caller allocates itself to join several pages. */
+ public static void requireCombinedImageFits(long width, long height)
+ throws OutOfMemoryDpiException {
+ long pixels = width * height;
+ long limit = maxPixels();
+ if (pixels > limit) {
+ throw ExceptionUtils.createCombinedImageTooLargeException(
+ megapixels(pixels), megapixels(limit));
+ }
+ }
+
+ /**
+ * Whether {@link PDImageXObject#getImage()} would fit the limit, judged without decoding. Do
+ * not call {@code getWidth()}, {@code getHeight()} or {@code getColorSpace()} on an image
+ * before this: for JPEG 2000 they decode it in full.
+ */
+ public static boolean embeddedImageFits(PDImageXObject image) throws IOException {
+ return decodedPixels(image) <= maxPixels();
+ }
+
+ /** As {@link #embeddedImageFits}, but rejects an image over the limit. */
+ public static void requireEmbeddedImageFits(PDImageXObject image) throws IOException {
+ long pixels = decodedPixels(image);
+ long limit = maxPixels();
+ if (pixels > limit) {
+ throw ExceptionUtils.createEmbeddedImageTooLargeException(
+ megapixels(pixels), megapixels(limit));
+ }
+ }
+
+ /** PDFBox scales an image and its mask to the larger of the two before combining them. */
+ private static long decodedPixels(PDImageXObject image) throws IOException {
+ long width = 0;
+ long height = 0;
+ for (PDImageXObject part :
+ new PDImageXObject[] {image, image.getSoftMask(), image.getMask()}) {
+ if (part != null) {
+ long[] size = decodedSize(part);
+ width = Math.max(width, size[0]);
+ height = Math.max(height, size[1]);
+ }
+ }
+ return width * height;
+ }
+
+ private static long[] decodedSize(PDImageXObject image) throws IOException {
+ COSDictionary dictionary = image.getCOSObject();
+ long width = Math.max(dictionary.getInt(COSName.WIDTH, 0), 0);
+ long height = Math.max(dictionary.getInt(COSName.HEIGHT, 0), 0);
+ long[] codecSize = codecHeaderSize(image);
+ if (codecSize != null) {
+ width = Math.max(width, codecSize[0]);
+ height = Math.max(height, codecSize[1]);
+ }
+ return new long[] {width, height};
+ }
+
+ /** Reads only the codec's header; null when the image's last filter does not size itself. */
+ private static long[] codecHeaderSize(PDImageXObject image) throws IOException {
+ List<COSName> filters = image.getStream().getFilters();
+ if (filters.isEmpty()) {
+ return null;
+ }
+ COSName codec = filters.getLast();
+ String format = SELF_SIZING_CODECS.get(codec);
+ if (format == null) {
+ return null;
+ }
+ Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(format);
+ if (!readers.hasNext()) {
+ return null;
+ }
+ ImageReader reader = readers.next();
+ try (InputStream encoded = image.getStream().createInputStream(List.of(codec.getName()));
+ ImageInputStream input = ImageIO.createImageInputStream(encoded)) {
+ // PDFBox's DCTFilter skips one leading line feed; without the same skip the header
+ // read would fail on a stream PDFBox goes on to decode.
+ if (COSName.DCT_DECODE.equals(codec) && input.read() != 0x0A) {
+ input.seek(0);
+ }
+ reader.setInput(input, true, true);
+ return new long[] {reader.getWidth(0), reader.getHeight(0)};
+ } catch (IOException | RuntimeException e) {
+ // PDFBox's decoder parses the same header first, so it fails before allocating too.
+ return null;
+ } finally {
+ reader.dispose();
+ }
+ }
+
+ private static long renderedSide(float points, float scale) {
+ return (long) Math.max(Math.floor(points * scale), 1);
+ }
+
+ private static long megapixels(long pixels) {
+ return Math.ceilDiv(pixels, 1_000_000L);
+ }
+}
diff --git a/app/common/src/main/java/stirling/software/common/util/LimitedPDFRenderer.java b/app/common/src/main/java/stirling/software/common/util/LimitedPDFRenderer.java
new file mode 100644
index 0000000000..1b9b501d3d
--- /dev/null
+++ b/app/common/src/main/java/stirling/software/common/util/LimitedPDFRenderer.java
@@ -0,0 +1,29 @@
+package stirling.software.common.util;
+
+import java.awt.image.BufferedImage;
+import java.io.IOException;
+
+import org.apache.pdfbox.pdmodel.PDDocument;
+import org.apache.pdfbox.rendering.ImageType;
+import org.apache.pdfbox.rendering.PDFRenderer;
+import org.apache.pdfbox.rendering.RenderDestination;
+
+/**
+ * A {@link PDFRenderer} that refuses a page whose raster would exceed {@link ImageMemoryLimit}. Use
+ * it for every page render: every {@code renderImage} and {@code renderImageWithDPI} overload
+ * reaches the one overridden here.
+ */
+public class LimitedPDFRenderer extends PDFRenderer {
+
+ public LimitedPDFRenderer(PDDocument document) {
+ super(document);
+ }
+
+ @Override
+ public BufferedImage renderImage(
+ int pageIndex, float scale, ImageType imageType, RenderDestination destination)
+ throws IOException {
+ ImageMemoryLimit.requirePageFits(document.getPage(pageIndex), pageIndex + 1, scale);
+ return super.renderImage(pageIndex, scale, imageType, destination);
+ }
+}
diff --git a/app/common/src/main/java/stirling/software/common/util/PdfToCbrUtils.java b/app/common/src/main/java/stirling/software/common/util/PdfToCbrUtils.java
index cfc95a290f..09a31296be 100644
--- a/app/common/src/main/java/stirling/software/common/util/PdfToCbrUtils.java
+++ b/app/common/src/main/java/stirling/software/common/util/PdfToCbrUtils.java
@@ -59,7 +59,7 @@ public class PdfToCbrUtils {
}
private static byte[] createCbrFromPdf(PDDocument document, int dpi) throws IOException {
- PDFRenderer pdfRenderer = new PDFRenderer(document);
+ PDFRenderer pdfRenderer = new LimitedPDFRenderer(document);
pdfRenderer.setSubsamplingAllowed(true); // Enable subsampling to reduce memory usage
Path tempDir = Files.createTempDirectory("stirling-pdf-cbr-");
diff --git a/app/common/src/main/java/stirling/software/common/util/PdfToCbzUtils.java b/app/common/src/main/java/stirling/software/common/util/PdfToCbzUtils.java
index 06e4558b96..68fcc7a20a 100644
--- a/app/common/src/main/java/stirling/software/common/util/PdfToCbzUtils.java
+++ b/app/common/src/main/java/stirling/software/common/util/PdfToCbzUtils.java
@@ -58,7 +58,7 @@ public class PdfToCbzUtils {
private static TempFile createCbzFromPdf(
PDDocument document, int dpi, TempFileManager tempFileManager) throws IOException {
- PDFRenderer pdfRenderer = new PDFRenderer(document);
+ PDFRenderer pdfRenderer = new LimitedPDFRenderer(document);
pdfRenderer.setSubsamplingAllowed(true); // Enable subsampling to reduce memory usage
TempFile cbzTempFile = new TempFile(tempFileManager, ".cbz");
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 5206c59b38..aef52520d5 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
@@ -95,6 +95,7 @@ public class PdfUtils {
for (COSName name : resources.getXObjectNames()) {
PDXObject object = resources.getXObject(name);
if (object instanceof PDImageXObject image) {
+ ImageMemoryLimit.requireEmbeddedImageFits(image);
images.add(image.getImage());
} else if (object instanceof PDFormXObject form) {
collectImages(form.getResources(), images, visited);
@@ -150,6 +151,7 @@ public class PdfUtils {
return false;
}
+ /** Whether the page draws an image XObject, directly or through forms; decodes no image. */
public boolean hasImagesOnPage(PDPage page) throws IOException {
return containsImage(
page.getResources(), Collections.newSetFromMap(new IdentityHashMap<>()));
@@ -193,7 +195,7 @@ public class PdfUtils {
try (PDDocument document = pdfDocumentFactory.load(inputStream);
ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
- PDFRenderer pdfRenderer = new PDFRenderer(document);
+ PDFRenderer pdfRenderer = new LimitedPDFRenderer(document);
pdfRenderer.setSubsamplingAllowed(true);
if (!includeAnnotations) {
pdfRenderer.setAnnotationsFilter(annotation -> false);
@@ -218,10 +220,6 @@ public class PdfUtils {
final int pageIndex = i;
BufferedImage image;
try {
- // Validate dimensions before rendering
- ExceptionUtils.validateRenderingDimensions(
- document.getPage(pageIndex), pageIndex + 1, DPI);
-
image =
ExceptionUtils.handleOomRendering(
pageIndex + 1,
@@ -255,7 +253,7 @@ public class PdfUtils {
// Calculate the combined image dimensions
int maxWidth = 0;
- int totalHeight = 0;
+ long totalHeight = 0;
// Using a map to store the calculated dimensions of each page size
HashMap<PdfRenderSettingsKey, PdfImageDimensionValue> pageSizes =
@@ -287,9 +285,9 @@ public class PdfUtils {
totalHeight += dimension.height();
}
- // Create a new BufferedImage to store the combined images
+ ImageMemoryLimit.requireCombinedImageFits(maxWidth, totalHeight);
BufferedImage combined =
- prepareImageForPdfToImage(maxWidth, totalHeight, imageType);
+ prepareImageForPdfToImage(maxWidth, (int) totalHeight, imageType);
Graphics g = combined.getGraphics();
int currentHeight = 0;
@@ -298,10 +296,6 @@ public class PdfUtils {
for (int i = 0; i < pageCount; ++i) {
final int pageIndex = i;
try {
- // Validate dimensions before rendering
- ExceptionUtils.validateRenderingDimensions(
- document.getPage(pageIndex), pageIndex + 1, DPI);
-
pageImage =
ExceptionUtils.handleOomRendering(
pageIndex + 1,
@@ -343,10 +337,6 @@ public class PdfUtils {
final int pageIndex = i;
BufferedImage image;
try {
- // Validate dimensions before rendering
- ExceptionUtils.validateRenderingDimensions(
- document.getPage(pageIndex), pageIndex + 1, DPI);
-
image =
ExceptionUtils.handleOomRendering(
pageIndex + 1,
@@ -402,7 +392,7 @@ public class PdfUtils {
public PDDocument convertPdfToPdfImage(PDDocument document) throws IOException {
PDDocument imageDocument = new PDDocument();
try {
- PDFRenderer pdfRenderer = new PDFRenderer(document);
+ PDFRenderer pdfRenderer = new LimitedPDFRenderer(document);
pdfRenderer.setSubsamplingAllowed(true);
for (int page = 0; page < document.getNumberOfPages(); ++page) {
final int pageIndex = page;
diff --git a/app/common/src/main/java/stirling/software/common/util/misc/InvertFullColorStrategy.java b/app/common/src/main/java/stirling/software/common/util/misc/InvertFullColorStrategy.java
index cd39648d06..5f05165dda 100644
--- a/app/common/src/main/java/stirling/software/common/util/misc/InvertFullColorStrategy.java
+++ b/app/common/src/main/java/stirling/software/common/util/misc/InvertFullColorStrategy.java
@@ -26,6 +26,7 @@ import stirling.software.common.model.ApplicationProperties;
import stirling.software.common.model.api.misc.ReplaceAndInvert;
import stirling.software.common.util.ApplicationContextProvider;
import stirling.software.common.util.ExceptionUtils;
+import stirling.software.common.util.LimitedPDFRenderer;
@Slf4j
public class InvertFullColorStrategy extends ReplaceAndInvertColorStrategy {
@@ -49,7 +50,7 @@ public class InvertFullColorStrategy extends ReplaceAndInvertColorStrategy {
// Load the uploaded PDF
try (PDDocument document = Loader.loadPDF(tempFile.getFile())) {
// Render each page and invert colors
- PDFRenderer pdfRenderer = new PDFRenderer(document);
+ PDFRenderer pdfRenderer = new LimitedPDFRenderer(document);
pdfRenderer.setSubsamplingAllowed(
true); // Enable subsampling to reduce memory usage
for (int page = 0; page < document.getNumberOfPages(); page++) {
diff --git a/app/common/src/test/java/stirling/software/common/util/DecodedStreamLimitTest.java b/app/common/src/test/java/stirling/software/common/util/DecodedStreamLimitTest.java
new file mode 100644
index 0000000000..090f34cb27
--- /dev/null
+++ b/app/common/src/test/java/stirling/software/common/util/DecodedStreamLimitTest.java
@@ -0,0 +1,127 @@
+package stirling.software.common.util;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import java.awt.image.BufferedImage;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.List;
+import java.util.Map;
+import java.util.zip.DeflaterOutputStream;
+
+import org.apache.pdfbox.cos.COSArray;
+import org.apache.pdfbox.cos.COSDictionary;
+import org.apache.pdfbox.cos.COSName;
+import org.apache.pdfbox.cos.COSStream;
+import org.apache.pdfbox.filter.Filter;
+import org.apache.pdfbox.filter.FilterFactory;
+import org.apache.pdfbox.pdmodel.PDDocument;
+import org.apache.pdfbox.pdmodel.PDPage;
+import org.apache.pdfbox.pdmodel.graphics.image.LosslessFactory;
+import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
+import org.junit.jupiter.api.Test;
+
+import stirling.software.common.util.DecodedStreamLimit.BoundedFilter;
+import stirling.software.common.util.ExceptionUtils.DecodedStreamTooLargeException;
+import stirling.software.common.util.ExceptionUtils.ErrorCode;
+
+class DecodedStreamLimitTest {
+
+ private static final int CAP = 64 * 1024;
+
+ @Test
+ void aStreamDecodingPastTheCapIsRefused() throws IOException {
+ Filter flate = new BoundedFilter(rawFlate(), () -> CAP);
+ byte[] bomb = deflated(CAP + 1);
+
+ assertThatThrownBy(
+ () ->
+ flate.decode(
+ new ByteArrayInputStream(bomb),
+ OutputStream.nullOutputStream(),
+ new COSDictionary(),
+ 0))
+ .isInstanceOfSatisfying(
+ DecodedStreamTooLargeException.class,
+ e ->
+ assertThat(e.getErrorCode())
+ .isEqualTo(ErrorCode.DECODED_STREAM_TOO_LARGE.getCode()));
+ }
+
+ @Test
+ void aStreamWithinTheCapDecodes() throws IOException {
+ Filter flate = new BoundedFilter(rawFlate(), () -> CAP);
+ ByteArrayOutputStream decoded = new ByteArrayOutputStream();
+
+ flate.decode(new ByteArrayInputStream(deflated(CAP)), decoded, new COSDictionary(), 0);
+
+ assertThat(decoded.size()).isEqualTo(CAP);
+ }
+
+ @Test
+ void installWrapsEachFilterOnceAndKeepsEncodingWorking() throws IOException {
+ DecodedStreamLimit.install();
+ Filter flate = FilterFactory.INSTANCE.getFilter(COSName.FLATE_DECODE);
+ DecodedStreamLimit.install();
+
+ assertThat(flate).isInstanceOf(BoundedFilter.class);
+ assertThat(FilterFactory.INSTANCE.getFilter(COSName.FLATE_DECODE)).isSameAs(flate);
+ assertThat(FilterFactory.INSTANCE.getFilter(COSName.FLATE_DECODE_ABBREVIATION))
+ .isSameAs(flate);
+ try (PDDocument document = new PDDocument()) {
+ PDImageXObject image =
+ LosslessFactory.createFromImage(
+ document, new BufferedImage(4, 4, BufferedImage.TYPE_INT_RGB));
+ assertThat(image.getImage().getWidth()).isEqualTo(4);
+ }
+ }
+
+ @Test
+ void aContentStreamPastTheCapFailsTheRenderInsteadOfDrawingABlankPage() throws IOException {
+ Map<COSName, Filter> registry = filterRegistry();
+ Filter original = registry.get(COSName.FLATE_DECODE);
+ registry.put(COSName.FLATE_DECODE, new BoundedFilter(rawFlate(), () -> CAP));
+ try (PDDocument document = new PDDocument()) {
+ COSStream content = document.getDocument().createCOSStream();
+ try (OutputStream out = content.createRawOutputStream()) {
+ out.write(deflated(CAP + 1));
+ }
+ // An array of filters takes PDFBox's buffered path, as any filter but a lone
+ // FlateDecode does; a lone FlateDecode is streamed and never buffered.
+ content.setItem(COSName.FILTER, new COSArray(List.of(COSName.FLATE_DECODE)));
+ PDPage page = new PDPage();
+ page.getCOSObject().setItem(COSName.CONTENTS, content);
+ document.addPage(page);
+
+ assertThatThrownBy(() -> new LimitedPDFRenderer(document).renderImage(0))
+ .isInstanceOf(DecodedStreamTooLargeException.class);
+ } finally {
+ registry.put(COSName.FLATE_DECODE, original);
+ }
+ }
+
+ private static Map<COSName, Filter> filterRegistry() {
+ try {
+ return DecodedStreamLimit.filterRegistry();
+ } catch (ReflectiveOperationException e) {
+ throw new AssertionError("PDFBox's FilterFactory no longer has its filters map", e);
+ }
+ }
+
+ /** Unwrapped even after another test installs the limit. */
+ private static Filter rawFlate() {
+ Filter flate = filterRegistry().get(COSName.FLATE_DECODE);
+ return flate instanceof BoundedFilter bounded ? bounded.delegate() : flate;
+ }
+
+ private static byte[] deflated(int zeroBytes) throws IOException {
+ ByteArrayOutputStream encoded = new ByteArrayOutputStream();
+ try (DeflaterOutputStream deflater = new DeflaterOutputStream(encoded)) {
+ deflater.write(new byte[zeroBytes]);
+ }
+ return encoded.toByteArray();
+ }
+}
diff --git a/app/common/src/test/java/stirling/software/common/util/ExceptionUtilsGapTest.java b/app/common/src/test/java/stirling/software/common/util/ExceptionUtilsGapTest.java
index 2fdc200008..5b3359c550 100644
--- a/app/common/src/test/java/stirling/software/common/util/ExceptionUtilsGapTest.java
+++ b/app/common/src/test/java/stirling/software/common/util/ExceptionUtilsGapTest.java
@@ -13,8 +13,6 @@ import static org.mockito.Mockito.mockStatic;
import java.io.IOException;
import java.util.List;
-import org.apache.pdfbox.pdmodel.PDPage;
-import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
@@ -416,35 +414,6 @@ class ExceptionUtilsGapTest {
}
}
- @Nested
- @DisplayName("validateRenderingDimensions")
- class ValidateRenderingDimensionsTests {
-
- @Test
- @DisplayName("null page is a no-op")
- void nullPage() {
- // Should simply return without throwing.
- org.junit.jupiter.api.Assertions.assertDoesNotThrow(
- () -> ExceptionUtils.validateRenderingDimensions(null, 1, 300));
- }
-
- @Test
- @DisplayName("normal letter-size page at 150 DPI passes validation")
- void normalPagePasses() {
- PDPage page = new PDPage(PDRectangle.LETTER);
- org.junit.jupiter.api.Assertions.assertDoesNotThrow(
- () -> ExceptionUtils.validateRenderingDimensions(page, 1, 150));
- }
-
- @Test
- @DisplayName("page with zero DPI yields zero pixels and passes")
- void zeroDpiPasses() {
- PDPage page = new PDPage(PDRectangle.A4);
- org.junit.jupiter.api.Assertions.assertDoesNotThrow(
- () -> ExceptionUtils.validateRenderingDimensions(page, 2, 0));
- }
- }
-
@Nested
@DisplayName("handleOomRendering wrappers")
class HandleOomRenderingTests {
diff --git a/app/common/src/test/java/stirling/software/common/util/ImageMemoryLimitTest.java b/app/common/src/test/java/stirling/software/common/util/ImageMemoryLimitTest.java
new file mode 100644
index 0000000000..2381687d17
--- /dev/null
+++ b/app/common/src/test/java/stirling/software/common/util/ImageMemoryLimitTest.java
@@ -0,0 +1,158 @@
+package stirling.software.common.util;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatCode;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import java.awt.image.BufferedImage;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+
+import javax.imageio.ImageIO;
+
+import org.apache.pdfbox.cos.COSName;
+import org.apache.pdfbox.cos.COSStream;
+import org.apache.pdfbox.pdmodel.PDDocument;
+import org.apache.pdfbox.pdmodel.PDPage;
+import org.apache.pdfbox.pdmodel.common.PDRectangle;
+import org.apache.pdfbox.pdmodel.common.PDStream;
+import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
+import org.junit.jupiter.api.Test;
+
+import stirling.software.common.util.ExceptionUtils.ErrorCode;
+import stirling.software.common.util.ExceptionUtils.OutOfMemoryDpiException;
+
+class ImageMemoryLimitTest {
+
+ /** 40000 pt square: 1.6 billion pixels at 72 DPI, over any automatic limit. */
+ private static final PDRectangle HUGE_PAGE = new PDRectangle(40_000, 40_000);
+
+ @Test
+ void aConfiguredLimitIsTakenInMegapixels() {
+ assertThat(ImageMemoryLimit.maxPixels(50, 8L << 30)).isEqualTo(50_000_000L);
+ }
+
+ @Test
+ void theAutomaticLimitFillsAQuarterOfTheHeapUpToOneGibibyte() {
+ assertThat(ImageMemoryLimit.maxPixels(0, 1L << 30)).isEqualTo((1L << 28) / 4);
+ assertThat(ImageMemoryLimit.maxPixels(0, 64L << 30)).isEqualTo((1L << 30) / 4);
+ }
+
+ @Test
+ void aPrintSizePageFits() {
+ assertThatCode(
+ () ->
+ ImageMemoryLimit.requirePageFits(
+ new PDPage(PDRectangle.LETTER), 1, 300 / 72f))
+ .doesNotThrowAnyException();
+ }
+
+ @Test
+ void aPageOverTheLimitIsRefused() {
+ assertThatThrownBy(() -> ImageMemoryLimit.requirePageFits(new PDPage(HUGE_PAGE), 3, 1))
+ .isInstanceOfSatisfying(
+ OutOfMemoryDpiException.class,
+ e -> {
+ assertThat(e.getErrorCode())
+ .isEqualTo(ErrorCode.PAGE_IMAGE_TOO_LARGE.getCode());
+ assertThat(e.getMessage()).startsWith("Page 3 at 72 DPI");
+ });
+ }
+
+ @Test
+ void aCanvasOverTheLimitIsRefused() {
+ assertThatThrownBy(() -> ImageMemoryLimit.requireCombinedImageFits(40_000, 40_000))
+ .isInstanceOfSatisfying(
+ OutOfMemoryDpiException.class,
+ e ->
+ assertThat(e.getErrorCode())
+ .isEqualTo(ErrorCode.COMBINED_IMAGE_TOO_LARGE.getCode()));
+ }
+
+ @Test
+ void theRendererRefusesAnOversizedPageBeforeAllocating() throws Exception {
+ try (PDDocument document = new PDDocument()) {
+ document.addPage(new PDPage(PDRectangle.A4));
+ document.addPage(new PDPage(HUGE_PAGE));
+ LimitedPDFRenderer renderer = new LimitedPDFRenderer(document);
+
+ BufferedImage firstPage = renderer.renderImageWithDPI(0, 72);
+
+ assertThat(firstPage.getWidth()).isEqualTo((int) PDRectangle.A4.getWidth());
+ assertThatThrownBy(() -> renderer.renderImageWithDPI(1, 72))
+ .isInstanceOf(OutOfMemoryDpiException.class);
+ }
+ }
+
+ @Test
+ void anEmbeddedImageIsSizedFromItsDictionaryWithoutDecoding() throws IOException {
+ try (PDDocument document = new PDDocument()) {
+ assertThat(ImageMemoryLimit.embeddedImageFits(declaredImage(document, 100, 100)))
+ .isTrue();
+ PDImageXObject bomb = declaredImage(document, 40_000, 40_000);
+
+ assertThat(ImageMemoryLimit.embeddedImageFits(bomb)).isFalse();
+ assertThatThrownBy(() -> ImageMemoryLimit.requireEmbeddedImageFits(bomb))
+ .isInstanceOfSatisfying(
+ OutOfMemoryDpiException.class,
+ e ->
+ assertThat(e.getErrorCode())
+ .isEqualTo(
+ ErrorCode.EMBEDDED_IMAGE_TOO_LARGE.getCode()));
+ }
+ }
+
+ @Test
+ void aSoftMaskLargerThanItsImageCounts() throws IOException {
+ try (PDDocument document = new PDDocument()) {
+ PDImageXObject image = declaredImage(document, 100, 100);
+ image.getCOSObject()
+ .setItem(COSName.SMASK, declaredImage(document, 40_000, 40_000).getCOSObject());
+
+ assertThat(ImageMemoryLimit.embeddedImageFits(image)).isFalse();
+ }
+ }
+
+ @Test
+ void aJpegIsSizedFromItsOwnHeaderWhateverTheDictionaryDeclares() throws IOException {
+ try (PDDocument document = new PDDocument()) {
+ PDImageXObject image = declaredImage(document, 8, 8);
+ COSStream stream = image.getCOSObject();
+ try (OutputStream out = stream.createRawOutputStream()) {
+ out.write(jpegClaiming(60_000, 60_000));
+ }
+ stream.setItem(COSName.FILTER, COSName.DCT_DECODE);
+
+ assertThat(ImageMemoryLimit.embeddedImageFits(image)).isFalse();
+ }
+ }
+
+ private static PDImageXObject declaredImage(PDDocument document, int width, int height)
+ throws IOException {
+ COSStream stream = document.getDocument().createCOSStream();
+ stream.setItem(COSName.SUBTYPE, COSName.IMAGE);
+ stream.setInt(COSName.WIDTH, width);
+ stream.setInt(COSName.HEIGHT, height);
+ stream.setInt(COSName.BITS_PER_COMPONENT, 8);
+ stream.setItem(COSName.COLORSPACE, COSName.DEVICERGB);
+ return new PDImageXObject(new PDStream(stream), null);
+ }
+
+ /** An 8x8 JPEG whose SOF0 header is rewritten to claim another size. */
+ private static byte[] jpegClaiming(int width, int height) throws IOException {
+ ByteArrayOutputStream encoded = new ByteArrayOutputStream();
+ ImageIO.write(new BufferedImage(8, 8, BufferedImage.TYPE_INT_RGB), "jpeg", encoded);
+ byte[] jpeg = encoded.toByteArray();
+ for (int i = 2; i + 8 < jpeg.length; i++) {
+ if ((jpeg[i] & 0xFF) == 0xFF && (jpeg[i + 1] & 0xFF) == 0xC0) {
+ jpeg[i + 5] = (byte) (height >> 8);
+ jpeg[i + 6] = (byte) height;
+ jpeg[i + 7] = (byte) (width >> 8);
+ jpeg[i + 8] = (byte) width;
+ return jpeg;
+ }
+ }
+ throw new IllegalStateException("no SOF0 marker");
+ }
+}
diff --git a/app/common/src/test/java/stirling/software/common/util/PdfUtilsMoreTest.java b/app/common/src/test/java/stirling/software/common/util/PdfUtilsMoreTest.java
index cf7e17a3e0..26a5cf703e 100644
--- a/app/common/src/test/java/stirling/software/common/util/PdfUtilsMoreTest.java
+++ b/app/common/src/test/java/stirling/software/common/util/PdfUtilsMoreTest.java
@@ -16,11 +16,14 @@ import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
+import org.apache.pdfbox.cos.COSName;
+import org.apache.pdfbox.cos.COSStream;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.PDResources;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
+import org.apache.pdfbox.pdmodel.common.PDStream;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.pdmodel.font.Standard14Fonts;
import org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject;
@@ -130,6 +133,60 @@ class PdfUtilsMoreTest {
}
}
+ @Nested
+ @DisplayName("hasImagesOnPage with form XObjects")
+ class HasImagesOnPageForms {
+
+ @Test
+ @DisplayName("an image nested inside a form XObject is found")
+ void findsAnImageInsideAForm() throws IOException {
+ try (PDDocument doc = new PDDocument()) {
+ PDFormXObject form = new PDFormXObject(doc);
+ form.setResources(new PDResources());
+ BufferedImage bi = new BufferedImage(8, 8, BufferedImage.TYPE_INT_RGB);
+ form.getResources().add(LosslessFactory.createFromImage(doc, bi));
+ PDPage page = new PDPage();
+ page.setResources(new PDResources());
+ page.getResources().add(form);
+
+ assertThat(PdfUtils.hasImagesOnPage(page)).isTrue();
+ }
+ }
+
+ @Test
+ @DisplayName("a form that draws itself is walked once")
+ void stopsAtAFormThatDrawsItself() throws IOException {
+ try (PDDocument doc = new PDDocument()) {
+ PDFormXObject form = new PDFormXObject(doc);
+ form.setResources(new PDResources());
+ form.getResources().add(form);
+ PDPage page = new PDPage();
+ page.setResources(new PDResources());
+ page.getResources().add(form);
+
+ assertThat(PdfUtils.hasImagesOnPage(page)).isFalse();
+ }
+ }
+
+ @Test
+ @DisplayName("an image is found without being decoded")
+ void doesNotDecodeTheImage() throws IOException {
+ try (PDDocument doc = new PDDocument()) {
+ COSStream stream = doc.getDocument().createCOSStream();
+ stream.setItem(COSName.SUBTYPE, COSName.IMAGE);
+ stream.setInt(COSName.WIDTH, 100_000);
+ stream.setInt(COSName.HEIGHT, 100_000);
+ stream.setInt(COSName.BITS_PER_COMPONENT, 8);
+ stream.setItem(COSName.COLORSPACE, COSName.DEVICERGB);
+ PDPage page = new PDPage();
+ page.setResources(new PDResources());
+ page.getResources().add(new PDImageXObject(new PDStream(stream), null));
+
+ assertThat(PdfUtils.hasImagesOnPage(page)).isTrue();
+ }
+ }
+ }
+
// ---- hasText found branch ----------------------------------------------
@Nested
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/CropController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/CropController.java
index 95daf28043..57c32f0712 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/CropController.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/CropController.java
@@ -35,6 +35,7 @@ import stirling.software.common.model.tool.ToolIO;
import stirling.software.common.service.CustomPDFDocumentFactory;
import stirling.software.common.util.ExceptionUtils;
import stirling.software.common.util.GeneralUtils;
+import stirling.software.common.util.LimitedPDFRenderer;
import stirling.software.common.util.ProcessExecutor;
import stirling.software.common.util.TempFile;
import stirling.software.common.util.TempFileManager;
@@ -180,7 +181,7 @@ public class CropController {
try (PDDocument newDocument =
pdfDocumentFactory.createNewDocumentBasedOnOldDocument(sourceDocument)) {
- PDFRenderer renderer = new PDFRenderer(sourceDocument);
+ PDFRenderer renderer = new LimitedPDFRenderer(sourceDocument);
renderer.setSubsamplingAllowed(true); // Enable subsampling to reduce memory usage
LayerUtility layerUtility = new LayerUtility(newDocument);
BitSet pagesToCrop = pageSelection(request, sourceDocument);
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToPDFA.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToPDFA.java
index ea29dffa7a..a9674fd100 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToPDFA.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToPDFA.java
@@ -98,6 +98,7 @@ import stirling.software.common.model.tool.ToolFormat;
import stirling.software.common.model.tool.ToolIO;
import stirling.software.common.service.PdfaLevelAServiceInterface;
import stirling.software.common.util.ExceptionUtils;
+import stirling.software.common.util.ImageMemoryLimit;
import stirling.software.common.util.ProcessExecutor;
import stirling.software.common.util.ProcessExecutor.ProcessExecutorResult;
import stirling.software.common.util.TempFile;
@@ -809,6 +810,7 @@ public class ConvertPDFToPDFA {
PDXObject loXo = loRes.getXObject(name);
if (!(loXo instanceof PDImageXObject img)) continue;
+ ImageMemoryLimit.requireEmbeddedImageFits(img);
PDImageXObject newImg = LosslessFactory.createFromImage(baseDoc, img.getImage());
// replace the resource under the same name
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertPdfToVideoController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertPdfToVideoController.java
index df5a91ad67..4e5a9ff1d9 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertPdfToVideoController.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertPdfToVideoController.java
@@ -29,6 +29,7 @@ import stirling.software.common.model.ApplicationProperties;
import stirling.software.common.service.CustomPDFDocumentFactory;
import stirling.software.common.util.ApplicationContextProvider;
import stirling.software.common.util.ExceptionUtils;
+import stirling.software.common.util.LimitedPDFRenderer;
import stirling.software.common.util.TempFile;
import stirling.software.common.util.TempFileManager;
@@ -161,7 +162,7 @@ public class ConvertPdfToVideoController {
boolean isWatermarkEnabled)
throws IOException {
try (PDDocument document = pdfDocumentFactory.load(inputPdf.toFile())) {
- PDFRenderer renderer = new PDFRenderer(document);
+ PDFRenderer renderer = new LimitedPDFRenderer(document);
renderer.setSubsamplingAllowed(true);
int pageCount = document.getNumberOfPages();
if (pageCount == 0) {
@@ -171,10 +172,6 @@ public class ConvertPdfToVideoController {
for (int pageIndex = 0; pageIndex < pageCount; pageIndex++) {
final int currentPageIndex = pageIndex;
- // Validate dimensions BEFORE attempting to render to prevent OOM
- ExceptionUtils.validateRenderingDimensions(
- document.getPage(currentPageIndex), currentPageIndex + 1, dpi);
-
BufferedImage image =
ExceptionUtils.handleOomRendering(
currentPageIndex + 1,
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/AutoRotateController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/AutoRotateController.java
index 85d60b02be..2a4ed8a125 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/AutoRotateController.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/AutoRotateController.java
@@ -51,6 +51,7 @@ import stirling.software.common.model.tool.ToolIOWhen;
import stirling.software.common.service.CustomPDFDocumentFactory;
import stirling.software.common.util.ExceptionUtils;
import stirling.software.common.util.GeneralUtils;
+import stirling.software.common.util.LimitedPDFRenderer;
import stirling.software.common.util.ProcessExecutor;
import stirling.software.common.util.ProcessExecutor.ProcessExecutorResult;
import stirling.software.common.util.TempDirectory;
@@ -256,7 +257,7 @@ public class AutoRotateController {
final int renderDpi = dpi;
try (TempDirectory tempDir = new TempDirectory(tempFileManager)) {
- PDFRenderer renderer = new PDFRenderer(document);
+ PDFRenderer renderer = new LimitedPDFRenderer(document);
renderer.setSubsamplingAllowed(true);
// One reused path, deleted after every page: the images are throwaway input for
// Tesseract, so a long document must not accumulate one file per page on disk.
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.java
index ea8b79916a..7a35de3ec4 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
@@ -47,6 +47,8 @@ import stirling.software.common.model.tool.ToolIO;
import stirling.software.common.service.CustomPDFDocumentFactory;
import stirling.software.common.util.ExceptionUtils;
import stirling.software.common.util.GeneralUtils;
+import stirling.software.common.util.ImageMemoryLimit;
+import stirling.software.common.util.LimitedPDFRenderer;
import stirling.software.common.util.TempFile;
import stirling.software.common.util.TempFileManager;
import stirling.software.common.util.WebResponseUtils;
@@ -214,20 +216,12 @@ public class AutoSplitPdfController {
continue;
}
PDImageXObject imageObject = (PDImageXObject) page.getResources().getXObject(name);
-
- BufferedImage image;
- try {
- image = imageObject.getImage();
- } catch (OutOfMemoryError e) {
- log.warn(
- "Skipping oversized embedded image '{}' ({}x{}) - out of memory",
- name.getName(),
- imageObject.getWidth(),
- imageObject.getHeight());
+ if (!ImageMemoryLimit.embeddedImageFits(imageObject)) {
+ log.warn("Skipping embedded image '{}': over the image limit", name.getName());
continue;
}
- String result = decodeQRCode(image);
+ String result = decodeQRCode(imageObject.getImage());
if (result != null) {
return result;
}
@@ -305,7 +299,7 @@ public class AutoSplitPdfController {
int totalPages = document.getNumberOfPages();
log.info("PDF loaded, totalPages={}", totalPages);
- PDFRenderer pdfRenderer = new PDFRenderer(document);
+ PDFRenderer pdfRenderer = new LimitedPDFRenderer(document);
pdfRenderer.setSubsamplingAllowed(true);
for (int page = 0; page < totalPages; ++page) {
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/BlankPageController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/BlankPageController.java
index 0a1477c72e..c92c6ef19b 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/BlankPageController.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/BlankPageController.java
@@ -40,6 +40,7 @@ import stirling.software.common.service.CustomPDFDocumentFactory;
import stirling.software.common.util.ApplicationContextProvider;
import stirling.software.common.util.ExceptionUtils;
import stirling.software.common.util.GeneralUtils;
+import stirling.software.common.util.LimitedPDFRenderer;
import stirling.software.common.util.PdfUtils;
import stirling.software.common.util.TempFile;
import stirling.software.common.util.TempFileManager;
@@ -114,7 +115,7 @@ public class BlankPageController {
List<PDPage> blankPages = new ArrayList<>();
int pageIndex = 0;
- PDFRenderer pdfRenderer = new PDFRenderer(document);
+ PDFRenderer pdfRenderer = new LimitedPDFRenderer(document);
pdfRenderer.setSubsamplingAllowed(true);
for (PDPage page : pages) {
log.info("checking page {}", pageIndex);
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/CompressController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/CompressController.java
index 03943ba87e..e5a5be315a 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/CompressController.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/CompressController.java
@@ -56,6 +56,7 @@ import stirling.software.common.service.CustomPDFDocumentFactory;
import stirling.software.common.service.LineArtConversionService;
import stirling.software.common.util.ExceptionUtils;
import stirling.software.common.util.GeneralUtils;
+import stirling.software.common.util.ImageMemoryLimit;
import stirling.software.common.util.ProcessExecutor;
import stirling.software.common.util.ProcessExecutor.ProcessExecutorResult;
import stirling.software.common.util.TempFile;
@@ -150,6 +151,13 @@ public class CompressController {
// Direct image
if (isImage(xobj)) {
+ if (!ImageMemoryLimit.embeddedImageFits((PDImageXObject) xobj)) {
+ log.info(
+ "Leaving image '{}' on page {} uncompressed: over the image limit",
+ name.getName(),
+ pageNum + 1);
+ continue;
+ }
addDirectImage(pageNum, name, (PDImageXObject) xobj, uniqueImages);
log.info(
"Found direct image '{}' on page {} - {}x{}",
@@ -207,6 +215,15 @@ public class CompressController {
if (isImage(nestedXobj)) {
PDImageXObject nestedImage = (PDImageXObject) nestedXobj;
+ if (!ImageMemoryLimit.embeddedImageFits(nestedImage)) {
+ log.info(
+ "Leaving image '{}' in form '{}' on page {} uncompressed: over the"
+ + " image limit",
+ nestedName.getName(),
+ formName.getName(),
+ pageNum + 1);
+ continue;
+ }
log.info(
"Found nested image '{}' in form '{}' on page {} - {}x{}",
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/ExtractImageScansController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/ExtractImageScansController.java
index 6b665ba969..36293b3851 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/ExtractImageScansController.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/ExtractImageScansController.java
@@ -42,6 +42,7 @@ import stirling.software.common.util.ApplicationContextProvider;
import stirling.software.common.util.CheckProgramInstall;
import stirling.software.common.util.ExceptionUtils;
import stirling.software.common.util.GeneralUtils;
+import stirling.software.common.util.LimitedPDFRenderer;
import stirling.software.common.util.ProcessExecutor;
import stirling.software.common.util.ProcessExecutor.ProcessExecutorResult;
import stirling.software.common.util.TempFile;
@@ -109,7 +110,7 @@ public class ExtractImageScansController {
if ("pdf".equalsIgnoreCase(extension)) {
// Load PDF document
try (PDDocument document = pdfDocumentFactory.load(inputFile)) {
- PDFRenderer pdfRenderer = new PDFRenderer(document);
+ PDFRenderer pdfRenderer = new LimitedPDFRenderer(document);
pdfRenderer.setSubsamplingAllowed(true);
int pageCount = document.getNumberOfPages();
images = new ArrayList<>();
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/ExtractImagesController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/ExtractImagesController.java
index 1efc277b3f..3fce459d33 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/ExtractImagesController.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/ExtractImagesController.java
@@ -56,6 +56,7 @@ import stirling.software.common.model.tool.ToolIO;
import stirling.software.common.service.CustomPDFDocumentFactory;
import stirling.software.common.util.ExceptionUtils;
import stirling.software.common.util.GeneralUtils;
+import stirling.software.common.util.ImageMemoryLimit;
import stirling.software.common.util.TempFile;
import stirling.software.common.util.TempFileManager;
import stirling.software.common.util.WebResponseUtils;
@@ -153,6 +154,9 @@ public class ExtractImagesController {
try {
PDImageXObject imageObject =
(PDImageXObject) page.getResources().getXObject(resourceName);
+ // Before fingerprinting, which reads the colour space: a JPEG 2000 image decodes
+ // in full to supply it.
+ ImageMemoryLimit.requireEmbeddedImageFits(imageObject);
if (!fingerprints.isFirstOccurrence(imageObject)) {
continue;
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/FlattenController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/FlattenController.java
index f88123117f..9dd805311f 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/FlattenController.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/FlattenController.java
@@ -34,6 +34,7 @@ import stirling.software.common.model.tool.ToolIO;
import stirling.software.common.service.CustomPDFDocumentFactory;
import stirling.software.common.util.ApplicationContextProvider;
import stirling.software.common.util.ExceptionUtils;
+import stirling.software.common.util.LimitedPDFRenderer;
import stirling.software.common.util.TempFileManager;
import stirling.software.common.util.WebResponseUtils;
@@ -78,7 +79,7 @@ public class FlattenController {
} else {
// flatten whole page aka convert each page to image and re-add it (making text
// unselectable)
- PDFRenderer pdfRenderer = new PDFRenderer(document);
+ PDFRenderer pdfRenderer = new LimitedPDFRenderer(document);
pdfRenderer.setSubsamplingAllowed(
true); // Enable subsampling to reduce memory usage
@@ -111,10 +112,6 @@ public class FlattenController {
final int pageIndex = i;
BufferedImage image = null;
try {
- // Validate dimensions BEFORE rendering to prevent OOM
- ExceptionUtils.validateRenderingDimensions(
- document.getPage(pageIndex), pageIndex + 1, renderDpi);
-
// Wrap entire rendering operation to catch OutOfMemoryError from any
// depth
image =
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/OCRController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/OCRController.java
index 4bf9fb3d5b..5bf857bb8d 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/OCRController.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/OCRController.java
@@ -49,6 +49,7 @@ import stirling.software.common.model.tool.ToolIOWhen;
import stirling.software.common.service.CustomPDFDocumentFactory;
import stirling.software.common.util.ExceptionUtils;
import stirling.software.common.util.GeneralUtils;
+import stirling.software.common.util.LimitedPDFRenderer;
import stirling.software.common.util.ProcessExecutor;
import stirling.software.common.util.ProcessExecutor.ProcessExecutorResult;
import stirling.software.common.util.TempDirectory;
@@ -363,7 +364,7 @@ public class OCRController {
merger.setDestinationFileName(finalOutputFile.toString());
try (PDDocument document = pdfDocumentFactory.load(tempInputFile.toFile())) {
- PDFRenderer pdfRenderer = new PDFRenderer(document);
+ PDFRenderer pdfRenderer = new LimitedPDFRenderer(document);
pdfRenderer.setSubsamplingAllowed(
true); // Enable subsampling to reduce memory usage
int pageCount = document.getNumberOfPages();
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/ScannerEffectController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/ScannerEffectController.java
index eb6b74fd58..db9bcc2a4c 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/ScannerEffectController.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/ScannerEffectController.java
@@ -54,6 +54,7 @@ import stirling.software.common.service.CustomPDFDocumentFactory;
import stirling.software.common.util.ApplicationContextProvider;
import stirling.software.common.util.ExceptionUtils;
import stirling.software.common.util.GeneralUtils;
+import stirling.software.common.util.LimitedPDFRenderer;
import stirling.software.common.util.TempFileManager;
import stirling.software.common.util.WebResponseUtils;
@@ -741,7 +742,7 @@ public class ScannerEffectController {
private RenderingResources(PDDocument document) {
this.document = document;
- this.renderer = new PDFRenderer(document);
+ this.renderer = new LimitedPDFRenderer(document);
this.renderer.setSubsamplingAllowed(true);
this.renderer.setImageDownscalingOptimizationThreshold(0.5f);
}
diff --git a/app/core/src/main/java/stirling/software/SPDF/exception/GlobalExceptionHandler.java b/app/core/src/main/java/stirling/software/SPDF/exception/GlobalExceptionHandler.java
index fb913d663c..c80493de8a 100644
--- a/app/core/src/main/java/stirling/software/SPDF/exception/GlobalExceptionHandler.java
+++ b/app/core/src/main/java/stirling/software/SPDF/exception/GlobalExceptionHandler.java
@@ -552,6 +552,18 @@ public class GlobalExceptionHandler {
* @param request the HTTP servlet request
* @return ProblemDetail with HTTP 400 BAD_REQUEST
*/
+ @ExceptionHandler(DecodedStreamTooLargeException.class)
+ public ResponseEntity<ProblemDetail> handleDecodedStreamTooLarge(
+ DecodedStreamTooLargeException ex, HttpServletRequest request) {
+ logException("warn", "Decoded stream too large", request, ex, ex.getErrorCode());
+ String title =
+ getLocalizedMessage(
+ "error.decodedStreamTooLarge.title",
+ ErrorTitles.DECODED_STREAM_TOO_LARGE_DEFAULT);
+ return createProblemDetailResponse(
+ ex, HttpStatus.BAD_REQUEST, ErrorTypes.DECODED_STREAM_TOO_LARGE, title, request);
+ }
+
@ExceptionHandler(BaseValidationException.class)
public ResponseEntity<ProblemDetail> handleValidation(
BaseValidationException ex, HttpServletRequest request) {
@@ -1220,6 +1232,8 @@ public class GlobalExceptionHandler {
} else {
return handleValidation(valEx, request);
}
+ } else if (cause instanceof DecodedStreamTooLargeException tooLarge) {
+ return handleDecodedStreamTooLarge(tooLarge, request);
} else if (cause instanceof IOException) {
// Unwrap and handle IOException (may contain PDF-specific errors)
return handleIOException((IOException) cause, request);
@@ -1510,6 +1524,7 @@ public class GlobalExceptionHandler {
static final String FFMPEG_REQUIRED = "/errors/ffmpeg-required";
static final String TOOL_REQUIRED = "/errors/tool-required";
static final String OUT_OF_MEMORY_DPI = "/errors/out-of-memory-dpi";
+ static final String DECODED_STREAM_TOO_LARGE = "/errors/decoded-stream-too-large";
static final String PDF_CORRUPTED = "/errors/pdf-corrupted";
static final String PDF_ENCRYPTION = "/errors/pdf-encryption";
static final String APP_ERROR = "/errors/app-error";
@@ -1540,6 +1555,7 @@ public class GlobalExceptionHandler {
static final String FFMPEG_REQUIRED_DEFAULT = "FFmpeg Required";
static final String TOOL_REQUIRED_DEFAULT = "Required Tool Not Installed";
static final String OUT_OF_MEMORY_DPI_DEFAULT = "Insufficient Memory for Image Rendering";
+ static final String DECODED_STREAM_TOO_LARGE_DEFAULT = "Content Too Large to Decompress";
static final String PDF_CORRUPTED_DEFAULT = "PDF File Corrupted";
static final String PDF_ENCRYPTION_DEFAULT = "PDF Encryption Error";
static final String APPLICATION_DEFAULT = "Application Error";
diff --git a/app/core/src/main/resources/settings.yml.template b/app/core/src/main/resources/settings.yml.template
index fb715bd1fe..33abf4b12b 100644
--- a/app/core/src/main/resources/settings.yml.template
+++ b/app/core/src/main/resources/settings.yml.template
@@ -190,6 +190,7 @@ system:
stirlingOfficeConversion: false # Beta: set to 'true' to convert Office files with the built-in Stirling Office Convert (better, faster conversions using less memory) instead of LibreOffice
maxDPI: 500 # Maximum allowed DPI for PDF to image conversion
maxPdfaConversionPages: 20000 # Most pages a PDF/A or PDF/X conversion accepts; larger documents are refused (0 = unlimited)
+ maxImageMegapixels: 0 # Largest image one page render may create, in megapixels. 0 = automatic (a quarter of the Java heap, at most 1 GB)
corsAllowedOrigins: [] # List of allowed origins for CORS (e.g. ['http://localhost:5173', 'https://app.example.com']). WARNING: leaving this empty falls back to allowing ALL origins (with credentials), it does NOT disable CORS. Set explicit origins to lock it down.
backendUrl: "" # Backend base URL for SAML/OAuth/API callbacks (e.g. 'http://localhost:8080' for dev, 'https://api.example.com' for production). REQUIRED for SSO authentication to work correctly. This is where your IdP will send SAML responses and OAuth callbacks. Leave empty to default to 'http://localhost:8080' in development.
frontendUrl: "" # Base URL of the web app, as a browser reaches it (e.g. 'https://app.example.com', or 'https://example.com/app' if served under a base path). Optional - if not set, will use backendUrl. Used for any link handed to a browser: invite and signing emails, share links, mobile QR codes, and the account-link handshake.
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureKind.java b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureKind.java
index 624457959d..655c21867e 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureKind.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureKind.java
@@ -241,21 +241,53 @@ public enum FailureKind {
global(DISMISS, ANYONE_WHO_SEES, OVERFLOW)),
/**
- * A page ran the renderer out of memory at the requested resolution. The page's size and the
- * step's DPI decide it together, so one oversized page fails while its neighbours succeed.
+ * A page's image at the requested resolution exceeded the server's image limit or ran the
+ * renderer out of memory. The page's size and the step's DPI decide it together, so one
+ * oversized page fails while its neighbours succeed.
*/
STEP_PAGE_TOO_LARGE(
FailureStage.INTERNAL,
FailureSeverity.ERROR,
FailureRemedy.NEEDS_CONFIG_FIX,
FailureScope.FILE,
- errorCodes("E081"),
+ errorCodes("E081", "E084", "E085"),
fallback(
"A page in this document was too large to render at the requested resolution."),
global(VIEW_FILE, OWNER, SECONDARY),
global(VIEW_IN_PROCESSOR, TEAM_REVIEWER, OVERFLOW),
global(DISMISS, ANYONE_WHO_SEES, OVERFLOW)),
+ /**
+ * An image embedded in the document is larger than the server's image limit. No step setting
+ * changes that: only a smaller image or a higher limit clears it.
+ */
+ INPUT_IMAGE_TOO_LARGE(
+ FailureStage.INPUT,
+ FailureSeverity.ERROR,
+ FailureRemedy.NEEDS_SERVER_FIX,
+ FailureScope.FILE,
+ errorCodes("E086"),
+ fallback("An image in this document is larger than this server can process."),
+ global(VIEW_FILE, OWNER, SECONDARY),
+ global(VIEW_IN_PROCESSOR, TEAM_REVIEWER, OVERFLOW),
+ global(DISMISS, ANYONE_WHO_SEES, OVERFLOW)),
+
+ /**
+ * A stream in the document decompresses past the server's limit. Practically always a damaged
+ * or hostile file, so no repair is offered: repairing decompresses the same stream.
+ */
+ INPUT_DECOMPRESSES_TOO_LARGE(
+ FailureStage.INPUT,
+ FailureSeverity.ERROR,
+ FailureRemedy.NEEDS_FILE_FIX,
+ FailureScope.FILE,
+ errorCodes("E087"),
+ fallback(
+ "Part of this document decompresses to more data than this server can process."),
+ global(VIEW_FILE, OWNER, SECONDARY),
+ global(VIEW_IN_PROCESSOR, TEAM_REVIEWER, OVERFLOW),
+ global(DISMISS, ANYONE_WHO_SEES, OVERFLOW)),
+
/**
* The step's settings, not the document, were refused: no OCR language, an unparseable page
* size. Scoped to the policy, since every document it reaches fails identically until the step
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/failure/FailureKindTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/failure/FailureKindTest.java
index 896d267445..52a9a1f430 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/failure/FailureKindTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/failure/FailureKindTest.java
@@ -465,6 +465,8 @@ class FailureKindTest {
FailureKind.STEP_TOOL_FAILED,
FailureKind.STEP_INTERRUPTED,
FailureKind.STEP_PAGE_TOO_LARGE,
+ FailureKind.INPUT_IMAGE_TOO_LARGE,
+ FailureKind.INPUT_DECOMPRESSES_TOO_LARGE,
FailureKind.STEP_MISCONFIGURED);
}
diff --git a/frontend/public/locales/en-US/translation.toml b/frontend/public/locales/en-US/translation.toml
index 49b0a8ecf6..f6f9ce0398 100644
--- a/frontend/public/locales/en-US/translation.toml
+++ b/frontend/public/locales/en-US/translation.toml
@@ -9211,10 +9211,18 @@ title = "Compliance standard not met"
description = "Your file is damaged, so the run could not read it."
title = "Damaged document"
+[portal.failures.kind.inputDecompressesTooLarge]
+description = "Part of your file decompresses to more data than this server will process. The file may be damaged."
+title = "File expands too large to process"
+
[portal.failures.kind.inputEmpty]
description = "Your file has no content in it, so there was nothing for the run to work on."
title = "Empty file"
+[portal.failures.kind.inputImageTooLarge]
+description = "An image in your file is larger than this server will process."
+title = "Image too large to process"
+
[portal.failures.kind.inputPasswordProtected]
description = "Your file is password protected, so the run could not read it."
title = "Password-protected document"
diff --git a/frontend/src/editor/core/services/notificationRetry.ts b/frontend/src/editor/core/services/notificationRetry.ts
index 4b25baf7c0..5984a74eea 100644
--- a/frontend/src/editor/core/services/notificationRetry.ts
+++ b/frontend/src/editor/core/services/notificationRetry.ts
@@ -58,7 +58,9 @@ export const KIND_ERROR_CODES: Record<string, readonly string[]> = {
STEP_CANNOT_RENDER_PAGE: ["E054"],
STEP_TOOL_FAILED: ["E044", "E051", "E052", "E060", "E077", "E083"],
STEP_INTERRUPTED: ["E053"],
- STEP_PAGE_TOO_LARGE: ["E081"],
+ STEP_PAGE_TOO_LARGE: ["E081", "E084", "E085"],
+ INPUT_IMAGE_TOO_LARGE: ["E086"],
+ INPUT_DECOMPRESSES_TOO_LARGE: ["E087"],
STEP_MISCONFIGURED: ["E040", "E041", "E043", "E050", "E070", "E072"],
};
diff --git a/scripts/init-without-ocr.sh b/scripts/init-without-ocr.sh
index 7ee644b5be..1a5f9583a2 100755
--- a/scripts/init-without-ocr.sh
+++ b/scripts/init-without-ocr.sh
@@ -1537,8 +1537,8 @@ if [ "$AOT_GENERATE_BACKGROUND" = true ]; then
fi
fi
-wait "$JAVA_PID" || true
-exit_code=$?
+exit_code=0
+wait "$JAVA_PID" || exit_code=$?
if [ -n "$ENGINE_PID" ] && kill -0 "$ENGINE_PID" 2>/dev/null; then
log "Stopping AI engine (PID $ENGINE_PID)..."
diff --git a/testing/failure-kind-codes.json b/testing/failure-kind-codes.json
index d0eaaef529..af70cae7c7 100644
--- a/testing/failure-kind-codes.json
+++ b/testing/failure-kind-codes.json
@@ -19,7 +19,9 @@
"STEP_CANNOT_RENDER_PAGE": ["E054"],
"STEP_TOOL_FAILED": ["E044", "E051", "E052", "E060", "E077", "E083"],
"STEP_INTERRUPTED": ["E053"],
- "STEP_PAGE_TOO_LARGE": ["E081"],
+ "STEP_PAGE_TOO_LARGE": ["E081", "E084", "E085"],
+ "INPUT_IMAGE_TOO_LARGE": ["E086"],
+ "INPUT_DECOMPRESSES_TOO_LARGE": ["E087"],
"STEP_MISCONFIGURED": ["E040", "E041", "E043", "E050", "E070", "E072"]
}
}