Skip to content

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

Bound logged tool output and the XMP size checked by veraPDF (#8705)

ConnorYoh0b5b7a3df598
diff --git a/app/common/src/main/java/stirling/software/common/util/ProcessExecutor.java b/app/common/src/main/java/stirling/software/common/util/ProcessExecutor.java
index f51fde37bd..acb9fb210e 100644
--- a/app/common/src/main/java/stirling/software/common/util/ProcessExecutor.java
+++ b/app/common/src/main/java/stirling/software/common/util/ProcessExecutor.java
@@ -18,6 +18,8 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.regex.Pattern;
import io.github.pixee.security.BoundedLineReader;
@@ -30,6 +32,11 @@ import stirling.software.common.model.ApplicationProperties;
@Slf4j
public class ProcessExecutor {
+ // A document can make a tool print without end, so each run logs a bounded amount of output
+ static final int MAX_LOGGED_LINES = 200;
+ static final int MAX_LOGGED_LINE_LENGTH = 1_000;
+ private static final Pattern CONTROL_CHARACTERS = Pattern.compile("[\\p{Cntrl}&&[^\\t]]");
+
private static final Map<Processes, ProcessExecutor> instances = new ConcurrentHashMap<>();
private static ApplicationProperties applicationProperties = new ApplicationProperties();
private static volatile UnoServerPool unoServerPool;
@@ -373,6 +380,7 @@ public class ProcessExecutor {
// Read the error stream and standard output stream concurrently
List<String> errorLines = new ArrayList<>();
List<String> outputLines = new ArrayList<>();
+ AtomicInteger offeredLines = new AtomicInteger();
Thread errorReaderThread =
Thread.ofVirtual()
@@ -389,7 +397,7 @@ public class ProcessExecutor {
errorReader, 5_000_000))
!= null) {
errorLines.add(line);
- if (liveUpdates) logLiveLine(line);
+ if (liveUpdates) logLiveLine(line, offeredLines);
}
} catch (InterruptedIOException e) {
log.warn(
@@ -414,7 +422,7 @@ public class ProcessExecutor {
outputReader, 5_000_000))
!= null) {
outputLines.add(line);
- if (liveUpdates) logLiveLine(line);
+ if (liveUpdates) logLiveLine(line, offeredLines);
}
} catch (InterruptedIOException e) {
log.warn(
@@ -477,21 +485,23 @@ public class ProcessExecutor {
// Wait for the reader threads to finish
errorReaderThread.join();
outputReaderThread.join();
+ logUnloggedLiveLines(offeredLines.get());
if (processType == Processes.CALIBRE) {
- return finishCalibreRun(exitCode, outputLines, errorLines);
+ return finishCalibreRun(exitCode, outputLines, errorLines, offeredLines);
}
boolean isQpdf =
commandToRun != null
&& !commandToRun.isEmpty()
&& commandToRun.getFirst().contains("qpdf");
+ boolean qpdfWarnings = isQpdf && exitCode == 3;
if (!outputLines.isEmpty()) {
String outputMessage = String.join("\n", outputLines);
messages += outputMessage;
if (!liveUpdates) {
- log.info("Command output:\n{}", outputMessage);
+ log.info("Command output:\n{}", forLog(outputLines, offeredLines));
}
}
@@ -499,32 +509,28 @@ public class ProcessExecutor {
String errorMessage = String.join("\n", errorLines);
messages += errorMessage;
if (!liveUpdates) {
- log.warn("Command error output:\n{}", errorMessage);
- }
- if (exitCode != 0) {
- if (isQpdf && exitCode == 3) {
- log.warn("qpdf succeeded with warnings: {}", messages);
- } else {
- throw new IOException(
- "Command process failed with exit code "
- + exitCode
- + ". Error message: "
- + errorMessage);
- }
+ log.warn("Command error output:\n{}", forLog(errorLines, offeredLines));
}
- }
-
- if (exitCode != 0) {
- if (isQpdf && exitCode == 3) {
- log.warn("qpdf succeeded with warnings: {}", messages);
- } else {
+ if (exitCode != 0 && !qpdfWarnings) {
throw new IOException(
"Command process failed with exit code "
+ exitCode
- + "\nLogs: "
- + messages);
+ + ". Error message: "
+ + forLog(errorLines));
}
}
+
+ if (qpdfWarnings) {
+ log.warn(
+ "qpdf succeeded with warnings: {}",
+ forLog(allLines(outputLines, errorLines), offeredLines));
+ } else if (exitCode != 0) {
+ throw new IOException(
+ "Command process failed with exit code "
+ + exitCode
+ + "\nLogs: "
+ + forLog(allLines(outputLines, errorLines)));
+ }
} finally {
if (ipcPipesBefore != null) {
LibreOfficeSandboxPolicy.removeLeftoverIpcPipes(
@@ -540,21 +546,82 @@ public class ProcessExecutor {
return new ProcessExecutorResult(exitCode, messages);
}
- private void logLiveLine(String line) {
+ private void logLiveLine(String line, AtomicInteger seen) {
+ if (seen.incrementAndGet() > MAX_LOGGED_LINES) {
+ return;
+ }
+ if (processType == Processes.CALIBRE) {
+ log.debug("{}", forLog(line));
+ } else {
+ log.info("{}", forLog(line));
+ }
+ }
+
+ private void logUnloggedLiveLines(int seen) {
+ int unlogged = seen - MAX_LOGGED_LINES;
+ if (unlogged <= 0) {
+ return;
+ }
if (processType == Processes.CALIBRE) {
- log.debug(line);
+ log.debug("{} more output lines were not logged", unlogged);
} else {
- log.info(line);
+ log.info("{} more output lines were not logged", unlogged);
+ }
+ }
+
+ private static List<String> allLines(List<String> outputLines, List<String> errorLines) {
+ List<String> lines = new ArrayList<>(outputLines);
+ lines.addAll(errorLines);
+ return lines;
+ }
+
+ /** Uses what is left of the run's {@link #MAX_LOGGED_LINES}, counted in {@code offered}. */
+ private static String forLog(List<String> lines, AtomicInteger offered) {
+ int left = MAX_LOGGED_LINES - offered.getAndAdd(lines.size());
+ return forLog(lines, Math.max(left, 0));
+ }
+
+ /** The first {@link #MAX_LOGGED_LINES} lines, each cut short and made printable. */
+ static String forLog(List<String> lines) {
+ return forLog(lines, MAX_LOGGED_LINES);
+ }
+
+ private static String forLog(List<String> lines, int allowance) {
+ StringBuilder text = new StringBuilder();
+ int shown = Math.min(lines.size(), allowance);
+ for (int i = 0; i < shown; i++) {
+ if (i > 0) {
+ text.append('\n');
+ }
+ text.append(forLog(lines.get(i)));
}
+ if (lines.size() > shown) {
+ if (shown > 0) {
+ text.append('\n');
+ }
+ text.append("... ").append(lines.size() - shown).append(" more lines");
+ }
+ return text.toString();
+ }
+
+ static String forLog(String line) {
+ boolean truncated = line.length() > MAX_LOGGED_LINE_LENGTH;
+ String head = truncated ? line.substring(0, MAX_LOGGED_LINE_LENGTH) : line;
+ String printable = CONTROL_CHARACTERS.matcher(head).replaceAll("?");
+ return truncated ? printable + "..." : printable;
}
private ProcessExecutorResult finishCalibreRun(
- int exitCode, List<String> outputLines, List<String> errorLines) throws IOException {
+ int exitCode,
+ List<String> outputLines,
+ List<String> errorLines,
+ AtomicInteger offeredLines)
+ throws IOException {
String output = String.join("\n", outputLines);
String errors = String.join("\n", errorLines);
if (!liveUpdates) {
- log.debug("Calibre output:\n{}", output);
- log.debug("Calibre error output:\n{}", errors);
+ log.debug("Calibre output:\n{}", forLog(outputLines, offeredLines));
+ log.debug("Calibre error output:\n{}", forLog(errorLines, offeredLines));
}
CalibreSandboxPolicy.checkLauncherOutcome(errorLines);
if (exitCode != 0) {
diff --git a/app/common/src/test/java/stirling/software/common/util/ProcessExecutorOutputLogTest.java b/app/common/src/test/java/stirling/software/common/util/ProcessExecutorOutputLogTest.java
new file mode 100644
index 0000000000..f150a11da2
--- /dev/null
+++ b/app/common/src/test/java/stirling/software/common/util/ProcessExecutorOutputLogTest.java
@@ -0,0 +1,207 @@
+package stirling.software.common.util;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.lang.reflect.Field;
+import java.nio.charset.StandardCharsets;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+import java.util.stream.Stream;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.MockedConstruction;
+import org.mockito.Mockito;
+import org.slf4j.LoggerFactory;
+
+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 ProcessExecutorOutputLogTest {
+
+ private static final int PRINTED_LINES = 5_000;
+
+ private final Logger logger = (Logger) LoggerFactory.getLogger(ProcessExecutor.class);
+ private final ListAppender<ILoggingEvent> appender = new ListAppender<>();
+ private final Map<ProcessExecutor.Processes, ProcessExecutor> replaced = new HashMap<>();
+ private Level previousLevel;
+
+ @BeforeEach
+ void captureLog() {
+ previousLevel = logger.getLevel();
+ logger.setLevel(Level.DEBUG);
+ appender.start();
+ logger.addAppender(appender);
+ }
+
+ @AfterEach
+ void releaseLog() {
+ logger.detachAppender(appender);
+ logger.setLevel(previousLevel);
+ }
+
+ private static String lines(int count) {
+ return IntStream.range(0, count)
+ .mapToObj(i -> "line " + i)
+ .collect(Collectors.joining("\n", "", "\n"));
+ }
+
+ /** Stands in for a tool that prints {@code stdout} and {@code stderr} and exits. */
+ private static MockedConstruction<ProcessBuilder> tool(
+ int exitCode, String stdout, String stderr) {
+ return Mockito.mockConstruction(
+ ProcessBuilder.class,
+ (builder, context) -> {
+ Process process = mock(Process.class);
+ when(process.getInputStream())
+ .thenReturn(
+ new ByteArrayInputStream(
+ stdout.getBytes(StandardCharsets.UTF_8)));
+ when(process.getErrorStream())
+ .thenReturn(
+ new ByteArrayInputStream(
+ stderr.getBytes(StandardCharsets.UTF_8)));
+ when(process.waitFor(anyLong(), any(TimeUnit.class))).thenReturn(true);
+ when(process.exitValue()).thenReturn(exitCode);
+ when(process.descendants()).thenAnswer(invocation -> Stream.empty());
+ when(builder.environment()).thenReturn(new HashMap<>());
+ when(builder.start()).thenReturn(process);
+ });
+ }
+
+ private int loggedOutputLines() {
+ return appender.list.stream()
+ .map(ILoggingEvent::getFormattedMessage)
+ .filter(message -> !message.startsWith("Running command"))
+ .mapToInt(message -> message.split("\n", -1).length)
+ .sum();
+ }
+
+ /** How many of the tool's own lines reached the log, wherever they were logged. */
+ private long loggedToolLines() {
+ return appender.list.stream()
+ .map(ILoggingEvent::getFormattedMessage)
+ .flatMap(message -> Stream.of(message.split("\n", -1)))
+ .filter(line -> line.matches("(qpdf succeeded with warnings: )?line \\d+"))
+ .count();
+ }
+
+ private long messagesStartingWith(String prefix) {
+ return appender.list.stream()
+ .map(ILoggingEvent::getFormattedMessage)
+ .filter(message -> message.startsWith(prefix))
+ .count();
+ }
+
+ /** A new executor, because getInstance keeps the first one made for each type. */
+ private ProcessExecutor executor(ProcessExecutor.Processes type, boolean liveUpdates)
+ throws ReflectiveOperationException {
+ ProcessExecutor previous = instances().remove(type);
+ if (!replaced.containsKey(type)) {
+ replaced.put(type, previous);
+ }
+ return ProcessExecutor.getInstance(type, liveUpdates);
+ }
+
+ @AfterEach
+ void restoreExecutors() throws ReflectiveOperationException {
+ Map<ProcessExecutor.Processes, ProcessExecutor> instances = instances();
+ replaced.forEach(
+ (type, previous) -> {
+ instances.remove(type);
+ if (previous != null) {
+ instances.put(type, previous);
+ }
+ });
+ }
+
+ @SuppressWarnings("unchecked")
+ private static Map<ProcessExecutor.Processes, ProcessExecutor> instances()
+ throws ReflectiveOperationException {
+ Field field = ProcessExecutor.class.getDeclaredField("instances");
+ field.setAccessible(true);
+ return (Map<ProcessExecutor.Processes, ProcessExecutor>) field.get(null);
+ }
+
+ @Test
+ void bothStreamsShareTheRunsAllowance() throws Exception {
+ try (MockedConstruction<ProcessBuilder> ignored = tool(0, lines(300), lines(300))) {
+ executor(ProcessExecutor.Processes.GHOSTSCRIPT, false)
+ .runCommandWithOutputHandling(List.of("gs", "-v"));
+ }
+
+ assertThat(loggedToolLines()).isEqualTo(ProcessExecutor.MAX_LOGGED_LINES);
+ }
+
+ @Test
+ void qpdfWarningsAreLoggedOnceWithinTheAllowance() throws Exception {
+ ProcessExecutor.ProcessExecutorResult result;
+ try (MockedConstruction<ProcessBuilder> ignored = tool(3, lines(150), lines(150))) {
+ result =
+ executor(ProcessExecutor.Processes.QPDF, false)
+ .runCommandWithOutputHandling(List.of("qpdf", "--check"));
+ }
+
+ assertThat(result.rc).isEqualTo(3);
+ assertThat(messagesStartingWith("qpdf succeeded with warnings")).isEqualTo(1);
+ assertThat(loggedToolLines()).isEqualTo(ProcessExecutor.MAX_LOGGED_LINES);
+ }
+
+ @Test
+ void longOutputIsLoggedInPart() throws Exception {
+ try (MockedConstruction<ProcessBuilder> ignored = tool(0, lines(PRINTED_LINES), "")) {
+ ProcessExecutor.getInstance(ProcessExecutor.Processes.GHOSTSCRIPT)
+ .runCommandWithOutputHandling(List.of("gs", "-v"));
+ }
+
+ assertThat(loggedOutputLines()).isLessThanOrEqualTo(ProcessExecutor.MAX_LOGGED_LINES + 2);
+ assertThat(appender.list)
+ .extracting(ILoggingEvent::getFormattedMessage)
+ .anyMatch(message -> message.contains("more"));
+ }
+
+ @Test
+ void failureMessageCarriesPartOfTheErrorOutput() {
+ try (MockedConstruction<ProcessBuilder> ignored = tool(1, "", lines(PRINTED_LINES))) {
+ assertThatThrownBy(
+ () ->
+ ProcessExecutor.getInstance(
+ ProcessExecutor.Processes.GHOSTSCRIPT)
+ .runCommandWithOutputHandling(List.of("gs", "-v")))
+ .isInstanceOf(IOException.class)
+ .satisfies(
+ e ->
+ assertThat(e.getMessage().split("\n", -1))
+ .hasSizeLessThanOrEqualTo(
+ ProcessExecutor.MAX_LOGGED_LINES + 1))
+ .hasMessageContaining("line 0")
+ .hasMessageContaining(
+ (PRINTED_LINES - ProcessExecutor.MAX_LOGGED_LINES) + " more lines");
+ }
+ }
+
+ @Test
+ void loggedLineIsShortAndPrintable() {
+ String coloured = "\u001b[31mred\u001b[0m\ttabbed";
+ assertThat(ProcessExecutor.forLog(coloured)).isEqualTo("?[31mred?[0m\ttabbed");
+
+ String longLine = "x".repeat(ProcessExecutor.MAX_LOGGED_LINE_LENGTH * 3);
+ assertThat(ProcessExecutor.forLog(longLine))
+ .hasSize(ProcessExecutor.MAX_LOGGED_LINE_LENGTH + 3)
+ .endsWith("...");
+ }
+}
diff --git a/app/core/src/main/java/stirling/software/SPDF/service/VeraPDFService.java b/app/core/src/main/java/stirling/software/SPDF/service/VeraPDFService.java
index f89a2a24b8..a0f12a051a 100644
--- a/app/core/src/main/java/stirling/software/SPDF/service/VeraPDFService.java
+++ b/app/core/src/main/java/stirling/software/SPDF/service/VeraPDFService.java
@@ -6,6 +6,11 @@ import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
+import org.apache.pdfbox.Loader;
+import org.apache.pdfbox.cos.COSName;
+import org.apache.pdfbox.cos.COSObject;
+import org.apache.pdfbox.cos.COSStream;
+import org.apache.pdfbox.pdmodel.PDDocument;
import org.springframework.stereotype.Service;
import org.verapdf.core.EncryptedPdfException;
import org.verapdf.core.ModelParsingException;
@@ -24,11 +29,13 @@ import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import stirling.software.SPDF.model.api.security.PDFVerificationResult;
+import stirling.software.common.util.XmpUtils;
@Service
@Slf4j
public class VeraPDFService {
+ private static final COSName XML = COSName.getPDFName("XML");
private static final String NOT_PDFA_STANDARD_ID = "not-pdfa";
private static final String NOT_PDFA_STANDARD_NAME =
"Not PDF/A (no PDF/A identification metadata)";
@@ -195,6 +202,18 @@ public class VeraPDFService {
byte[] pdfBytes = pdfStream.readAllBytes();
List<PDFVerificationResult> results = new ArrayList<>();
+ if (hasOversizedXmp(pdfBytes)) {
+ log.warn("Skipping standards validation: an XMP packet exceeds the size limit");
+ results.add(
+ buildErrorResult(
+ null,
+ null,
+ "Not validated: an XMP metadata packet is larger than "
+ + XmpUtils.MAX_XMP_BYTES
+ + " bytes"));
+ return results;
+ }
+
PDFAFlavour declaredFlavour;
List<PDFAFlavour> detectedFlavours;
@@ -323,6 +342,40 @@ public class VeraPDFService {
return results;
}
+ /**
+ * veraPDF parses every XMP packet it validates with no size limit, in time that grows with the
+ * square of an array's length. It reads the catalog's packet and each stream typed /Metadata
+ * /XML, so both are measured here before it starts.
+ */
+ static boolean hasOversizedXmp(byte[] pdfBytes) {
+ try (PDDocument document = Loader.loadPDF(pdfBytes)) {
+ if (document.getDocumentCatalog().getCOSObject().getDictionaryObject(COSName.METADATA)
+ instanceof COSStream catalogPacket
+ && isOversized(catalogPacket)) {
+ return true;
+ }
+ for (COSObject object : document.getDocument().getObjectsByType(COSName.METADATA)) {
+ if (object.getObject() instanceof COSStream packet
+ && XML.equals(packet.getCOSName(COSName.SUBTYPE))
+ && isOversized(packet)) {
+ return true;
+ }
+ }
+ return false;
+ } catch (IOException e) {
+ // veraPDF reports documents that PDFBox cannot open
+ return false;
+ }
+ }
+
+ private static boolean isOversized(COSStream packet) {
+ try (InputStream in = packet.createInputStream()) {
+ return in.readNBytes(XmpUtils.MAX_XMP_BYTES + 1).length > XmpUtils.MAX_XMP_BYTES;
+ } catch (IOException e) {
+ return false;
+ }
+ }
+
private static boolean isPdfaFlavour(PDFAFlavour flavour) {
return flavour != null
&& PDFFlavours.isFlavourFamily(flavour, PDFAFlavour.SpecificationFamily.PDF_A);
diff --git a/app/core/src/test/java/stirling/software/SPDF/service/VeraPDFServiceXmpLimitTest.java b/app/core/src/test/java/stirling/software/SPDF/service/VeraPDFServiceXmpLimitTest.java
new file mode 100644
index 0000000000..5ef1b1273f
--- /dev/null
+++ b/app/core/src/test/java/stirling/software/SPDF/service/VeraPDFServiceXmpLimitTest.java
@@ -0,0 +1,86 @@
+package stirling.software.SPDF.service;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+
+import org.apache.pdfbox.pdmodel.PDDocument;
+import org.apache.pdfbox.pdmodel.PDPage;
+import org.apache.pdfbox.pdmodel.common.PDMetadata;
+import org.junit.jupiter.api.Test;
+
+import stirling.software.SPDF.model.api.security.PDFVerificationResult;
+import stirling.software.common.util.XmpUtils;
+
+class VeraPDFServiceXmpLimitTest {
+
+ /** An XMP packet with {@code padding} bytes of whitespace, as packets carry for editing. */
+ private static byte[] packet(int padding) {
+ String xmp =
+ "<?xpacket begin=\"\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>"
+ + "<x:xmpmeta xmlns:x=\"adobe:ns:meta/\"></x:xmpmeta>"
+ + " ".repeat(padding)
+ + "<?xpacket end=\"w\"?>";
+ return xmp.getBytes(StandardCharsets.UTF_8);
+ }
+
+ private static PDMetadata metadata(PDDocument document, int padding) throws IOException {
+ PDMetadata metadata = new PDMetadata(document);
+ metadata.importXMPMetadata(packet(padding));
+ return metadata;
+ }
+
+ private static byte[] save(PDDocument document) throws IOException {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ document.save(out);
+ return out.toByteArray();
+ }
+
+ @Test
+ void oversizedCatalogPacketIsNotValidated() throws Exception {
+ byte[] pdf;
+ try (PDDocument document = new PDDocument()) {
+ document.addPage(new PDPage());
+ document.getDocumentCatalog().setMetadata(metadata(document, XmpUtils.MAX_XMP_BYTES));
+ pdf = save(document);
+ }
+
+ List<PDFVerificationResult> results =
+ new VeraPDFService().validatePDF(new ByteArrayInputStream(pdf));
+
+ assertThat(results).hasSize(1);
+ assertThat(results.getFirst().isCompliant()).isFalse();
+ assertThat(results.getFirst().getFailures())
+ .extracting(PDFVerificationResult.ValidationIssue::getMessage)
+ .singleElement()
+ .asString()
+ .startsWith("Not validated");
+ }
+
+ @Test
+ void oversizedPagePacketIsFound() throws Exception {
+ try (PDDocument document = new PDDocument()) {
+ PDPage page = new PDPage();
+ document.addPage(page);
+ page.setMetadata(metadata(document, XmpUtils.MAX_XMP_BYTES));
+
+ assertThat(VeraPDFService.hasOversizedXmp(save(document))).isTrue();
+ }
+ }
+
+ @Test
+ void ordinaryPacketsPass() throws Exception {
+ try (PDDocument document = new PDDocument()) {
+ PDPage page = new PDPage();
+ document.addPage(page);
+ document.getDocumentCatalog().setMetadata(metadata(document, 2_000));
+ page.setMetadata(metadata(document, 2_000));
+
+ assertThat(VeraPDFService.hasOversizedXmp(save(document))).isFalse();
+ }
+ }
+}