Skip to content

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

Bound the PDF/A sanitizer's per-page and per-annotation work (#8681)

ConnorYohac487a13a4c8
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 cf536ee5a7..660167ada0 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
@@ -1320,6 +1320,7 @@ public class ApplicationProperties {
private boolean disableSanitize;
private boolean stirlingOfficeConversion;
private int maxDPI = 500;
+ private int maxPdfaConversionPages = 20_000;
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/OfficeDocumentSanitizer.java b/app/common/src/main/java/stirling/software/common/util/OfficeDocumentSanitizer.java
index 8e7d3bed98..74583a07d3 100644
--- a/app/common/src/main/java/stirling/software/common/util/OfficeDocumentSanitizer.java
+++ b/app/common/src/main/java/stirling/software/common/util/OfficeDocumentSanitizer.java
@@ -177,7 +177,7 @@ public class OfficeDocumentSanitizer {
if (isAdminAllowed(targetValue)) {
continue;
}
- log.warn(
+ log.debug(
"Stripping OOXML external relationship target: {}",
truncateForLog(targetValue));
toRemove.add(node);
@@ -185,6 +185,7 @@ public class OfficeDocumentSanitizer {
if (toRemove.isEmpty()) {
return xmlBytes;
}
+ log.warn("Stripping {} OOXML external relationship(s)", toRemove.size());
for (Node n : toRemove) {
n.getParentNode().removeChild(n);
}
@@ -198,15 +199,16 @@ public class OfficeDocumentSanitizer {
if (root == null) {
return xmlBytes;
}
- boolean modified = stripExternalHrefs(root);
- if (!modified) {
+ int stripped = stripExternalHrefs(root);
+ if (stripped == 0) {
return xmlBytes;
}
+ log.warn("Stripped {} ODF external href attribute(s)", stripped);
return serializeDocument(doc);
}
- private boolean stripExternalHrefs(Node node) {
- boolean modified = false;
+ private int stripExternalHrefs(Node node) {
+ int stripped = 0;
if (node.getNodeType() == Node.ELEMENT_NODE) {
NamedNodeMap attrs = node.getAttributes();
List<String> hrefAttrsToRemove = new ArrayList<>();
@@ -229,7 +231,7 @@ public class OfficeDocumentSanitizer {
if (isAdminAllowed(value)) {
continue;
}
- log.warn(
+ log.debug(
"Stripping ODF external href attribute ({}): {}",
name,
truncateForLog(value));
@@ -238,16 +240,14 @@ public class OfficeDocumentSanitizer {
Element element = (Element) node;
for (String attrName : hrefAttrsToRemove) {
element.removeAttribute(attrName);
- modified = true;
+ stripped++;
}
}
NodeList children = node.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
- if (stripExternalHrefs(children.item(i))) {
- modified = true;
- }
+ stripped += stripExternalHrefs(children.item(i));
}
- return modified;
+ return stripped;
}
private boolean isExternalUrl(String url) {
diff --git a/app/common/src/main/java/stirling/software/common/util/XmpUtils.java b/app/common/src/main/java/stirling/software/common/util/XmpUtils.java
new file mode 100644
index 0000000000..db9adf7e5f
--- /dev/null
+++ b/app/common/src/main/java/stirling/software/common/util/XmpUtils.java
@@ -0,0 +1,41 @@
+package stirling.software.common.util;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+
+import org.apache.pdfbox.pdmodel.common.PDMetadata;
+import org.apache.xmpbox.XMPMetadata;
+import org.apache.xmpbox.xml.DomXmpParser;
+import org.apache.xmpbox.xml.XmpParsingException;
+
+import lombok.experimental.UtilityClass;
+
+/**
+ * Parses a document's own XMP packet with a size limit. xmpbox inserts every array item with a
+ * linear scan, so parse time grows with the square of an array's length.
+ */
+@UtilityClass
+public class XmpUtils {
+
+ public static final int MAX_XMP_BYTES = 1024 * 1024;
+
+ /**
+ * Parses the XMP packet of {@code metadata} with a {@link #MAX_XMP_BYTES}-byte limit.
+ *
+ * @throws IOException if the packet is larger than {@link #MAX_XMP_BYTES} or cannot be read
+ */
+ public XMPMetadata parse(PDMetadata metadata, boolean strict)
+ throws IOException, XmpParsingException {
+ byte[] packet;
+ try (InputStream in = metadata.createInputStream()) {
+ packet = in.readNBytes(MAX_XMP_BYTES + 1);
+ }
+ if (packet.length > MAX_XMP_BYTES) {
+ throw new IOException("XMP packet is larger than " + MAX_XMP_BYTES + " bytes");
+ }
+ DomXmpParser parser = new DomXmpParser();
+ parser.setStrictParsing(strict);
+ return parser.parse(new ByteArrayInputStream(packet));
+ }
+}
diff --git a/app/common/src/test/java/stirling/software/common/util/OfficeDocumentSanitizerTest.java b/app/common/src/test/java/stirling/software/common/util/OfficeDocumentSanitizerTest.java
index 246a279d6f..af848b6b44 100644
--- a/app/common/src/test/java/stirling/software/common/util/OfficeDocumentSanitizerTest.java
+++ b/app/common/src/test/java/stirling/software/common/util/OfficeDocumentSanitizerTest.java
@@ -1,6 +1,7 @@
package stirling.software.common.util;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -21,10 +22,16 @@ import java.util.zip.ZipOutputStream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import org.slf4j.LoggerFactory;
import stirling.software.common.model.ApplicationProperties;
import stirling.software.common.service.SsrfProtectionService;
+import ch.qos.logback.classic.Level;
+import ch.qos.logback.classic.Logger;
+import ch.qos.logback.classic.spi.ILoggingEvent;
+import ch.qos.logback.core.read.ListAppender;
+
class OfficeDocumentSanitizerTest {
private static final String EXTERNAL_URL = "https://webhook.site/ssrf-callback";
@@ -174,6 +181,41 @@ class OfficeDocumentSanitizerTest {
assertTrue(content.contains("Pictures/image1.png"), "Internal href should be preserved");
}
+ @Test
+ void sanitize_logsOneSummaryPerPartNotOneLinePerHref() throws IOException {
+ StringBuilder content =
+ new StringBuilder(
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ + "<office:document-content"
+ + " xmlns:office=\"urn:oasis:names:tc:opendocument:xmlns:office:1.0\""
+ + " xmlns:xlink=\"http://www.w3.org/1999/xlink\">");
+ for (int i = 0; i < 1_000; i++) {
+ content.append("<a xlink:href=\"").append(EXTERNAL_URL).append("\"/>");
+ }
+ content.append("</office:document-content>");
+ Map<String, byte[]> entries = new LinkedHashMap<>();
+ entries.put("content.xml", content.toString().getBytes(StandardCharsets.UTF_8));
+
+ Logger logger = (Logger) LoggerFactory.getLogger(OfficeDocumentSanitizer.class);
+ Level previousLevel = logger.getLevel();
+ logger.setLevel(Level.INFO);
+ ListAppender<ILoggingEvent> appender = new ListAppender<>();
+ appender.start();
+ logger.addAppender(appender);
+ try {
+ byte[] cleaned = sanitizer.sanitize(zip(entries), "odt");
+
+ String result = new String(unzip(cleaned).get("content.xml"), StandardCharsets.UTF_8);
+ assertFalse(result.contains(EXTERNAL_URL));
+ assertEquals(1, appender.list.size(), () -> appender.list.toString());
+ assertTrue(appender.list.get(0).getFormattedMessage().contains("1000"));
+ } finally {
+ logger.detachAppender(appender);
+ appender.stop();
+ logger.setLevel(previousLevel);
+ }
+ }
+
@Test
void sanitize_odsStripsExternalXlinkHref() throws IOException {
Map<String, byte[]> entries = new LinkedHashMap<>();
diff --git a/app/common/src/test/java/stirling/software/common/util/XmpUtilsTest.java b/app/common/src/test/java/stirling/software/common/util/XmpUtilsTest.java
new file mode 100644
index 0000000000..0eb42c51a1
--- /dev/null
+++ b/app/common/src/test/java/stirling/software/common/util/XmpUtilsTest.java
@@ -0,0 +1,50 @@
+package stirling.software.common.util;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+
+import org.apache.pdfbox.pdmodel.PDDocument;
+import org.apache.pdfbox.pdmodel.common.PDMetadata;
+import org.apache.xmpbox.XMPMetadata;
+import org.apache.xmpbox.xml.XmpSerializer;
+import org.junit.jupiter.api.Test;
+
+class XmpUtilsTest {
+
+ @Test
+ void parsesAPacketUnderTheLimit() throws Exception {
+ XMPMetadata source = XMPMetadata.createXMPMetadata();
+ source.createAndAddDublinCoreSchema().setTitle("Report");
+ ByteArrayOutputStream packet = new ByteArrayOutputStream();
+ new XmpSerializer().serialize(source, packet, true);
+
+ try (PDDocument document = new PDDocument()) {
+ PDMetadata metadata = new PDMetadata(document);
+ metadata.importXMPMetadata(packet.toByteArray());
+
+ XMPMetadata parsed = XmpUtils.parse(metadata, false);
+
+ assertThat(parsed.getDublinCoreSchema().getTitle()).isEqualTo("Report");
+ }
+ }
+
+ @Test
+ void refusesAPacketOverTheLimit() throws Exception {
+ byte[] oversized =
+ ("<!--" + "x".repeat(XmpUtils.MAX_XMP_BYTES) + "-->")
+ .getBytes(StandardCharsets.US_ASCII);
+
+ try (PDDocument document = new PDDocument()) {
+ PDMetadata metadata = new PDMetadata(document);
+ metadata.importXMPMetadata(oversized);
+
+ assertThatThrownBy(() -> XmpUtils.parse(metadata, false))
+ .isInstanceOf(IOException.class)
+ .hasMessageContaining(String.valueOf(XmpUtils.MAX_XMP_BYTES));
+ }
+ }
+}
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/MergeController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/MergeController.java
index 1503ecdfe6..9546eb7cd7 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/MergeController.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/MergeController.java
@@ -2,7 +2,6 @@ package stirling.software.SPDF.controller.api;
import java.io.File;
import java.io.IOException;
-import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
@@ -23,7 +22,6 @@ import org.apache.pdfbox.pdmodel.interactive.form.PDField;
import org.apache.pdfbox.pdmodel.interactive.form.PDSignatureField;
import org.apache.xmpbox.XMPMetadata;
import org.apache.xmpbox.schema.XMPBasicSchema;
-import org.apache.xmpbox.xml.DomXmpParser;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
@@ -52,6 +50,7 @@ import stirling.software.common.util.PdfUtils;
import stirling.software.common.util.TempFile;
import stirling.software.common.util.TempFileManager;
import stirling.software.common.util.WebResponseUtils;
+import stirling.software.common.util.XmpUtils;
import stirling.software.jpdfium.PdfDocument;
import stirling.software.jpdfium.PdfMerge;
import stirling.software.jpdfium.doc.Bookmark;
@@ -195,9 +194,8 @@ public class MergeController {
PDMetadata metadata = doc.getDocumentCatalog().getMetadata();
if (metadata != null) {
- try (InputStream is = metadata.createInputStream()) {
- DomXmpParser parser = new DomXmpParser();
- XMPMetadata xmp = parser.parse(is);
+ try {
+ XMPMetadata xmp = XmpUtils.parse(metadata, true);
XMPBasicSchema basic = xmp.getXMPBasicSchema();
if (basic != null) {
if (basic.getModifyDate() != null) {
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 fa55f89304..ea29dffa7a 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
@@ -22,6 +22,7 @@ import org.apache.pdfbox.cos.COSArray;
import org.apache.pdfbox.cos.COSBase;
import org.apache.pdfbox.cos.COSDictionary;
import org.apache.pdfbox.cos.COSName;
+import org.apache.pdfbox.cos.COSObject;
import org.apache.pdfbox.cos.COSStream;
import org.apache.pdfbox.io.RandomAccessRead;
import org.apache.pdfbox.io.RandomAccessReadBufferedFile;
@@ -70,7 +71,7 @@ import org.apache.xmpbox.schema.AdobePDFSchema;
import org.apache.xmpbox.schema.DublinCoreSchema;
import org.apache.xmpbox.schema.PDFAIdentificationSchema;
import org.apache.xmpbox.schema.XMPBasicSchema;
-import org.apache.xmpbox.xml.DomXmpParser;
+import org.apache.xmpbox.type.ArrayProperty;
import org.apache.xmpbox.xml.XmpSerializer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
@@ -92,6 +93,7 @@ import stirling.software.common.annotations.AutoJobPostMapping;
import stirling.software.common.annotations.api.ConvertApi;
import stirling.software.common.configuration.RuntimePathConfig;
import stirling.software.common.enumeration.ResourceWeight;
+import stirling.software.common.model.ApplicationProperties;
import stirling.software.common.model.tool.ToolFormat;
import stirling.software.common.model.tool.ToolIO;
import stirling.software.common.service.PdfaLevelAServiceInterface;
@@ -101,6 +103,7 @@ import stirling.software.common.util.ProcessExecutor.ProcessExecutorResult;
import stirling.software.common.util.TempFile;
import stirling.software.common.util.TempFileManager;
import stirling.software.common.util.WebResponseUtils;
+import stirling.software.common.util.XmpUtils;
@ConvertApi
@Slf4j
@@ -112,16 +115,20 @@ public class ConvertPDFToPDFA {
// Level A needs the proprietary tagger; core builds convert at level B instead.
private final PdfaLevelAServiceInterface pdfaLevelAService;
private final TempFileManager tempFileManager;
+ // The sanitizer adds content streams to every page, all held in memory until the save
+ private final int maxConversionPages;
public ConvertPDFToPDFA(
RuntimePathConfig runtimePathConfig,
stirling.software.SPDF.service.VeraPDFService veraPDFService,
@Autowired(required = false) PdfaLevelAServiceInterface pdfaLevelAService,
- TempFileManager tempFileManager) {
+ TempFileManager tempFileManager,
+ ApplicationProperties applicationProperties) {
this.runtimePathConfig = runtimePathConfig;
this.veraPDFService = veraPDFService;
this.pdfaLevelAService = pdfaLevelAService;
this.tempFileManager = tempFileManager;
+ this.maxConversionPages = applicationProperties.getSystem().getMaxPdfaConversionPages();
}
private static final String ICC_RESOURCE_PATH = "/icc/sRGB2014.icc";
@@ -1280,89 +1287,20 @@ public class ConvertPDFToPDFA {
return false;
}
- private static File preProcessHighlights(File inputPdf) throws Exception {
+ private static File preProcessHighlights(File inputPdf, int maxPages) throws Exception {
try (PDDocument document = Loader.loadPDF(inputPdf)) {
-
- for (PDPage page : document.getPages()) {
- List<PDAnnotation> annotations = page.getAnnotations();
- for (PDAnnotation annot : annotations) {
- if (ANNOTATION_HIGHLIGHT.equals(annot.getSubtype())
- && annot instanceof PDAnnotationHighlight highlight) {
- float[] colorComponents =
- highlight.getColor() != null
- ? highlight.getColor().getComponents()
- : new float[] {1f, 1f, 0f};
- Color highlightColor =
- new Color(
- colorComponents[0], colorComponents[1], colorComponents[2]);
-
- float[] quadPoints = highlight.getQuadPoints();
- if (quadPoints != null) {
- try (PDPageContentStream cs =
- new PDPageContentStream(
- document,
- page,
- PDPageContentStream.AppendMode.PREPEND,
- true,
- true)) {
-
- cs.setStrokingColor(highlightColor);
- cs.setLineWidth(0.05f);
- float spacing = 2f;
- for (int i = 0; i < quadPoints.length; i += 8) {
- float minX =
- Math.min(
- Math.min(quadPoints[i], quadPoints[i + 2]),
- Math.min(quadPoints[i + 4], quadPoints[i + 6]));
- float maxX =
- Math.max(
- Math.max(quadPoints[i], quadPoints[i + 2]),
- Math.max(quadPoints[i + 4], quadPoints[i + 6]));
- float minY =
- Math.min(
- Math.min(quadPoints[i + 1], quadPoints[i + 3]),
- Math.min(quadPoints[i + 5], quadPoints[i + 7]));
- float maxY =
- Math.max(
- Math.max(quadPoints[i + 1], quadPoints[i + 3]),
- Math.max(quadPoints[i + 5], quadPoints[i + 7]));
-
- float width = maxX - minX;
- float height = maxY - minY;
-
- for (float y = minY; y <= maxY; y += spacing) {
- float len = Math.min(width, maxY - y);
- cs.moveTo(minX, y);
- cs.lineTo(minX + len, y + len);
- }
- for (float x = minX + spacing; x <= maxX; x += spacing) {
- float len = Math.min(maxX - x, height);
- cs.moveTo(x, minY);
- cs.lineTo(x + len, minY + len);
- }
- }
-
- cs.stroke();
- }
- }
-
- page.getAnnotations().remove(highlight);
- COSDictionary pageDict = page.getCOSObject();
-
- if (pageDict.containsKey(COSName.GROUP)) {
- COSDictionary groupDict =
- (COSDictionary) pageDict.getDictionaryObject(COSName.GROUP);
-
- if (groupDict != null
- && COSName.TRANSPARENCY
- .getName()
- .equalsIgnoreCase(
- groupDict.getNameAsString(COSName.S))) {
- pageDict.removeItem(COSName.GROUP);
- }
- }
- }
+ requireSanitizablePageCount(document, maxPages);
+
+ // PDF/A-1 cannot keep a highlight without an appearance, so drop the ones we cannot
+ // draw
+ for (PDPage page : flattenHighlights(document, true)) {
+ COSDictionary pageDict = page.getCOSObject();
+ if (pageDict.getDictionaryObject(COSName.GROUP) instanceof COSDictionary groupDict
+ && COSName.TRANSPARENCY
+ .getName()
+ .equalsIgnoreCase(groupDict.getNameAsString(COSName.S))) {
+ pageDict.removeItem(COSName.GROUP);
}
}
// Save the modified document to a temporary file.
@@ -1451,11 +1389,10 @@ public class ConvertPDFToPDFA {
XMPMetadata xmp;
if (existingMetadata != null) {
- try (InputStream xmpStream = existingMetadata.createInputStream()) {
- DomXmpParser parser = new DomXmpParser();
- parser.setStrictParsing(false);
- xmp = parser.parse(xmpStream);
+ try {
+ xmp = XmpUtils.parse(existingMetadata, false);
} catch (Exception e) {
+ log.debug("Replacing the document's XMP packet: {}", e.getMessage());
xmp = XMPMetadata.createXMPMetadata();
}
} else {
@@ -1472,11 +1409,9 @@ public class ConvertPDFToPDFA {
DublinCoreSchema dcSchema = xmp.getDublinCoreSchema();
if (dcSchema != null) {
- List<String> existingCreators = dcSchema.getCreators();
+ ArrayProperty existingCreators = dcSchema.getCreatorsProperty();
if (existingCreators != null) {
- for (String creator : new ArrayList<>(existingCreators)) {
- dcSchema.removeCreator(creator);
- }
+ dcSchema.removeProperty(existingCreators);
}
} else {
dcSchema = xmp.createAndAddDublinCoreSchema();
@@ -1775,12 +1710,13 @@ public class ConvertPDFToPDFA {
if (pdfaPart == 2 || pdfaPart == 3) {
preProcessedFile = tempInputFile.toFile();
} else {
- preProcessedFile = preProcessHighlights(tempInputFile.toFile());
+ preProcessedFile = preProcessHighlights(tempInputFile.toFile(), maxConversionPages);
}
Set<String> missingFonts;
boolean needImgs;
try (PDDocument doc = Loader.loadPDF(preProcessedFile)) {
+ requireSanitizablePageCount(doc, maxConversionPages);
missingFonts = findUnembeddedFontNames(doc);
needImgs = (pdfaPart == 1) && hasTransparentImages(doc);
if (!missingFonts.isEmpty() || needImgs) {
@@ -2063,8 +1999,10 @@ public class ConvertPDFToPDFA {
private void sanitizeDocument(Path inputPath, Path outputPath, boolean addWhiteBackground)
throws IOException {
try (PDDocument doc = Loader.loadPDF(inputPath.toFile())) {
+ requireSanitizablePageCount(doc, maxConversionPages);
Map<String, DocumentSanitizer> sanitizers = new LinkedHashMap<>();
- sanitizers.put("Flatten highlight annotations", this::flattenHighlightsToContent);
+ sanitizers.put(
+ "Flatten highlight annotations", ConvertPDFToPDFA::flattenHighlightsToContent);
sanitizers.put("Sanitize font resources", ConvertPDFToPDFA::sanitizeFontResources);
sanitizers.put("Clean metadata", this::sanitizeMetadata);
sanitizers.put("Remove forbidden actions", this::removeForbiddenActions);
@@ -2262,12 +2200,120 @@ public class ConvertPDFToPDFA {
}
}
- private void addWhiteBackground(PDDocument doc) throws IOException {
+ private static void requireSanitizablePageCount(PDDocument doc, int maxPages) {
+ if (maxPages <= 0) {
+ return;
+ }
+ if (hasMorePagesThan(doc, maxPages)) {
+ throw ExceptionUtils.createIllegalArgumentException(
+ "error.invalidArgument",
+ "Invalid argument: {0}",
+ "PDF/A and PDF/X conversion is limited to "
+ + maxPages
+ + " pages, split the document first");
+ }
+ }
+
+ /**
+ * Counts pages the way {@code doc.getPages()} lists them, visiting each intermediate node once,
+ * and stops at the first page over {@code maxPages}. getNumberOfPages() is only the /Count the
+ * file declares, and the PDFBox iterator resolves the whole tree before returning a page.
+ */
+ private static boolean hasMorePagesThan(PDDocument doc, int maxPages) {
+ COSDictionary root =
+ doc.getDocumentCatalog().getCOSObject().getCOSDictionary(COSName.PAGES);
+ if (root == null) {
+ return false;
+ }
+ Set<COSDictionary> visitedNodes = Collections.newSetFromMap(new IdentityHashMap<>());
+ Deque<Iterator<COSBase>> pending = new ArrayDeque<>();
+ pending.push(kidsOf(root));
+ int pages = 0;
+ while (!pending.isEmpty()) {
+ Iterator<COSBase> kids = pending.peek();
+ if (!kids.hasNext()) {
+ pending.pop();
+ continue;
+ }
+ COSBase kid = kids.next();
+ if (kid instanceof COSObject indirect) {
+ kid = indirect.getObject();
+ }
+ if (!(kid instanceof COSDictionary node)) {
+ continue;
+ }
+ if (COSName.PAGES.equals(node.getCOSName(COSName.TYPE))
+ || node.containsKey(COSName.KIDS)) {
+ if (visitedNodes.add(node)) {
+ pending.push(kidsOf(node));
+ }
+ } else if (++pages > maxPages) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private static Iterator<COSBase> kidsOf(COSDictionary node) {
+ COSArray kids = node.getCOSArray(COSName.KIDS);
+ return kids == null ? Collections.emptyIterator() : kids.iterator();
+ }
+
+ /** The page tree can list one page object many times; each step should touch it once. */
+ private static List<PDPage> distinctPages(PDDocument doc) {
+ Set<COSDictionary> seen = Collections.newSetFromMap(new IdentityHashMap<>());
+ List<PDPage> pages = new ArrayList<>();
for (PDPage page : doc.getPages()) {
+ if (seen.add(page.getCOSObject())) {
+ pages.add(page);
+ }
+ }
+ return pages;
+ }
+
+ /**
+ * Rebuilds /Annots without the given annotations in one pass. Removing them through {@code
+ * page.getAnnotations()} rescans the whole array for every item.
+ */
+ private static void removeAnnotations(PDPage page, Collection<PDAnnotation> toRemove) {
+ if (toRemove.isEmpty()) {
+ return;
+ }
+ COSArray annots = page.getCOSObject().getCOSArray(COSName.ANNOTS);
+ if (annots == null) {
+ return;
+ }
+ Set<COSBase> removed = Collections.newSetFromMap(new IdentityHashMap<>());
+ for (PDAnnotation annot : toRemove) {
+ removed.add(annot.getCOSObject());
+ }
+ COSArray kept = new COSArray();
+ for (int i = 0; i < annots.size(); i++) {
+ if (!removed.contains(annots.getObject(i))) {
+ kept.add(annots.get(i));
+ }
+ }
+ page.getCOSObject().setItem(COSName.ANNOTS, kept);
+ }
+
+ private static String truncateForLog(String value) {
+ if (value == null) {
+ return "null";
+ }
+ boolean truncated = value.length() > 64;
+ String head = truncated ? value.substring(0, 64) : value;
+ String printable = NON_PRINTABLE_ASCII.matcher(head).replaceAll("?");
+ return truncated ? printable + "..." : printable;
+ }
+
+ private void addWhiteBackground(PDDocument doc) throws IOException {
+ for (PDPage page : distinctPages(doc)) {
PDRectangle mediaBox = page.getMediaBox();
try (PDPageContentStream cs =
new PDPageContentStream(
doc, page, PDPageContentStream.AppendMode.PREPEND, true, true)) {
+ // Without the restore, page text that relies on the default fill is drawn white
+ cs.saveGraphicsState();
cs.setNonStrokingColor(Color.WHITE);
cs.addRect(
mediaBox.getLowerLeftX(),
@@ -2275,68 +2321,106 @@ public class ConvertPDFToPDFA {
mediaBox.getWidth(),
mediaBox.getHeight());
cs.fill();
+ cs.restoreGraphicsState();
}
}
}
- private void flattenHighlightsToContent(PDDocument doc) throws IOException {
- for (PDPage page : doc.getPages()) {
- List<PDAnnotation> annotations = new ArrayList<>(page.getAnnotations());
+ /**
+ * Draws each highlight's quads as filled rectangles under the page content and removes the
+ * annotation. Returns the pages that had one.
+ */
+ private static List<PDPage> flattenHighlightsToContent(PDDocument doc) throws IOException {
+ return flattenHighlights(doc, false);
+ }
+
+ /**
+ * With {@code dropUndrawable}, highlights whose quad points are missing or malformed are
+ * removed without drawing; otherwise they are left on the page.
+ */
+ private static List<PDPage> flattenHighlights(PDDocument doc, boolean dropUndrawable)
+ throws IOException {
+ List<PDPage> changedPages = new ArrayList<>();
+ int invalidQuads = 0;
+ for (PDPage page : distinctPages(doc)) {
+ List<PDAnnotation> highlights = new ArrayList<>();
List<PDAnnotation> toRemove = new ArrayList<>();
+ for (PDAnnotation annot : page.getAnnotations()) {
+ if (annot instanceof PDAnnotationHighlight highlight
+ && ANNOTATION_HIGHLIGHT.equals(annot.getSubtype())) {
+ if (isValidQuadPoints(highlight.getQuadPoints())) {
+ highlights.add(highlight);
+ toRemove.add(highlight);
+ } else {
+ invalidQuads++;
+ if (dropUndrawable) {
+ toRemove.add(highlight);
+ }
+ }
+ }
+ }
+ if (toRemove.isEmpty()) {
+ continue;
+ }
+ if (highlights.isEmpty()) {
+ removeAnnotations(page, toRemove);
+ changedPages.add(page);
+ continue;
+ }
try (PDPageContentStream cs =
new PDPageContentStream(
doc, page, PDPageContentStream.AppendMode.PREPEND, true, true)) {
+ // A prepended stream's state carries into the page content, so restore the fill
+ cs.saveGraphicsState();
+ for (PDAnnotation annot : highlights) {
+ PDAnnotationHighlight highlight = (PDAnnotationHighlight) annot;
+ PDColor color = highlight.getColor();
+ if (color != null) {
+ cs.setNonStrokingColor(color);
+ } else {
+ cs.setNonStrokingColor(Color.YELLOW);
+ }
+ fillQuads(cs, highlight.getQuadPoints());
+ }
+ cs.restoreGraphicsState();
+ }
+ removeAnnotations(page, toRemove);
+ changedPages.add(page);
+ }
+ if (invalidQuads > 0) {
+ log.warn(
+ "{} {} highlight annotation(s) with an invalid quad points array",
+ dropUndrawable ? "Removed" : "Skipped",
+ invalidQuads);
+ }
+ return changedPages;
+ }
- for (PDAnnotation annot : annotations) {
- if (annot instanceof PDAnnotationHighlight highlight
- && ANNOTATION_HIGHLIGHT.equals(annot.getSubtype())) {
-
- PDColor color = highlight.getColor();
- if (color != null) {
- cs.setNonStrokingColor(color);
- } else {
- cs.setNonStrokingColor(Color.YELLOW);
- }
-
- float[] quads = highlight.getQuadPoints();
- if (!isValidQuadPoints(quads)) {
- log.warn(
- "Invalid quad points array for highlight annotation: {}",
- quads != null ? "length=" + quads.length : "null");
- continue;
- }
+ private static void fillQuads(PDPageContentStream cs, float[] quads) throws IOException {
+ for (int i = 0; i <= quads.length - 8; i += 8) {
+ float minX = Float.MAX_VALUE, minY = Float.MAX_VALUE;
+ float maxX = -Float.MAX_VALUE, maxY = -Float.MAX_VALUE;
- for (int i = 0; i <= quads.length - 8; i += 8) {
- float minX = Float.MAX_VALUE, minY = Float.MAX_VALUE;
- float maxX = -Float.MAX_VALUE, maxY = -Float.MAX_VALUE;
-
- for (int j = 0; j < 8; j += 2) {
- float x = quads[i + j];
- float y = quads[i + j + 1];
- minX = Math.min(minX, x);
- maxX = Math.max(maxX, x);
- minY = Math.min(minY, y);
- maxY = Math.max(maxY, y);
- }
+ for (int j = 0; j < 8; j += 2) {
+ float x = quads[i + j];
+ float y = quads[i + j + 1];
+ minX = Math.min(minX, x);
+ maxX = Math.max(maxX, x);
+ minY = Math.min(minY, y);
+ maxY = Math.max(maxY, y);
+ }
- // Only draw if we have a valid rectangle
- float width = maxX - minX;
- float height = maxY - minY;
- if (width > 0 && height > 0) {
- cs.addRect(minX, minY, width, height);
- cs.fill();
- }
- }
- toRemove.add(annot);
- }
- }
+ float width = maxX - minX;
+ float height = maxY - minY;
+ if (width > 0 && height > 0) {
+ cs.addRect(minX, minY, width, height);
+ cs.fill();
}
- page.getAnnotations().removeAll(toRemove);
}
}
- private boolean isValidQuadPoints(float[] quads) {
+ private static boolean isValidQuadPoints(float[] quads) {
return quads != null && quads.length >= 8 && quads.length % 8 == 0;
}
@@ -2368,7 +2452,8 @@ public class ConvertPDFToPDFA {
}
private void ensureAnnotationAppearances(PDDocument doc) throws IOException {
- for (PDPage page : doc.getPages()) {
+ int removedCount = 0;
+ for (PDPage page : distinctPages(doc)) {
List<PDAnnotation> annotations = page.getAnnotations();
List<PDAnnotation> toRemove = new ArrayList<>();
@@ -2387,15 +2472,19 @@ public class ConvertPDFToPDFA {
PDAppearanceDictionary appearanceDict = annot.getAppearance();
if (appearanceDict == null || appearanceDict.getNormalAppearance() == null) {
if (!tryGenerateAppearance(doc, page, annot)) {
- log.warn("Removing annotation without appearance: {} on page", subtype);
+ log.debug(
+ "Removing annotation without appearance: {}",
+ truncateForLog(subtype));
toRemove.add(annot);
}
}
}
- if (!toRemove.isEmpty()) {
- annotations.removeAll(toRemove);
- }
+ removeAnnotations(page, toRemove);
+ removedCount += toRemove.size();
+ }
+ if (removedCount > 0) {
+ log.warn("Removed {} annotation(s) without an appearance stream", removedCount);
}
}
@@ -2445,6 +2534,11 @@ public class ConvertPDFToPDFA {
}
}
+ Set<COSBase> inAf = Collections.newSetFromMap(new IdentityHashMap<>());
+ for (int i = 0; i < afArray.size(); i++) {
+ inAf.add(afArray.getObject(i));
+ }
+
boolean afArrayModified = false;
for (Map.Entry<String, PDComplexFileSpecification> entry : fileSpecs.entrySet()) {
@@ -2466,15 +2560,7 @@ public class ConvertPDFToPDFA {
ensureEmbeddedFileMimeType(fileSpec, fileName);
- boolean alreadyInAf = false;
- for (int i = 0; i < afArray.size(); i++) {
- if (afArray.getObject(i) == fileSpecDict) {
- alreadyInAf = true;
- break;
- }
- }
-
- if (!alreadyInAf) {
+ if (inAf.add(fileSpecDict)) {
afArray.add(fileSpecDict);
afArrayModified = true;
}
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/security/GetInfoOnPDF.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/security/GetInfoOnPDF.java
index e23d543817..0951bdb84f 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/security/GetInfoOnPDF.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/security/GetInfoOnPDF.java
@@ -39,7 +39,6 @@ import org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm;
import org.apache.pdfbox.pdmodel.interactive.form.PDField;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.xmpbox.XMPMetadata;
-import org.apache.xmpbox.xml.DomXmpParser;
import org.apache.xmpbox.xml.XmpParsingException;
import org.apache.xmpbox.xml.XmpSerializer;
import org.springframework.http.MediaType;
@@ -63,6 +62,7 @@ import stirling.software.common.model.tool.ToolIO;
import stirling.software.common.service.CustomPDFDocumentFactory;
import stirling.software.common.util.RegexPatternUtils;
import stirling.software.common.util.WebResponseUtils;
+import stirling.software.common.util.XmpUtils;
import tools.jackson.databind.ObjectMapper;
import tools.jackson.databind.json.JsonMapper;
@@ -755,15 +755,12 @@ public class GetInfoOnPDF {
PDMetadata pdMetadata = document.getDocumentCatalog().getMetadata();
if (pdMetadata != null) {
try {
- try (COSInputStream inputStream = pdMetadata.createInputStream()) {
- DomXmpParser domXmpParser = new DomXmpParser();
- XMPMetadata xmpMeta = domXmpParser.parse(inputStream);
+ XMPMetadata xmpMeta = XmpUtils.parse(pdMetadata, true);
- ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
- new XmpSerializer().serialize(xmpMeta, outputStream, true);
- xmpString = outputStream.toString(StandardCharsets.UTF_8);
- }
- } catch (XmpParsingException e) {
+ ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
+ new XmpSerializer().serialize(xmpMeta, outputStream, true);
+ xmpString = outputStream.toString(StandardCharsets.UTF_8);
+ } catch (XmpParsingException | IOException e) {
log.debug("XMP parsing failed, reading raw metadata: {}", e.getMessage());
try (COSInputStream inputStream = pdMetadata.createInputStream()) {
byte[] metadataBytes = inputStream.readAllBytes();
diff --git a/app/core/src/main/resources/settings.yml.template b/app/core/src/main/resources/settings.yml.template
index 64f5c29c3d..fb715bd1fe 100644
--- a/app/core/src/main/resources/settings.yml.template
+++ b/app/core/src/main/resources/settings.yml.template
@@ -189,6 +189,7 @@ system:
disableSanitize: false # set to true to disable Sanitize HTML; (can lead to injections in HTML)
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)
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/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToPDFAGapTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToPDFAGapTest.java
index ea693ddd27..5a11a73f73 100644
--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToPDFAGapTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToPDFAGapTest.java
@@ -4,30 +4,43 @@ import static org.assertj.core.api.Assertions.*;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
+import java.awt.image.BufferedImage;
+import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.file.Files;
import java.nio.file.Path;
+import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
+import java.util.Map;
import java.util.Set;
+import java.util.concurrent.atomic.AtomicBoolean;
+import org.apache.pdfbox.Loader;
import org.apache.pdfbox.cos.COSArray;
+import org.apache.pdfbox.cos.COSBase;
import org.apache.pdfbox.cos.COSDictionary;
import org.apache.pdfbox.cos.COSName;
+import org.apache.pdfbox.cos.COSObject;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentCatalog;
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
+import org.apache.pdfbox.pdmodel.PDDocumentNameDictionary;
+import org.apache.pdfbox.pdmodel.PDEmbeddedFilesNameTreeNode;
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.filespecification.PDComplexFileSpecification;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.pdmodel.font.Standard14Fonts;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation;
+import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationHighlight;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationLink;
+import org.apache.pdfbox.rendering.PDFRenderer;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
@@ -37,6 +50,7 @@ import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
+import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockMultipartFile;
@@ -46,9 +60,15 @@ import stirling.software.SPDF.model.api.converters.PdfToPdfARequest;
import stirling.software.SPDF.model.api.security.PDFVerificationResult;
import stirling.software.SPDF.service.VeraPDFService;
import stirling.software.common.configuration.RuntimePathConfig;
+import stirling.software.common.model.ApplicationProperties;
import stirling.software.common.service.PdfaLevelAServiceInterface;
import stirling.software.common.util.TempFileManager;
+import ch.qos.logback.classic.Level;
+import ch.qos.logback.classic.Logger;
+import ch.qos.logback.classic.spi.ILoggingEvent;
+import ch.qos.logback.core.read.ListAppender;
+
/**
* Gap-filling unit tests for {@link ConvertPDFToPDFA}. Focuses on validation/option/error branches
* and the small pure helpers, mocking the collaborators so that no external binary (ghostscript,
@@ -68,7 +88,11 @@ class ConvertPDFToPDFAGapTest {
private ConvertPDFToPDFA newController() {
return new ConvertPDFToPDFA(
- runtimePathConfig, veraPDFService, pdfaLevelAService, tempFileManager);
+ runtimePathConfig,
+ veraPDFService,
+ pdfaLevelAService,
+ tempFileManager,
+ new ApplicationProperties());
}
// ---- reflection helpers ----------------------------------------------------------------
@@ -106,6 +130,17 @@ class ConvertPDFToPDFAGapTest {
"No method named " + methodName + " with " + argCount + " params");
}
+ private static Object pdfaProfile(String token) throws Exception {
+ for (Class<?> inner : ConvertPDFToPDFA.class.getDeclaredClasses()) {
+ if (inner.getSimpleName().equals("PdfaProfile")) {
+ Method fromRequest = inner.getDeclaredMethod("fromRequest", String.class);
+ fromRequest.setAccessible(true);
+ return fromRequest.invoke(null, token);
+ }
+ }
+ throw new IllegalStateException("PdfaProfile not found");
+ }
+
private static Exception unwrap(InvocationTargetException e) {
Throwable cause = e.getCause();
if (cause instanceof Exception ex) {
@@ -579,6 +614,31 @@ class ConvertPDFToPDFAGapTest {
assertThat(document.getPage(0).hasContents()).isTrue();
}
}
+
+ @Test
+ @DisplayName("page text that uses the default fill stays black")
+ void textStaysBlack() throws Exception {
+ try (PDDocument document = simplePdf()) {
+ invokeInstance(newController(), "addWhiteBackground", document);
+
+ assertThat(darkTextPixels(document)).isPositive();
+ }
+ }
+ }
+
+ /** Dark pixels where {@link #simplePdf()} draws its text, rendered at 72 dpi. */
+ private static int darkTextPixels(PDDocument document) throws IOException {
+ BufferedImage image = new PDFRenderer(document).renderImage(0);
+ int dark = 0;
+ for (int x = 100; x < 170; x++) {
+ for (int y = 132; y < 145; y++) {
+ int rgb = image.getRGB(x, y);
+ if (((rgb >> 16) & 0xff) < 90 && ((rgb >> 8) & 0xff) < 90 && (rgb & 0xff) < 90) {
+ dark++;
+ }
+ }
+ }
+ return dark;
}
// =======================================================================================
@@ -926,4 +986,342 @@ class ConvertPDFToPDFAGapTest {
assertThat((boolean) invokeStatic("isTransparencyGroup", withoutGroup)).isFalse();
}
}
+
+ @Nested
+ @DisplayName("sanitizer bounds")
+ class SanitizerBounds {
+
+ /** Lists the document's only page {@code times} times in the root /Kids array. */
+ private void repeatOnlyPage(PDDocument document, int times) {
+ COSDictionary pages =
+ document.getDocumentCatalog().getCOSObject().getCOSDictionary(COSName.PAGES);
+ COSArray kids = pages.getCOSArray(COSName.KIDS);
+ COSDictionary page = (COSDictionary) kids.getObject(0);
+ for (int i = 1; i < times; i++) {
+ kids.add(page);
+ }
+ pages.setInt(COSName.COUNT, times);
+ }
+
+ private int contentStreamCount(PDPage page) {
+ COSBase contents = page.getCOSObject().getDictionaryObject(COSName.CONTENTS);
+ return contents instanceof COSArray array ? array.size() : 1;
+ }
+
+ private PDAnnotationHighlight highlight(float... quads) {
+ PDAnnotationHighlight highlight = new PDAnnotationHighlight();
+ highlight.setRectangle(new PDRectangle(0, 0, 10, 10));
+ highlight.setQuadPoints(quads);
+ return highlight;
+ }
+
+ @Test
+ @DisplayName("a page listed many times in the page tree gets one white background")
+ void repeatedPageSanitizedOnce() throws Exception {
+ try (PDDocument once = simplePdf();
+ PDDocument repeated = simplePdf()) {
+ repeatOnlyPage(repeated, 50);
+
+ invokeInstance(newController(), "addWhiteBackground", once);
+ invokeInstance(newController(), "addWhiteBackground", repeated);
+
+ assertThat(contentStreamCount(repeated.getPage(0)))
+ .isEqualTo(contentStreamCount(once.getPage(0)));
+ }
+ }
+
+ @Test
+ @DisplayName("more page-tree entries than the limit are refused")
+ void tooManyPagesRefused() throws Exception {
+ try (PDDocument document = simplePdf()) {
+ repeatOnlyPage(document, 20_001);
+
+ assertThatThrownBy(
+ () -> invokeStatic("requireSanitizablePageCount", document, 20_000))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("20000");
+ }
+ }
+
+ @Test
+ @DisplayName("a limit of 0 turns the page check off")
+ void zeroLimitDisablesTheCheck() throws Exception {
+ try (PDDocument document = simplePdf()) {
+ repeatOnlyPage(document, 50);
+
+ assertThatCode(() -> invokeStatic("requireSanitizablePageCount", document, 0))
+ .doesNotThrowAnyException();
+ }
+ }
+
+ @Test
+ @DisplayName("the page check stops at the limit without resolving later page-tree entries")
+ void pageCheckStopsAtTheLimit() throws Exception {
+ try (PDDocument document = simplePdf()) {
+ repeatOnlyPage(document, 6);
+ AtomicBoolean armed = new AtomicBoolean();
+ document.getDocumentCatalog()
+ .getCOSObject()
+ .getCOSDictionary(COSName.PAGES)
+ .getCOSArray(COSName.KIDS)
+ .add(
+ new COSObject(new COSDictionary()) {
+ @Override
+ public COSBase getObject() {
+ if (armed.get()) {
+ throw new AssertionError("resolved past the limit");
+ }
+ return super.getObject();
+ }
+ });
+ armed.set(true);
+
+ assertThatThrownBy(() -> invokeStatic("requireSanitizablePageCount", document, 5))
+ .isInstanceOf(IllegalArgumentException.class);
+ }
+ }
+
+ @Test
+ @DisplayName("pages are counted as the page tree lists them, with shared nodes and cycles")
+ void pageCountMatchesPageTree() throws Exception {
+ try (PDDocument document = simplePdf()) {
+ COSDictionary root =
+ document.getDocumentCatalog()
+ .getCOSObject()
+ .getCOSDictionary(COSName.PAGES);
+ COSArray rootKids = root.getCOSArray(COSName.KIDS);
+ COSDictionary page = (COSDictionary) rootKids.getObject(0);
+ COSArray sharedKids = new COSArray();
+ sharedKids.add(page);
+ sharedKids.add(page);
+ COSDictionary shared = new COSDictionary();
+ shared.setItem(COSName.TYPE, COSName.PAGES);
+ shared.setItem(COSName.KIDS, sharedKids);
+ rootKids.add(shared);
+ rootKids.add(shared);
+ rootKids.add(root);
+
+ int iterated = 0;
+ for (PDPage ignored : document.getPages()) {
+ iterated++;
+ }
+ int listed = iterated;
+
+ assertThatCode(() -> invokeStatic("requireSanitizablePageCount", document, listed))
+ .doesNotThrowAnyException();
+ assertThatThrownBy(
+ () ->
+ invokeStatic(
+ "requireSanitizablePageCount",
+ document,
+ listed - 1))
+ .isInstanceOf(IllegalArgumentException.class);
+ }
+ }
+
+ @Test
+ @DisplayName("the PDF/A-2 fallback refuses documents over the page limit")
+ void fallbackChecksPageLimit() throws Exception {
+ Path input = tempDir.resolve("six-pages.pdf");
+ try (PDDocument document = simplePdf()) {
+ repeatOnlyPage(document, 6);
+ document.save(input.toFile());
+ }
+ ApplicationProperties properties = new ApplicationProperties();
+ properties.getSystem().setMaxPdfaConversionPages(5);
+ ConvertPDFToPDFA controller =
+ new ConvertPDFToPDFA(
+ runtimePathConfig,
+ veraPDFService,
+ pdfaLevelAService,
+ tempFileManager,
+ properties);
+
+ assertThatThrownBy(
+ () ->
+ invokeInstance(
+ controller,
+ "convertWithPdfBoxMethod",
+ input,
+ pdfaProfile("pdfa-2b")))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("5 pages");
+ }
+
+ @Test
+ @DisplayName("the PDF/A-1 fallback removes highlights it cannot draw")
+ void fallbackDropsMalformedHighlights() throws Exception {
+ Path input = tempDir.resolve("bad-quads.pdf");
+ try (PDDocument document = simplePdf()) {
+ PDAnnotationHighlight noQuads = new PDAnnotationHighlight();
+ noQuads.setRectangle(new PDRectangle(0, 0, 10, 10));
+ PDAnnotationLink link = new PDAnnotationLink();
+ link.setRectangle(new PDRectangle(0, 0, 5, 5));
+ document.getPage(0)
+ .setAnnotations(List.of(highlight(0, 0, 10, 10, 0), noQuads, link));
+ document.save(input.toFile());
+ }
+
+ File output = invokeStatic("preProcessHighlights", input.toFile(), 20_000);
+ try (PDDocument result = Loader.loadPDF(output)) {
+ assertThat(result.getPage(0).getAnnotations())
+ .extracting(PDAnnotation::getSubtype)
+ .containsExactly("Link");
+ } finally {
+ Files.deleteIfExists(output.toPath());
+ }
+ }
+
+ @Test
+ @DisplayName("the sanitizer leaves highlights it cannot draw for the appearance check")
+ void sanitizerKeepsMalformedHighlights() throws Exception {
+ try (PDDocument document = simplePdf()) {
+ PDPage page = document.getPage(0);
+ page.setAnnotations(List.of(highlight(0, 0, 10, 10, 0)));
+
+ List<PDPage> flattened = invokeStatic("flattenHighlightsToContent", document);
+
+ assertThat(flattened).isEmpty();
+ assertThat(page.getAnnotations()).hasSize(1);
+ }
+ }
+
+ @Test
+ @DisplayName("pages without highlights get no extra content stream")
+ void noHighlightNoStream() throws Exception {
+ try (PDDocument document = simplePdf()) {
+ int before = contentStreamCount(document.getPage(0));
+
+ List<PDPage> flattened = invokeStatic("flattenHighlightsToContent", document);
+
+ assertThat(flattened).isEmpty();
+ assertThat(contentStreamCount(document.getPage(0))).isEqualTo(before);
+ }
+ }
+
+ @Test
+ @DisplayName("a highlight is drawn inside its own graphics state and removed")
+ void highlightFlattenedAndRemoved() throws Exception {
+ try (PDDocument document = simplePdf()) {
+ PDPage page = document.getPage(0);
+ PDAnnotationLink link = new PDAnnotationLink();
+ link.setRectangle(new PDRectangle(0, 0, 5, 5));
+ page.setAnnotations(List.of(highlight(0, 10, 10, 10, 0, 0, 10, 0), link));
+
+ List<PDPage> flattened = invokeStatic("flattenHighlightsToContent", document);
+
+ assertThat(flattened).hasSize(1);
+ assertThat(page.getAnnotations())
+ .extracting(PDAnnotation::getSubtype)
+ .containsExactly("Link");
+
+ // The highlight colour must not carry into the page text drawn after it
+ assertThat(darkTextPixels(document)).isPositive();
+ }
+ }
+
+ @Test
+ @DisplayName("the PDF/A-1 fallback draws a highlight with huge coordinates in bounded time")
+ void fallbackHugeQuadPoints() throws Exception {
+ Path input = tempDir.resolve("huge-quad.pdf");
+ try (PDDocument document = simplePdf()) {
+ document.getPage(0)
+ .setAnnotations(
+ List.of(
+ highlight(
+ 0,
+ 40_000_010,
+ 10,
+ 40_000_010,
+ 0,
+ 40_000_000,
+ 10,
+ 40_000_000)));
+ document.save(input.toFile());
+ }
+
+ File output =
+ assertTimeoutPreemptively(
+ Duration.ofSeconds(20),
+ () -> invokeStatic("preProcessHighlights", input.toFile(), 20_000));
+ try (PDDocument result = Loader.loadPDF(output)) {
+ assertThat(result.getPage(0).getAnnotations()).isEmpty();
+ } finally {
+ Files.deleteIfExists(output.toPath());
+ }
+ }
+
+ @Test
+ @DisplayName("many annotations without appearance are removed in one pass with one warning")
+ void manyAnnotationsRemovedWithOneWarning() throws Exception {
+ Logger logger = (Logger) LoggerFactory.getLogger(ConvertPDFToPDFA.class);
+ Level previousLevel = logger.getLevel();
+ logger.setLevel(Level.INFO);
+ ListAppender<ILoggingEvent> appender = new ListAppender<>();
+ appender.start();
+ logger.addAppender(appender);
+ try (PDDocument document = simplePdf()) {
+ PDPage page = document.getPage(0);
+ COSArray annots = new COSArray();
+ COSDictionary keptLink = new COSDictionary();
+ keptLink.setName(COSName.SUBTYPE, "Link");
+ annots.add(keptLink);
+ String longSubtype = "A".repeat(10_000) + "\nforged line";
+ for (int i = 0; i < 200_000; i++) {
+ COSDictionary unknown = new COSDictionary();
+ unknown.setName(COSName.SUBTYPE, longSubtype);
+ annots.add(unknown);
+ }
+ page.getCOSObject().setItem(COSName.ANNOTS, annots);
+
+ assertTimeoutPreemptively(
+ Duration.ofSeconds(30),
+ () ->
+ invokeInstance(
+ newController(), "ensureAnnotationAppearances", document));
+
+ COSArray remaining = page.getCOSObject().getCOSArray(COSName.ANNOTS);
+ assertThat(remaining.size()).isEqualTo(1);
+ assertThat(remaining.getObject(0)).isSameAs(keptLink);
+ assertThat(appender.list)
+ .singleElement()
+ .satisfies(
+ e ->
+ assertThat(e.getFormattedMessage())
+ .contains("200000")
+ .hasSizeLessThan(200)
+ .doesNotContain("\n"));
+ } finally {
+ logger.detachAppender(appender);
+ appender.stop();
+ logger.setLevel(previousLevel);
+ }
+ }
+
+ @Test
+ @DisplayName("only file specifications missing from /AF are appended")
+ void embeddedFilesAppendedToAfOnce() throws Exception {
+ try (PDDocument document = simplePdf()) {
+ PDComplexFileSpecification listed = new PDComplexFileSpecification();
+ PDComplexFileSpecification missing = new PDComplexFileSpecification();
+ PDEmbeddedFilesNameTreeNode tree = new PDEmbeddedFilesNameTreeNode();
+ tree.setNames(Map.of("a.txt", listed, "b.txt", missing));
+ PDDocumentNameDictionary names =
+ new PDDocumentNameDictionary(document.getDocumentCatalog());
+ names.setEmbeddedFiles(tree);
+ document.getDocumentCatalog().setNames(names);
+ COSArray af = new COSArray();
+ af.add(listed.getCOSObject());
+ document.getDocumentCatalog().getCOSObject().setItem(COSName.AF, af);
+
+ invokeInstance(newController(), "ensureEmbeddedFileCompliance", document);
+
+ COSArray result =
+ document.getDocumentCatalog().getCOSObject().getCOSArray(COSName.AF);
+ assertThat(result.size()).isEqualTo(2);
+ assertThat(result.getObject(0)).isSameAs(listed.getCOSObject());
+ assertThat(result.getObject(1)).isSameAs(missing.getCOSObject());
+ }
+ }
+ }
}
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToPDFAMoreTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToPDFAMoreTest.java
index 760deb45ca..ecff558184 100644
--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToPDFAMoreTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToPDFAMoreTest.java
@@ -42,6 +42,7 @@ import org.springframework.mock.web.MockMultipartFile;
import stirling.software.SPDF.model.api.converters.PdfToPdfARequest;
import stirling.software.SPDF.service.VeraPDFService;
import stirling.software.common.configuration.RuntimePathConfig;
+import stirling.software.common.model.ApplicationProperties;
import stirling.software.common.service.PdfaLevelAServiceInterface;
import stirling.software.common.util.ExceptionUtils;
import stirling.software.common.util.ProcessExecutor;
@@ -70,7 +71,11 @@ class ConvertPDFToPDFAMoreTest {
private ConvertPDFToPDFA newController() {
return new ConvertPDFToPDFA(
- runtimePathConfig, veraPDFService, pdfaLevelAService, tempFileManager);
+ runtimePathConfig,
+ veraPDFService,
+ pdfaLevelAService,
+ tempFileManager,
+ new ApplicationProperties());
}
private static ResponseEntity<Resource> streamingOk(byte[] bytes) {
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToPDFATest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToPDFATest.java
index 300ccb239a..3e4a42648c 100644
--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToPDFATest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToPDFATest.java
@@ -9,6 +9,7 @@ import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
+import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
@@ -37,6 +38,8 @@ import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.junit.jupiter.MockitoExtension;
+import stirling.software.common.util.XmpUtils;
+
@DisplayName("PDF to PDF/A Converter Tests")
@ExtendWith(MockitoExtension.class)
class ConvertPDFToPDFATest {
@@ -241,6 +244,63 @@ class ConvertPDFToPDFATest {
document.close();
}
+ @Test
+ @DisplayName("Should replace every existing creator with the document's creator")
+ void shouldReplaceExistingCreators() throws Exception {
+ PDDocument document = createSimplePdf();
+ document.getDocumentInformation().setCreator("Original Creator");
+ XMPMetadata existing = XMPMetadata.createXMPMetadata();
+ DublinCoreSchema dc = existing.createAndAddDublinCoreSchema();
+ for (int i = 0; i < 5_000; i++) {
+ dc.addCreator("creator " + i);
+ }
+ ByteArrayOutputStream packet = new ByteArrayOutputStream();
+ new XmpSerializer().serialize(existing, packet, true);
+ PDMetadata metadata = new PDMetadata(document);
+ metadata.importXMPMetadata(packet.toByteArray());
+ document.getDocumentCatalog().setMetadata(metadata);
+
+ invokePrivateMethod("mergeAndAddXmpMetadata", document, 1);
+
+ try (InputStream is = document.getDocumentCatalog().getMetadata().createInputStream()) {
+ XMPMetadata xmp = new DomXmpParser().parse(is);
+ assertThat(xmp.getDublinCoreSchema().getCreators())
+ .containsExactly("Original Creator");
+ }
+
+ document.close();
+ }
+
+ @Test
+ @DisplayName("Should replace an oversized XMP packet instead of parsing it")
+ void shouldReplaceOversizedXmp() throws Exception {
+ PDDocument document = createSimplePdf();
+ String filler = "<!--" + "x".repeat(XmpUtils.MAX_XMP_BYTES) + "-->";
+ PDMetadata metadata = new PDMetadata(document);
+ metadata.importXMPMetadata(
+ ("<?xpacket begin=\"\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>"
+ + filler
+ + "<x:xmpmeta xmlns:x=\"adobe:ns:meta/\"/>"
+ + "<?xpacket end=\"w\"?>")
+ .getBytes(StandardCharsets.UTF_8));
+ document.getDocumentCatalog().setMetadata(metadata);
+
+ invokePrivateMethod("mergeAndAddXmpMetadata", document, 2);
+
+ PDMetadata written = document.getDocumentCatalog().getMetadata();
+ assertThat(written.toByteArray().length).isLessThan(XmpUtils.MAX_XMP_BYTES);
+ try (InputStream is = written.createInputStream()) {
+ PDFAIdentificationSchema pdfaSchema =
+ (PDFAIdentificationSchema)
+ new DomXmpParser()
+ .parse(is)
+ .getSchema(PDFAIdentificationSchema.class);
+ assertThat(pdfaSchema.getPart()).isEqualTo(2);
+ }
+
+ document.close();
+ }
+
@Test
@DisplayName("Should handle existing XMP metadata gracefully")
void shouldHandleExistingXmpMetadata() throws Exception {
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/security/GetInfoOnPDFMoreTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/security/GetInfoOnPDFMoreTest.java
index 1df66f739e..59695ebac4 100644
--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/security/GetInfoOnPDFMoreTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/security/GetInfoOnPDFMoreTest.java
@@ -7,6 +7,7 @@ import static org.mockito.Mockito.when;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
+import java.nio.charset.StandardCharsets;
import java.util.Calendar;
import java.util.GregorianCalendar;
@@ -15,6 +16,7 @@ import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
+import org.apache.pdfbox.pdmodel.common.PDMetadata;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.documentinterchange.logicalstructure.PDStructureTreeRoot;
import org.apache.pdfbox.pdmodel.encryption.AccessPermission;
@@ -47,6 +49,7 @@ import org.springframework.web.multipart.MultipartFile;
import stirling.software.SPDF.service.VeraPDFService;
import stirling.software.common.model.api.PDFFile;
import stirling.software.common.service.CustomPDFDocumentFactory;
+import stirling.software.common.util.XmpUtils;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.ObjectMapper;
@@ -264,6 +267,23 @@ class GetInfoOnPDFMoreTest {
@DisplayName("error handling")
class Errors {
+ @Test
+ @DisplayName("an XMP packet over the parse limit is returned raw")
+ void oversizedXmpReturnedRaw() throws Exception {
+ PDDocument doc = new PDDocument();
+ doc.addPage(new PDPage(PDRectangle.A4));
+ PDMetadata metadata = new PDMetadata(doc);
+ metadata.importXMPMetadata(
+ ("<!--" + "x".repeat(XmpUtils.MAX_XMP_BYTES) + "-->")
+ .getBytes(StandardCharsets.US_ASCII));
+ doc.getDocumentCatalog().setMetadata(metadata);
+
+ JsonNode json = run(doc);
+
+ String xmp = json.path("Other").path("XMPMetadata").asText();
+ assertThat(xmp).startsWith("<!--").hasSizeGreaterThan(XmpUtils.MAX_XMP_BYTES);
+ }
+
@Test
@DisplayName("veraPDF failure is swallowed and a report is still produced")
void veraPdfFailureSwallowed() throws Exception {
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/pdf/ua/PdfUaMetadataWriter.java b/app/proprietary/src/main/java/stirling/software/proprietary/pdf/ua/PdfUaMetadataWriter.java
index 7f58654c87..4a6bebcbb0 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/pdf/ua/PdfUaMetadataWriter.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/pdf/ua/PdfUaMetadataWriter.java
@@ -1,6 +1,5 @@
package stirling.software.proprietary.pdf.ua;
-import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
@@ -18,11 +17,12 @@ import org.apache.pdfbox.pdmodel.interactive.viewerpreferences.PDViewerPreferenc
import org.apache.xmpbox.XMPMetadata;
import org.apache.xmpbox.schema.DublinCoreSchema;
import org.apache.xmpbox.schema.XMPSchema;
-import org.apache.xmpbox.xml.DomXmpParser;
import org.apache.xmpbox.xml.XmpSerializer;
import lombok.extern.slf4j.Slf4j;
+import stirling.software.common.util.XmpUtils;
+
/** Applies the document-level PDF/UA requirements: title, language, tab order, declaration. */
@Slf4j
public class PdfUaMetadataWriter {
@@ -211,10 +211,8 @@ public class PdfUaMetadataWriter {
PDMetadata existing = catalog.getMetadata();
if (existing != null) {
try {
- DomXmpParser parser = new DomXmpParser();
// Strict parsing rejects pdfuaid, silently discarding a packet we just wrote.
- parser.setStrictParsing(false);
- return parser.parse(new ByteArrayInputStream(existing.toByteArray()));
+ return XmpUtils.parse(existing, false);
} catch (Exception e) {
log.debug("Replacing unparseable XMP packet: {}", e.getMessage());
}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/service/ua/PdfaAccessibilityService.java b/app/proprietary/src/main/java/stirling/software/proprietary/service/ua/PdfaAccessibilityService.java
index 5a13b4ab65..2f60756a50 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/service/ua/PdfaAccessibilityService.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/service/ua/PdfaAccessibilityService.java
@@ -1,9 +1,7 @@
package stirling.software.proprietary.service.ua;
-import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
-import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
@@ -19,7 +17,6 @@ import org.apache.xmpbox.type.ArrayProperty;
import org.apache.xmpbox.type.Cardinality;
import org.apache.xmpbox.type.PDFAPropertyType;
import org.apache.xmpbox.type.PDFASchemaType;
-import org.apache.xmpbox.xml.DomXmpParser;
import org.apache.xmpbox.xml.XmpSerializer;
import org.springframework.stereotype.Service;
@@ -27,6 +24,7 @@ import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import stirling.software.common.service.PdfaLevelAServiceInterface;
+import stirling.software.common.util.XmpUtils;
import stirling.software.proprietary.pdf.ua.PdfUaIdentificationSchema;
import stirling.software.proprietary.pdf.ua.PdfUaProfile;
import stirling.software.proprietary.pdf.ua.PdfUaTagger;
@@ -236,11 +234,7 @@ public class PdfaAccessibilityService implements PdfaLevelAServiceInterface {
if (existing == null) {
return XMPMetadata.createXMPMetadata();
}
- try (InputStream in = new ByteArrayInputStream(existing.toByteArray())) {
- DomXmpParser parser = new DomXmpParser();
- parser.setStrictParsing(false);
- return parser.parse(in);
- }
+ return XmpUtils.parse(existing, false);
}
private static void writeMetadata(PDDocument document, XMPMetadata xmp) throws Exception {
@@ -257,11 +251,7 @@ public class PdfaAccessibilityService implements PdfaLevelAServiceInterface {
PDMetadata existing = document.getDocumentCatalog().getMetadata();
XMPMetadata xmp;
if (existing != null) {
- try (InputStream in = new ByteArrayInputStream(existing.toByteArray())) {
- DomXmpParser parser = new DomXmpParser();
- parser.setStrictParsing(false);
- xmp = parser.parse(in);
- }
+ xmp = XmpUtils.parse(existing, false);
} else {
xmp = XMPMetadata.createXMPMetadata();
}