#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
Calibre and Office conversion hardening (#8669)
EthanHealy0137c810f0d5f5
diff --git a/app/common/src/main/java/stirling/software/SPDF/config/EndpointConfiguration.java b/app/common/src/main/java/stirling/software/SPDF/config/EndpointConfiguration.javaindex 7789d2b1ee..56bcee36c2 100644--- a/app/common/src/main/java/stirling/software/SPDF/config/EndpointConfiguration.java+++ b/app/common/src/main/java/stirling/software/SPDF/config/EndpointConfiguration.java@@ -384,6 +384,7 @@ public class EndpointConfiguration {addEndpointToGroup("Convert", "pdf-to-markdown");addEndpointToGroup("Convert", "eml-to-pdf");addEndpointToGroup("Convert", "pdf-to-epub");+ addEndpointToGroup("Convert", "ebook-to-pdf");// Backend-only endpoints (not in frontend tool registry)addEndpointToGroup("Convert", "pdf-to-vector");addEndpointToGroup("Convert", "vector-to-pdf");@@ -562,6 +563,7 @@ public class EndpointConfiguration {addEndpointToGroup("Java", "validate-signature");addEndpointToGroup("Java", "edit-table-of-contents");addEndpointToGroup("Java", "pdf-to-epub");+ addEndpointToGroup("Java", "ebook-to-pdf");addEndpointToGroup("Java", "eml-to-pdf");addEndpointToGroup("Java", "handleData");addEndpointToGroup("Java", "form-detection");@@ -646,6 +648,7 @@ public class EndpointConfiguration {// Calibre dependent endpointsaddEndpointToGroup("Calibre", "pdf-to-epub");+ addEndpointToGroup("Calibre", "ebook-to-pdf");}private void processEnvironmentConfigs() {diff --git a/app/common/src/main/java/stirling/software/common/util/CalibreSandboxPolicy.java b/app/common/src/main/java/stirling/software/common/util/CalibreSandboxPolicy.javaindex b11768ab3e..7636516858 100644--- a/app/common/src/main/java/stirling/software/common/util/CalibreSandboxPolicy.java+++ b/app/common/src/main/java/stirling/software/common/util/CalibreSandboxPolicy.java@@ -2,25 +2,39 @@ package stirling.software.common.util;import java.io.File;import java.io.IOException;+import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;import java.util.ArrayList;+import java.util.Comparator;import java.util.List;import java.util.Locale;import java.util.Map;import java.util.Set;-import java.util.concurrent.atomic.AtomicBoolean;+import java.util.concurrent.TimeUnit;import lombok.extern.slf4j.Slf4j;+/**+ * Confines Calibre to its job directory with the launcher's Landlock and seccomp sandbox and a+ * scrubbed environment. The sandbox is Linux-only: it needs Linux 5.13+ with Landlock and seccomp,+ * and Python 3, so Windows, macOS, Docker Desktop and older kernels cannot provide it. With the+ * sandbox {@link Mode#ON}, the default, such a host gets no Calibre: the startup probe disables its+ * endpoint group, and a job the launcher refuses fails.+ */@Slf4jfinal class CalibreSandboxPolicy {+ /** {@code ON}, the default: confined, or not at all. {@code OFF}: never confined. */enum Mode {- UNSUPPORTED,- OFF,- ENFORCE,- REQUIRED+ ON,+ OFF+ }++ enum Probe {+ ACTIVE,+ REFUSED,+ UNKNOWN}static final String LAUNCHER = "calibre_sandbox.py";@@ -29,8 +43,6 @@ final class CalibreSandboxPolicy {static final int LAUNCHER_REFUSED_EXIT_CODE = 125;static final String REFUSED_MESSAGE = "Calibre conversion refused: its sandbox is unavailable";- private static final Path CALIBRE_CONVERT = Path.of("/opt/calibre/ebook-convert");-private static final String HOME_DIR = ".calibre";private static final Set<String> ENV_ALLOWLIST =@@ -44,74 +56,69 @@ final class CalibreSandboxPolicy {"LD_LIBRARY_PATH","FONTCONFIG_PATH","FONTCONFIG_FILE",- "MALLOC_ARENA_MAX",- MODE_VARIABLE);+ "MALLOC_ARENA_MAX");private static final List<String> ENV_ALLOWED_PREFIXES = List.of("LC_", "QT_", "QTWEBENGINE_");- private static final AtomicBoolean unsupportedReported = new AtomicBoolean();+ private static final String PROBE_STDERR = "probe.err";+ private static final long PROBE_TIMEOUT_SECONDS = 60;private CalibreSandboxPolicy() {}static Mode configuredMode() {- return resolveMode(System.getenv(MODE_VARIABLE), Files.isExecutable(CALIBRE_CONVERT));+ return resolveMode(System.getenv(MODE_VARIABLE));}- static Mode resolveMode(String configured, boolean sandboxExpected) {+ /**+ * Only {@code off} turns the sandbox off. {@code required} is the older name for {@code on};+ * any other value, {@code enforce} included, means {@code on} and is logged, so an install+ * still set to one learns why Calibre is disabled and how to turn the sandbox off.+ */+ static Mode resolveMode(String configured) {if (configured == null || configured.isBlank()) {- return sandboxExpected ? Mode.ENFORCE : Mode.UNSUPPORTED;+ return Mode.ON;}- return switch (configured.trim().toLowerCase(Locale.ROOT)) {+ String value = configured.trim().toLowerCase(Locale.ROOT);+ return switch (value) {case "off" -> Mode.OFF;- case "required" -> Mode.REQUIRED;- default -> Mode.ENFORCE;+ case "on", "required" -> Mode.ON;+ default -> {+ log.warn(+ "{}={} is not recognised, so the Calibre sandbox is on; set {}=off to run"+ + " Calibre without it",+ MODE_VARIABLE,+ value,+ MODE_VARIABLE);+ yield Mode.ON;+ }};}+ /**+ * {@code command} wrapped in the launcher and confined to {@code workingDirectory}, with {@code+ * env} cut down to what Calibre needs and pointed into that directory. Without a working+ * directory or Python to run the launcher the job is refused. {@code OFF} returns the command+ * unchanged.+ */static List<String> confine(Mode mode, List<String> command, File workingDirectory, Map<String, String> env)throws IOException {- switch (mode) {- case UNSUPPORTED -> {- if (unsupportedReported.compareAndSet(false, true)) {- log.warn(- "Calibre is not installed under {}, so it runs unconfined; set"- + " {}=required to confine it anyway",- CALIBRE_CONVERT.getParent(),- MODE_VARIABLE);- }- return command;- }- case OFF -> {- log.error("Calibre is running unconfined because {}=off", MODE_VARIABLE);- return command;- }- default -> {- return wrap(mode, command, workingDirectory, env);- }+ if (mode == Mode.OFF) {+ log.error("Calibre is running unconfined because {}=off", MODE_VARIABLE);+ return command;}- }-- private static List<String> wrap(- Mode mode, List<String> command, File workingDirectory, Map<String, String> env)- throws IOException {if (workingDirectory == null) {throw new IOException("Calibre needs a working directory to be confined to");}String python = CheckProgramInstall.getAvailablePythonCommand();if (python == null) {- if (mode == Mode.REQUIRED) {- log.error("Refusing to run Calibre: its sandbox needs Python, which is missing");- throw new IOException(REFUSED_MESSAGE);- }- log.error("Calibre is running unconfined because Python is not installed");- return command;+ log.error("Refusing to run Calibre: its sandbox needs Python, which is missing");+ throw new IOException(REFUSED_MESSAGE);}Path workDir = workingDirectory.toPath().toAbsolutePath().normalize();Path home = Files.createDirectories(workDir.resolve(HOME_DIR));env.keySet().removeIf(name -> !isEnvAllowed(name));- env.put(MODE_VARIABLE, mode.name().toLowerCase(Locale.ROOT));env.put("HOME", home.toString());for (String name : List.of("TMPDIR", "TMP", "TEMP", "XDG_RUNTIME_DIR")) {env.put(name, home.toString());@@ -126,23 +133,115 @@ final class CalibreSandboxPolicy {return confined;}- static void checkLauncherOutcome(int exitCode, List<String> errorLines) throws IOException {- List<String> launcherLines =- errorLines.stream().filter(line -> line.startsWith(LAUNCHER_PREFIX)).toList();- if (launcherLines.isEmpty()) {- return;+ /**+ * Whether Calibre may be offered: with the sandbox on, only when {@code probeCommand} ran fully+ * confined. Pass Calibre's own version check, so its install path is checked against the+ * launcher's allowlist too. stderr goes to a file, not a pipe, so a stalled launcher cannot+ * outlive the timeout.+ */+ static boolean probeAtStartup(Mode mode, List<String> probeCommand) {+ if (mode == Mode.OFF) {+ log.error("Calibre sandbox is off ({}=off); Calibre runs unconfined", MODE_VARIABLE);+ return true;}- if (exitCode == LAUNCHER_REFUSED_EXIT_CODE) {- log.error(- "Refusing to run Calibre: its sandbox is required but unavailable on this"- + " host: {}",- String.join("; ", launcherLines));- throw new IOException(REFUSED_MESSAGE);+ Path workDir;+ try {+ workDir = Files.createTempDirectory("calibre-sandbox-probe");+ } catch (IOException e) {+ return report(Probe.UNKNOWN, "no temp dir for the probe: " + e.getMessage());+ }+ Path stderr = workDir.resolve(PROBE_STDERR);+ try {+ ProcessBuilder builder = new ProcessBuilder(probeCommand);+ builder.command(confine(mode, probeCommand, workDir.toFile(), builder.environment()));+ builder.directory(workDir.toFile());+ builder.redirectOutput(ProcessBuilder.Redirect.DISCARD);+ builder.redirectError(stderr.toFile());+ Process process = builder.start();+ if (!process.waitFor(PROBE_TIMEOUT_SECONDS, TimeUnit.SECONDS)) {+ process.descendants().forEach(ProcessHandle::destroyForcibly);+ process.destroyForcibly();+ return report(+ Probe.UNKNOWN,+ "the probe did not finish within " + PROBE_TIMEOUT_SECONDS + "s");+ }+ List<String> errorLines =+ Files.exists(stderr)+ ? Files.readAllLines(stderr, StandardCharsets.UTF_8)+ : List.of();+ int exitCode = process.exitValue();+ Probe probe = classifyProbe(exitCode, errorLines);+ return report(probe, describe(probe, exitCode, errorLines));+ } catch (IOException e) {+ return report(Probe.UNKNOWN, "the probe could not run: " + e.getMessage());+ } catch (InterruptedException e) {+ Thread.currentThread().interrupt();+ return false;+ } finally {+ deleteTree(workDir);+ }+ }++ private static void deleteTree(Path root) {+ try (var paths = Files.walk(root)) {+ for (Path path : paths.sorted(Comparator.reverseOrder()).toList()) {+ Files.deleteIfExists(path);+ }+ } catch (IOException e) {+ log.debug("Cannot remove {}: {}", root, e.getMessage());+ }+ }++ /** A non-zero exit that is not the launcher's own refusal says nothing about the sandbox. */+ static Probe classifyProbe(int exitCode, List<String> errorLines) {+ if (exitCode == LAUNCHER_REFUSED_EXIT_CODE || !launcherLines(errorLines).isEmpty()) {+ return Probe.REFUSED;+ }+ return exitCode == 0 ? Probe.ACTIVE : Probe.UNKNOWN;+ }++ /** What the launcher said, or else the exit code and the last line Calibre wrote. */+ private static String describe(Probe probe, int exitCode, List<String> errorLines) {+ if (probe == Probe.REFUSED) {+ return String.join("; ", launcherLines(errorLines));+ }+ String lastLine =+ errorLines.stream()+ .map(String::strip)+ .filter(line -> !line.isEmpty())+ .reduce((first, second) -> second)+ .orElse("");+ return "exit " + exitCode + (lastLine.isEmpty() ? "" : ": " + lastLine);+ }++ private static boolean report(Probe probe, String detail) {+ if (probe == Probe.ACTIVE) {+ log.info("Calibre sandbox active");+ return true;}log.error(- "Calibre ran without part of its sandbox: {}. Set {}=required to refuse such runs",- String.join("; ", launcherLines),+ "Calibre did not run in its sandbox on this host ({}), so ebook conversion is"+ + " disabled; the sandbox needs Linux 5.13+ with Landlock and seccomp, and"+ + " Python 3. Set {}=off to run Calibre without it",+ detail,MODE_VARIABLE);+ return false;+ }++ /** Fails a job whose launcher refused to run it. */+ static void checkLauncherOutcome(List<String> errorLines) throws IOException {+ List<String> launcherLines = launcherLines(errorLines);+ if (launcherLines.isEmpty()) {+ return;+ }+ log.error(+ "Refusing to run Calibre: its sandbox is unavailable on this host: {}",+ String.join("; ", launcherLines));+ throw new IOException(REFUSED_MESSAGE);+ }++ private static List<String> launcherLines(List<String> errorLines) {+ return errorLines.stream().filter(line -> line.startsWith(LAUNCHER_PREFIX)).toList();}private static boolean isEnvAllowed(String name) {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.javaindex 11cd32a18f..8e7d3bed98 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@@ -73,6 +73,15 @@ public class OfficeDocumentSanitizer {return OOXML_EXTENSIONS.contains(lower) || ODF_EXTENSIONS.contains(lower);}+ /**+ * The document with external references stripped from its relationship and ODF XML parts,+ * except targets an admin has allowlisted. Returned unchanged, with no part inspected, when+ * {@code system.disableSanitize} is set.+ *+ * @throws IOException when the input is empty, an entry is named outside the archive, or a+ * relationship or ODF XML part cannot be parsed; such a document is refused rather than+ * passed on with that part unchanged+ */public byte[] sanitize(byte[] documentBytes, String extension) throws IOException {if (documentBytes == null || documentBytes.length == 0) {throw new IOException("Office document input is empty or null");@@ -114,11 +123,15 @@ public class OfficeDocumentSanitizer {}zipOut.closeEntry();}+ } catch (SecurityException e) {+ throw new IOException("Office document has an unsafe entry name", e);}return out.toByteArray();}- private byte[] sanitizeEntry(String entryName, byte[] entryBytes) {+ // The converters' parsers accept parts this one rejects, so such a part could still carry+ // references there.+ private byte[] sanitizeEntry(String entryName, byte[] entryBytes) throws IOException {String lower = entryName.toLowerCase(Locale.ROOT);try {if (lower.endsWith(".rels")) {@@ -127,14 +140,9 @@ public class OfficeDocumentSanitizer {if (isOdfXmlPart(lower)) {return sanitizeOdfXml(entryBytes);}- } catch (ParserConfigurationException- | SAXException- | IOException- | TransformerException e) {- log.warn(- "Failed to parse XML part '{}' for sanitization, leaving as-is: {}",- entryName,- e.getMessage());+ } catch (ParserConfigurationException | SAXException | TransformerException e) {+ throw new IOException(+ "Office document part '" + entryName + "' could not be sanitized", e);}return entryBytes;}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.javaindex 7538c0e3fb..f51fde37bd 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@@ -212,6 +212,14 @@ public class ProcessExecutor {calibreSandboxMode = mode;}+ /**+ * Runs {@code probeCommand}, normally Calibre's version check, through the Calibre sandbox,+ * logs the outcome, and says whether the configured mode lets Calibre be offered on this host.+ */+ public static boolean isCalibreSandboxUsable(List<String> probeCommand) {+ return CalibreSandboxPolicy.probeAtStartup(calibreSandboxMode, probeCommand);+ }+private static Path profileTemplateFromEnvironment() {String template = System.getenv("STIRLING_LO_PROFILE_TEMPLATE");if (template == null || template.isBlank()) {@@ -548,7 +556,7 @@ public class ProcessExecutor {log.debug("Calibre output:\n{}", output);log.debug("Calibre error output:\n{}", errors);}- CalibreSandboxPolicy.checkLauncherOutcome(exitCode, errorLines);+ CalibreSandboxPolicy.checkLauncherOutcome(errorLines);if (exitCode != 0) {log.warn("Calibre exited with code {}; its output is logged at debug level", exitCode);throw new IOException("Calibre conversion failed with exit code " + exitCode);diff --git a/app/common/src/test/java/stirling/software/SPDF/config/EndpointConfigurationGapTest.java b/app/common/src/test/java/stirling/software/SPDF/config/EndpointConfigurationGapTest.javaindex be9f1cb149..2a72440c5e 100644--- a/app/common/src/test/java/stirling/software/SPDF/config/EndpointConfigurationGapTest.java+++ b/app/common/src/test/java/stirling/software/SPDF/config/EndpointConfigurationGapTest.java@@ -320,6 +320,16 @@ class EndpointConfigurationGapTest {config.disableGroup("Calibre");assertFalse(config.isEndpointEnabled("pdf-to-epub"));}++ @Test+ @DisplayName("both ebook conversions are disabled with the Calibre group")+ void ebookConversionsFollowCalibre() {+ EndpointConfiguration config = buildDefault();+ assertTrue(config.isEndpointEnabled("ebook-to-pdf"));+ config.disableGroup("Calibre");+ assertFalse(config.isEndpointEnabled("ebook-to-pdf"));+ assertFalse(config.isEndpointEnabled("pdf-to-epub"));+ }}@Nesteddiff --git a/app/common/src/test/java/stirling/software/common/util/CalibreSandboxPolicyTest.java b/app/common/src/test/java/stirling/software/common/util/CalibreSandboxPolicyTest.javaindex 0b98555b42..6fce508e08 100644--- a/app/common/src/test/java/stirling/software/common/util/CalibreSandboxPolicyTest.java+++ b/app/common/src/test/java/stirling/software/common/util/CalibreSandboxPolicyTest.java@@ -10,23 +10,28 @@ import static org.mockito.Mockito.verify;import static org.mockito.Mockito.when;import java.io.ByteArrayInputStream;+import java.io.File;import java.io.IOException;import java.nio.charset.StandardCharsets;+import java.nio.file.Files;import java.nio.file.Path;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.concurrent.TimeUnit;+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.junit.jupiter.api.io.TempDir;+import org.mockito.ArgumentCaptor;import org.mockito.MockedConstruction;import org.mockito.MockedStatic;import org.mockito.Mockito;import stirling.software.common.util.CalibreSandboxPolicy.Mode;+import stirling.software.common.util.CalibreSandboxPolicy.Probe;class CalibreSandboxPolicyTest {@@ -74,38 +79,34 @@ class CalibreSandboxPolicyTest {}@Test- void sandboxEnforcesByDefaultWhereItIsExpected() {- assertThat(CalibreSandboxPolicy.resolveMode(null, true)).isEqualTo(Mode.ENFORCE);- assertThat(CalibreSandboxPolicy.resolveMode(" ", true)).isEqualTo(Mode.ENFORCE);- assertThat(CalibreSandboxPolicy.resolveMode(null, false)).isEqualTo(Mode.UNSUPPORTED);+ void sandboxIsOnByDefault() {+ assertThat(CalibreSandboxPolicy.resolveMode(null)).isEqualTo(Mode.ON);+ assertThat(CalibreSandboxPolicy.resolveMode(" ")).isEqualTo(Mode.ON);}@Test- void configuredModeIsHonouredAndUnknownValuesEnforce() {- assertThat(CalibreSandboxPolicy.resolveMode("off", true)).isEqualTo(Mode.OFF);- assertThat(CalibreSandboxPolicy.resolveMode("ENFORCE", true)).isEqualTo(Mode.ENFORCE);- assertThat(CalibreSandboxPolicy.resolveMode("required", false)).isEqualTo(Mode.REQUIRED);- assertThat(CalibreSandboxPolicy.resolveMode("disabled", true)).isEqualTo(Mode.ENFORCE);+ void onlyOffTurnsTheSandboxOff() {+ assertThat(CalibreSandboxPolicy.resolveMode("off")).isEqualTo(Mode.OFF);+ assertThat(CalibreSandboxPolicy.resolveMode(" OFF ")).isEqualTo(Mode.OFF);+ for (String value : List.of("on", "required", "enforce", "best-effort", "disabled")) {+ assertThat(CalibreSandboxPolicy.resolveMode(value)).as(value).isEqualTo(Mode.ON);+ }}@Testvoid commandIsWrappedInTheLauncherAndConfinedToTheWorkingDirectory() throws IOException {- for (Mode mode : List.of(Mode.ENFORCE, Mode.REQUIRED)) {- assertThat(- CalibreSandboxPolicy.confine(- mode, command, workDir.toFile(), new HashMap<>()))- .isEqualTo(confinedCommand);- }+ assertThat(+ CalibreSandboxPolicy.confine(+ Mode.ON, command, workDir.toFile(), new HashMap<>()))+ .isEqualTo(confinedCommand);}@Test- void unconfinedModesLeaveTheCommandAlone() throws IOException {- for (Mode mode : List.of(Mode.OFF, Mode.UNSUPPORTED)) {- assertThat(- CalibreSandboxPolicy.confine(- mode, command, workDir.toFile(), new HashMap<>()))- .isEqualTo(command);- }+ void offLeavesTheCommandAlone() throws IOException {+ assertThat(+ CalibreSandboxPolicy.confine(+ Mode.OFF, command, workDir.toFile(), new HashMap<>()))+ .isEqualTo(command);}@Test@@ -120,7 +121,7 @@ class CalibreSandboxPolicyTest {env.put("LC_ALL", "C.UTF-8");env.put("QTWEBENGINE_CHROMIUM_FLAGS", "--disable-gpu");- CalibreSandboxPolicy.confine(Mode.REQUIRED, command, workDir.toFile(), env);+ CalibreSandboxPolicy.confine(Mode.ON, command, workDir.toFile(), env);String home = workDir.resolve(".calibre").toString();assertThat(env)@@ -132,44 +133,119 @@ class CalibreSandboxPolicyTest {Map.entry("XDG_RUNTIME_DIR", home),Map.entry("PATH", "/usr/bin"),Map.entry("LC_ALL", "C.UTF-8"),- Map.entry("QTWEBENGINE_CHROMIUM_FLAGS", "--disable-gpu"),- Map.entry(CalibreSandboxPolicy.MODE_VARIABLE, "required"));+ Map.entry("QTWEBENGINE_CHROMIUM_FLAGS", "--disable-gpu"));assertThat(Path.of(home)).isDirectory();}@Testvoid aJobWithoutAWorkingDirectoryIsRefused() {assertThatThrownBy(- () ->- CalibreSandboxPolicy.confine(- Mode.REQUIRED, command, null, new HashMap<>()))+ () -> CalibreSandboxPolicy.confine(Mode.ON, command, null, new HashMap<>())).isInstanceOf(IOException.class).hasMessageContaining("working directory");}@Test- void withoutPythonARequiredSandboxRefusesToRunCalibre() {+ void withoutPythonCalibreIsRefused() {checkProgramInstall.when(CheckProgramInstall::getAvailablePythonCommand).thenReturn(null);assertThatThrownBy(() ->CalibreSandboxPolicy.confine(- Mode.REQUIRED, command, workDir.toFile(), new HashMap<>()))+ Mode.ON, command, workDir.toFile(), new HashMap<>())).isInstanceOf(IOException.class).hasMessage(CalibreSandboxPolicy.REFUSED_MESSAGE);}@Test- void withoutPythonAnEnforcedSandboxRunsCalibreUnconfined() throws IOException {- checkProgramInstall.when(CheckProgramInstall::getAvailablePythonCommand).thenReturn(null);-+ void probeClassifiesWhatTheLauncherReports() {+ String landlock = "calibre-sandbox: landlock unavailable, refusing to run";+ assertThat(CalibreSandboxPolicy.classifyProbe(0, List.of())).isEqualTo(Probe.ACTIVE);+ assertThat(CalibreSandboxPolicy.classifyProbe(0, List.of(landlock)))+ .isEqualTo(Probe.REFUSED);assertThat(- CalibreSandboxPolicy.confine(- Mode.ENFORCE, command, workDir.toFile(), new HashMap<>()))- .isEqualTo(command);+ CalibreSandboxPolicy.classifyProbe(+ CalibreSandboxPolicy.LAUNCHER_REFUSED_EXIT_CODE, List.of(landlock)))+ .isEqualTo(Probe.REFUSED);+ assertThat(CalibreSandboxPolicy.classifyProbe(1, List.of())).isEqualTo(Probe.UNKNOWN);+ }++ private static final List<String> PROBE = List.of("ebook-convert", "--version");++ @Test+ void startupProbeRunsCalibreThroughTheLauncherAndCleansUp() {+ try (MockedConstruction<ProcessBuilder> builders = calibre(0, "")) {+ assertThat(CalibreSandboxPolicy.probeAtStartup(Mode.ON, PROBE)).isTrue();++ ProcessBuilder builder = builders.constructed().getFirst();+ verify(builder)+ .command(+ org.mockito.ArgumentMatchers.<List<String>>argThat(+ cmd ->+ cmd.subList(0, 3)+ .equals(+ List.of(+ "python3",+ "-I",+ LAUNCHER.toString()))+ && cmd.subList(cmd.size() - 2, cmd.size())+ .equals(PROBE)));+ ArgumentCaptor<File> probeDir = ArgumentCaptor.forClass(File.class);+ verify(builder).directory(probeDir.capture());+ assertThat(probeDir.getValue()).doesNotExist();+ }+ }++ @Test+ void startupProbeRefusalDisablesCalibre() {+ try (MockedConstruction<ProcessBuilder> ignored =+ calibre(+ CalibreSandboxPolicy.LAUNCHER_REFUSED_EXIT_CODE,+ "calibre-sandbox: landlock unavailable, refusing to run\n")) {+ assertThat(CalibreSandboxPolicy.probeAtStartup(Mode.ON, PROBE)).isFalse();+ }+ }++ @Test+ void startupProbeLaunchesNothingWhenTheSandboxIsOff() {+ try (MockedConstruction<ProcessBuilder> builders = calibre(0, "")) {+ assertThat(CalibreSandboxPolicy.probeAtStartup(Mode.OFF, PROBE)).isTrue();+ assertThat(builders.constructed()).isEmpty();+ }+ }++ @Test+ void startupProbeThatDoesNotFinishIsNotActive() {+ ProcessHandle calibreChild = mock(ProcessHandle.class);+ try (MockedConstruction<ProcessBuilder> builders = calibre(0, "", false, calibreChild)) {+ assertThat(CalibreSandboxPolicy.probeAtStartup(Mode.ON, PROBE)).isFalse();+ verify(calibreChild).destroyForcibly();++ ArgumentCaptor<File> probeDir = ArgumentCaptor.forClass(File.class);+ verify(builders.constructed().getFirst()).directory(probeDir.capture());+ assertThat(probeDir.getValue()).doesNotExist();+ }+ }++ @Test+ void startupProbeWithoutPythonLaunchesNothing() {+ checkProgramInstall.when(CheckProgramInstall::getAvailablePythonCommand).thenReturn(null);+ try (MockedConstruction<ProcessBuilder> builders = calibre(0, "")) {+ assertThat(CalibreSandboxPolicy.probeAtStartup(Mode.ON, PROBE)).isFalse();+ assertThat(builders.constructed()).allSatisfy(b -> verify(b, never()).start());+ }}private static MockedConstruction<ProcessBuilder> calibre(int exitCode, String stderr) {+ return calibre(exitCode, stderr, true);+ }++ /**+ * Stands in for the launcher: stderr arrives on the process's stream and, for callers that+ * redirect it, in the file they named.+ */+ private static MockedConstruction<ProcessBuilder> calibre(+ int exitCode, String stderr, boolean finishes, ProcessHandle... descendants) {return Mockito.mockConstruction(ProcessBuilder.class,(builder, context) -> {@@ -180,9 +256,17 @@ class CalibreSandboxPolicyTest {.thenReturn(new ByteArrayInputStream(stderr.getBytes(StandardCharsets.UTF_8)));- when(process.waitFor(anyLong(), any(TimeUnit.class))).thenReturn(true);+ when(process.waitFor(anyLong(), any(TimeUnit.class))).thenReturn(finishes);when(process.exitValue()).thenReturn(exitCode);+ when(process.descendants()).thenAnswer(invocation -> Stream.of(descendants));when(builder.environment()).thenReturn(new HashMap<>());+ when(builder.redirectError(any(File.class)))+ .thenAnswer(+ invocation -> {+ Files.writeString(+ invocation.<File>getArgument(0).toPath(), stderr);+ return builder;+ });when(builder.start()).thenReturn(process);});}@@ -194,7 +278,7 @@ class CalibreSandboxPolicyTest {@Testvoid processExecutorLaunchesCalibreConfined() throws Exception {- ProcessExecutor.setCalibreSandboxMode(Mode.REQUIRED);+ ProcessExecutor.setCalibreSandboxMode(Mode.ON);try (MockedConstruction<ProcessBuilder> builders = calibre(0, "")) {runCalibre();@@ -203,8 +287,8 @@ class CalibreSandboxPolicyTest {}@Test- void bareInstallLaunchesCalibreUnchanged() throws Exception {- ProcessExecutor.setCalibreSandboxMode(Mode.UNSUPPORTED);+ void offModeLaunchesCalibreUnchanged() throws Exception {+ ProcessExecutor.setCalibreSandboxMode(Mode.OFF);try (MockedConstruction<ProcessBuilder> builders = calibre(0, "")) {runCalibre();@@ -213,9 +297,8 @@ class CalibreSandboxPolicyTest {}@Test- void processExecutorDoesNotStartCalibreWhenTheRequiredSandboxNeedsMissingPython()- throws Exception {- ProcessExecutor.setCalibreSandboxMode(Mode.REQUIRED);+ void processExecutorDoesNotStartCalibreWithoutPython() throws Exception {+ ProcessExecutor.setCalibreSandboxMode(Mode.ON);checkProgramInstall.when(CheckProgramInstall::getAvailablePythonCommand).thenReturn(null);try (MockedConstruction<ProcessBuilder> builders = calibre(0, "")) {assertThatThrownBy(this::runCalibre)@@ -228,11 +311,11 @@ class CalibreSandboxPolicyTest {@Testvoid launcherRefusalOnAKernelWithoutLandlockFailsTheJob() throws Exception {- ProcessExecutor.setCalibreSandboxMode(Mode.REQUIRED);+ ProcessExecutor.setCalibreSandboxMode(Mode.ON);try (MockedConstruction<ProcessBuilder> ignored =calibre(CalibreSandboxPolicy.LAUNCHER_REFUSED_EXIT_CODE,- "calibre-sandbox: landlock unavailable, filesystem unconfined\n")) {+ "calibre-sandbox: landlock unavailable, refusing to run\n")) {assertThatThrownBy(this::runCalibre).isInstanceOf(IOException.class).hasMessage(CalibreSandboxPolicy.REFUSED_MESSAGE);@@ -240,17 +323,19 @@ class CalibreSandboxPolicyTest {}@Test- void partialConfinementUnderEnforceStillConverts() throws Exception {- ProcessExecutor.setCalibreSandboxMode(Mode.ENFORCE);+ void calibreExitingWithTheLauncherCodeIsAnOrdinaryFailure() throws Exception {+ ProcessExecutor.setCalibreSandboxMode(Mode.ON);try (MockedConstruction<ProcessBuilder> ignored =- calibre(0, "calibre-sandbox: seccomp unavailable, network unconfined\n")) {- runCalibre();+ calibre(CalibreSandboxPolicy.LAUNCHER_REFUSED_EXIT_CODE, "Traceback\n")) {+ assertThatThrownBy(this::runCalibre)+ .isInstanceOf(IOException.class)+ .hasMessage("Calibre conversion failed with exit code 125");}}@Testvoid calibreErrorOutputIsNotPutInTheExceptionMessage() throws Exception {- ProcessExecutor.setCalibreSandboxMode(Mode.REQUIRED);+ ProcessExecutor.setCalibreSandboxMode(Mode.ON);String stderr ="Could not find file missing.png in book\n"+ "Could not find file uuid-in-the-copy/"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.javaindex eb22919068..246a279d6f 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@@ -312,6 +312,52 @@ class OfficeDocumentSanitizerTest {assertTrue(rels.contains("media/image1.png"));}+ @Test+ void sanitize_rejectsRelsPartWithDoctype() throws IOException {+ String relsWithDoctype =+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?><!DOCTYPE Relationships>"+ + "<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">"+ + "<Relationship Id=\"rId1\" Type=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image\""+ + " Target=\"file:///etc/hostname\" TargetMode=\"External\"/>"+ + "</Relationships>";+ Map<String, byte[]> entries = new LinkedHashMap<>();+ entries.put(+ "word/_rels/document.xml.rels", relsWithDoctype.getBytes(StandardCharsets.UTF_8));+ byte[] docx = zip(entries);++ assertThrows(IOException.class, () -> sanitizer.sanitize(docx, "docx"));+ }++ @Test+ void sanitize_rejectsMalformedRelsPart() throws IOException {+ String malformedRels =+ "<Relationships><Relationship Id=\"rId1\" Target=\"file:///etc/hostname\""+ + " TargetMode=\"External\"";+ Map<String, byte[]> entries = new LinkedHashMap<>();+ entries.put("word/_rels/document.xml.rels", malformedRels.getBytes(StandardCharsets.UTF_8));+ byte[] docx = zip(entries);++ assertThrows(IOException.class, () -> sanitizer.sanitize(docx, "docx"));+ }++ @Test+ void sanitize_rejectsMalformedOdfPart() throws IOException {+ Map<String, byte[]> entries = new LinkedHashMap<>();+ entries.put("content.xml", "<office:document-content>".getBytes(StandardCharsets.UTF_8));+ byte[] odt = zip(entries);++ assertThrows(IOException.class, () -> sanitizer.sanitize(odt, "odt"));+ }++ @Test+ void sanitize_rejectsEntryNamedOutsideTheArchive() throws IOException {+ Map<String, byte[]> entries = new LinkedHashMap<>();+ entries.put("../word/document.xml", "<w:document/>".getBytes(StandardCharsets.UTF_8));+ byte[] docx = zip(entries);++ assertThrows(IOException.class, () -> sanitizer.sanitize(docx, "docx"));+ }+@Testvoid sanitize_corruptZipProducesSafeOutput() throws IOException {byte[] garbage = "this is not a zip file".getBytes(StandardCharsets.UTF_8);diff --git a/app/core/src/main/java/stirling/software/SPDF/config/ExternalAppDepConfig.java b/app/core/src/main/java/stirling/software/SPDF/config/ExternalAppDepConfig.javaindex 46b1976ca7..9e1b557329 100644--- a/app/core/src/main/java/stirling/software/SPDF/config/ExternalAppDepConfig.java+++ b/app/core/src/main/java/stirling/software/SPDF/config/ExternalAppDepConfig.java@@ -19,6 +19,7 @@ import jakarta.annotation.PostConstruct;import lombok.extern.slf4j.Slf4j;import stirling.software.common.configuration.RuntimePathConfig;+import stirling.software.common.util.ProcessExecutor;import stirling.software.common.util.RegexPatternUtils;/**@@ -101,6 +102,8 @@ public class ExternalAppDepConfig {// Python / OpenCV special handlingcheckPythonAndOpenCV();+ disableCalibreUnlessConfined();+dependenciesChecked = true;} finally {endpointConfiguration.logDisabledEndpointsSummary();@@ -108,6 +111,19 @@ public class ExternalAppDepConfig {}}+ private void disableCalibreUnlessConfined() {+ if (!endpointConfiguration.isGroupEnabled("Calibre")+ || ProcessExecutor.isCalibreSandboxUsable(List.of(calibrePath, "--version"))) {+ return;+ }+ endpointConfiguration.disableGroup(+ "Calibre", EndpointConfiguration.DisableReason.DEPENDENCY);+ log.warn(+ "Calibre cannot be confined on this host - Disabling group: Calibre (Affected"+ + " features: {})",+ String.join(", ", getAffectedFeatures("Calibre")));+ }+private void checkDependencyAndDisableGroup(String command) {boolean available = isCommandAvailable(command);diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertEbookToPDFController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertEbookToPDFController.javaindex f6733bb0e0..5f1347470e 100644--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertEbookToPDFController.java+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertEbookToPDFController.java@@ -28,6 +28,7 @@ import stirling.software.SPDF.config.EndpointConfiguration;import stirling.software.SPDF.model.api.converters.ConvertEbookToPdfRequest;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.tool.ToolFormat;import stirling.software.common.model.tool.ToolIO;@@ -52,6 +53,7 @@ public class ConvertEbookToPDFController {private final TempFileManager tempFileManager;private final EndpointConfiguration endpointConfiguration;private final OfficeDocumentSanitizer officeDocumentSanitizer;+ private final RuntimePathConfig runtimePathConfig;private boolean isCalibreEnabled() {return endpointConfiguration.isGroupEnabled("Calibre");@@ -116,72 +118,74 @@ public class ConvertEbookToPDFController {Path workingDirectory = tempFileManager.createTempDirectory();Path inputPath = workingDirectory.resolve(baseName + "." + lowerExtension);Path outputPath = workingDirectory.resolve(baseName + ".pdf");+ try {- if (officeDocumentSanitizer.isSanitizableExtension(lowerExtension)) {- Files.write(- inputPath,- officeDocumentSanitizer.sanitize(inputFile.getBytes(), lowerExtension));- } else {- try (InputStream inputStream = inputFile.getInputStream()) {- Files.copy(inputStream, inputPath, StandardCopyOption.REPLACE_EXISTING);+ if (officeDocumentSanitizer.isSanitizableExtension(lowerExtension)) {+ Files.write(+ inputPath,+ officeDocumentSanitizer.sanitize(inputFile.getBytes(), lowerExtension));+ } else {+ try (InputStream inputStream = inputFile.getInputStream()) {+ Files.copy(inputStream, inputPath, StandardCopyOption.REPLACE_EXISTING);+ }}- }- List<String> command =- buildCalibreCommand(- inputPath,- outputPath,- embedAllFonts,- includeTableOfContents,- includePageNumbers);- ProcessExecutorResult result =- ProcessExecutor.getInstance(ProcessExecutor.Processes.CALIBRE)- .runCommandWithOutputHandling(command, workingDirectory.toFile());-- if (result == null) {- throw new IllegalStateException("Calibre conversion returned no result");- }+ List<String> command =+ buildCalibreCommand(+ inputPath,+ outputPath,+ embedAllFonts,+ includeTableOfContents,+ includePageNumbers);+ ProcessExecutorResult result =+ ProcessExecutor.getInstance(ProcessExecutor.Processes.CALIBRE)+ .runCommandWithOutputHandling(command, workingDirectory.toFile());++ if (result == null) {+ throw new IllegalStateException("Calibre conversion returned no result");+ }- if (result.getRc() != 0) {- throw new IllegalStateException("Calibre conversion failed");- }+ if (result.getRc() != 0) {+ throw new IllegalStateException("Calibre conversion failed");+ }- if (!Files.exists(outputPath) || Files.size(outputPath) == 0L) {- throw new IllegalStateException("Calibre did not produce a PDF output");- }+ if (!Files.exists(outputPath) || Files.size(outputPath) == 0L) {+ throw new IllegalStateException("Calibre did not produce a PDF output");+ }- String outputFilename =- GeneralUtils.generateFilename(originalFilename, "_convertedToPDF.pdf");+ String outputFilename =+ GeneralUtils.generateFilename(originalFilename, "_convertedToPDF.pdf");- TempFile tempOut = null;- try {- tempOut = tempFileManager.createManagedTempFile(".pdf");- if (optimizeForEbook) {- byte[] pdfBytes = Files.readAllBytes(outputPath);- try {- byte[] optimizedPdf = GeneralUtils.optimizePdfWithGhostscript(pdfBytes);- Files.write(tempOut.getPath(), optimizedPdf);- } catch (IOException e) {- log.warn(- "Ghostscript optimization failed for ebook conversion, returning"- + " original PDF",- e);- Files.write(tempOut.getPath(), pdfBytes);+ TempFile tempOut = null;+ try {+ tempOut = tempFileManager.createManagedTempFile(".pdf");+ if (optimizeForEbook) {+ byte[] pdfBytes = Files.readAllBytes(outputPath);+ try {+ byte[] optimizedPdf = GeneralUtils.optimizePdfWithGhostscript(pdfBytes);+ Files.write(tempOut.getPath(), optimizedPdf);+ } catch (IOException e) {+ log.warn(+ "Ghostscript optimization failed for ebook conversion, returning"+ + " original PDF",+ e);+ Files.write(tempOut.getPath(), pdfBytes);+ }+ } else {+ try (PDDocument document = pdfDocumentFactory.load(outputPath.toFile())) {+ document.save(tempOut.getFile());+ }}- } else {- try (PDDocument document = pdfDocumentFactory.load(outputPath.toFile())) {- document.save(tempOut.getFile());+ ResponseEntity<Resource> response =+ WebResponseUtils.pdfFileToWebResponse(tempOut, outputFilename);+ tempOut = null;+ return response;+ } catch (Exception e) {+ if (tempOut != null) {+ tempOut.close();}+ throw e;}- ResponseEntity<Resource> response =- WebResponseUtils.pdfFileToWebResponse(tempOut, outputFilename);- tempOut = null;- return response;- } catch (Exception e) {- if (tempOut != null) {- tempOut.close();- }- throw e;} finally {cleanupTempFiles(workingDirectory, inputPath, outputPath);}@@ -194,7 +198,7 @@ public class ConvertEbookToPDFController {boolean includeTableOfContents,boolean includePageNumbers) {List<String> command = new ArrayList<>();- command.add("ebook-convert");+ command.add(runtimePathConfig.getCalibrePath());command.add(inputPath.toString());command.add(outputPath.toString());diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertOfficeController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertOfficeController.javaindex cdd43afabe..8d5ce09fd5 100644--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertOfficeController.java+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertOfficeController.java@@ -92,17 +92,37 @@ public class ConvertOfficeController {baseName = "input";}- // create temporary working directory+ // The caller deletes it on success: the returned PDF lives in it.Path workDir = Files.createTempDirectory("office2pdf_");+ boolean converted = false;+ try {+ File pdf =+ convertInWorkDir(+ inputFile, useStirlingOfficeConvert, extensionLower, baseName, workDir);+ converted = true;+ return pdf;+ } finally {+ if (!converted) {+ FileUtils.deleteQuietly(workDir.toFile());+ }+ }+ }++ private File convertInWorkDir(+ MultipartFile inputFile,+ Boolean useStirlingOfficeConvert,+ String extensionLower,+ String baseName,+ Path workDir)+ throws IOException, InterruptedException {Path inputPath = workDir.resolve(baseName + "." + extensionLower);Path outputPath = workDir.resolve(baseName + ".pdf");if (officeToPdfService.handles(extensionLower, useStirlingOfficeConvert)) {- if (convertInProcess(inputFile, extensionLower, workDir, inputPath, outputPath)) {+ if (convertInProcess(inputFile, extensionLower, inputPath, outputPath)) {return outputPath.toFile();}} else if (!officeConversionService.libreOfficeAvailable()) {- FileUtils.deleteQuietly(workDir.toFile());throw ExceptionUtils.createLibreOfficeRequiredException(extensionLower);}@@ -221,33 +241,20 @@ public class ConvertOfficeController {/** False when LibreOffice should retry the file; the original upload is converted as is. */private boolean convertInProcess(- MultipartFile inputFile,- String extension,- Path workDir,- Path inputPath,- Path outputPath)+ MultipartFile inputFile, String extension, Path inputPath, Path outputPath)throws IOException {- try {- // Same sanitizing and ZIP budget as the LibreOffice path; a refused file never falls- // back.- if (officeDocumentSanitizer.isSanitizableExtension(extension)) {- Files.write(- inputPath,- officeDocumentSanitizer.sanitize(inputFile.getBytes(), extension));- } else {- Files.copy(- inputFile.getInputStream(), inputPath, StandardCopyOption.REPLACE_EXISTING);- }- } catch (IOException | RuntimeException e) {- FileUtils.deleteQuietly(workDir.toFile());- throw e;+ // Same sanitizing and ZIP budget as the LibreOffice path; a refused file never falls back.+ if (officeDocumentSanitizer.isSanitizableExtension(extension)) {+ Files.write(+ inputPath, officeDocumentSanitizer.sanitize(inputFile.getBytes(), extension));+ } else {+ Files.copy(inputFile.getInputStream(), inputPath, StandardCopyOption.REPLACE_EXISTING);}try {officeToPdfService.convert(inputPath, outputPath);return true;} catch (IOException | RuntimeException e) {if (!officeToPdfService.canFallBack(e)) {- FileUtils.deleteQuietly(workDir.toFile());throw e;}log.warn(diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToEpubController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToEpubController.javaindex 0788402480..40fa359a3e 100644--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToEpubController.java+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToEpubController.java@@ -27,6 +27,7 @@ import stirling.software.SPDF.model.api.converters.ConvertPdfToEpubRequest.Outpuimport stirling.software.SPDF.model.api.converters.ConvertPdfToEpubRequest.TargetDevice;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.tool.ToolFormat;import stirling.software.common.model.tool.ToolIO;@@ -51,19 +52,23 @@ public class ConvertPDFToEpubController {private final TempFileManager tempFileManager;private final EndpointConfiguration endpointConfiguration;+ private final RuntimePathConfig runtimePathConfig;- private static List<String> buildCalibreCommand(+ private List<String> buildCalibreCommand(Path inputPath, Path outputPath, boolean detectChapters, TargetDevice targetDevice) {List<String> command = new ArrayList<>();- command.add("ebook-convert");+ command.add(runtimePathConfig.getCalibrePath());command.add(inputPath.toString());command.add(outputPath.toString());- // Use pdftohtml engine (poppler) for PDF input instead of calibre's Qt-based engine.- // This avoids the Qt WebEngine dependency for PDF parsing and uses the lighter- // poppler-utils pdftohtml binary which is already available in the container.+ // Calibre's own engine reads pdftohtml's XML output, so no Qt WebEngine is involved in+ // parsing. Header and footer detection is off: it fails on some short documents.command.add("--pdf-engine");- command.add("pdftohtml");+ command.add("calibre");+ command.add("--pdf-header-skip");+ command.add("0");+ command.add("--pdf-footer-skip");+ command.add("0");// Golden defaultscommand.add("--enable-heuristics");diff --git a/app/core/src/main/resources/static/python/calibre_sandbox.py b/app/core/src/main/resources/static/python/calibre_sandbox.pyindex 66ebf11422..23a7b80850 100644--- a/app/core/src/main/resources/static/python/calibre_sandbox.py+++ b/app/core/src/main/resources/static/python/calibre_sandbox.py@@ -1,3 +1,9 @@+"""Runs a command confined to one working directory with Landlock and seccomp.++Linux only (5.13+). Where the sandbox cannot be applied, including every non-Linux host, it exits+125 instead of running the command unconfined.+"""+import ctypesimport errnoimport os@@ -77,7 +83,8 @@ ARCHITECTURES = {}NR_IO_URING_SETUP, NR_IO_URING_ENTER, NR_IO_URING_REGISTER = 425, 426, 427-libc = ctypes.CDLL(None, use_errno=True)+LINUX = sys.platform.startswith("linux")+libc = ctypes.CDLL(None, use_errno=True) if LINUX else Noneclass RulesetAttr(ctypes.Structure):@@ -204,17 +211,18 @@ def main():print("usage: calibre_sandbox.py <working directory> <command...>", file=sys.stderr)return 2work_dir, command = sys.argv[1], sys.argv[2:]- required = os.environ.get("STIRLING_CALIBRE_SANDBOX") == "required"++ if not LINUX:+ print("calibre-sandbox: Landlock and seccomp need Linux, refusing to run", file=sys.stderr)+ return 125call(libc.prctl, PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0)if not confine_file_system(work_dir):- print("calibre-sandbox: landlock unavailable, filesystem unconfined", file=sys.stderr)- if required:- return 125+ print("calibre-sandbox: landlock unavailable, refusing to run", file=sys.stderr)+ return 125if not confine_network():- print("calibre-sandbox: seccomp unavailable, network unconfined", file=sys.stderr)- if required:- return 125+ print("calibre-sandbox: seccomp unavailable, refusing to run", file=sys.stderr)+ return 125os.execvp(command[0], command)diff --git a/app/core/src/test/java/stirling/software/SPDF/config/ExternalAppDepConfigMoreTest.java b/app/core/src/test/java/stirling/software/SPDF/config/ExternalAppDepConfigMoreTest.javaindex 510a357358..90b0b83c75 100644--- a/app/core/src/test/java/stirling/software/SPDF/config/ExternalAppDepConfigMoreTest.java+++ b/app/core/src/test/java/stirling/software/SPDF/config/ExternalAppDepConfigMoreTest.java@@ -30,11 +30,14 @@ import org.junit.jupiter.api.Test;import org.junit.jupiter.api.extension.ExtendWith;import org.mockito.Mock;import org.mockito.MockedConstruction;+import org.mockito.MockedStatic;+import org.mockito.Mockito;import org.mockito.junit.jupiter.MockitoExtension;import org.mockito.junit.jupiter.MockitoSettings;import org.mockito.quality.Strictness;import stirling.software.common.configuration.RuntimePathConfig;+import stirling.software.common.util.ProcessExecutor;/*** Covers the process-probing paths of ExternalAppDepConfig by intercepting ProcessBuilder@@ -239,6 +242,54 @@ class ExternalAppDepConfigMoreTest {}}+ @Nested+ @DisplayName("disableCalibreUnlessConfined")+ class DisableCalibreUnlessConfined {++ private void sandboxUsable(boolean usable) throws Exception {+ try (MockedStatic<ProcessExecutor> executor =+ Mockito.mockStatic(ProcessExecutor.class)) {+ executor.when(() -> ProcessExecutor.isCalibreSandboxUsable(any()))+ .thenReturn(usable);+ invoke("disableCalibreUnlessConfined", new Class<?>[] {});+ }+ }++ @Test+ @DisplayName("disables Calibre when its sandbox cannot be applied")+ void disablesWhenUnconfined() throws Exception {+ when(endpointConfiguration.isGroupEnabled("Calibre")).thenReturn(true);++ sandboxUsable(false);++ verify(endpointConfiguration)+ .disableGroup("Calibre", EndpointConfiguration.DisableReason.DEPENDENCY);+ }++ @Test+ @DisplayName("keeps Calibre when its sandbox is active")+ void keepsWhenConfined() throws Exception {+ when(endpointConfiguration.isGroupEnabled("Calibre")).thenReturn(true);++ sandboxUsable(true);++ verify(endpointConfiguration, never()).disableGroup(anyString(), any());+ }++ @Test+ @DisplayName("does not probe when Calibre is already disabled")+ void skipsProbeWhenAlreadyDisabled() throws Exception {+ when(endpointConfiguration.isGroupEnabled("Calibre")).thenReturn(false);+ try (MockedStatic<ProcessExecutor> executor =+ Mockito.mockStatic(ProcessExecutor.class)) {+ invoke("disableCalibreUnlessConfined", new Class<?>[] {});++ executor.verifyNoInteractions();+ }+ verify(endpointConfiguration, never()).disableGroup(anyString(), any());+ }+ }+/*** checkDependencyAndDisableGroup is tested directly (single-threaded). The public* checkDependencies() fans probes out over virtual threads where Mockito's thread-confineddiff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertEbookToPDFControllerTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertEbookToPDFControllerTest.javaindex 57205dd0d3..bc77b727da 100644--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertEbookToPDFControllerTest.java+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertEbookToPDFControllerTest.java@@ -39,6 +39,7 @@ import org.springframework.mock.web.MockMultipartFile;import stirling.software.SPDF.config.EndpointConfiguration;import stirling.software.SPDF.model.api.converters.ConvertEbookToPdfRequest;+import stirling.software.common.configuration.RuntimePathConfig;import stirling.software.common.service.CustomPDFDocumentFactory;import stirling.software.common.util.GeneralUtils;import stirling.software.common.util.OfficeDocumentSanitizer;@@ -67,11 +68,15 @@ class ConvertEbookToPDFControllerTest {@Mock private TempFileManager tempFileManager;@Mock private EndpointConfiguration endpointConfiguration;@Mock private OfficeDocumentSanitizer officeDocumentSanitizer;+ @Mock private RuntimePathConfig runtimePathConfig;++ private static final String CALIBRE_PATH = "/opt/calibre/ebook-convert";@InjectMocks private ConvertEbookToPDFController controller;@BeforeEachvoid setUp() throws Exception {+ lenient().when(runtimePathConfig.getCalibrePath()).thenReturn(CALIBRE_PATH);lenient().when(tempFileManager.createManagedTempFile(anyString())).thenAnswer(@@ -162,7 +167,7 @@ class ConvertEbookToPDFControllerTest {List<String> command = commandCaptor.getValue();assertEquals(6, command.size());- assertEquals("ebook-convert", command.get(0));+ assertEquals(CALIBRE_PATH, command.get(0));assertEquals(expectedInput.toString(), command.get(1));assertEquals(expectedOutput.toString(), command.get(2));assertEquals("--embed-all-fonts", command.get(3));@@ -328,6 +333,33 @@ class ConvertEbookToPDFControllerTest {}assertArrayEquals(sanitized, seenByCalibre.get());+ Mockito.verify(tempFileManager).deleteTempDirectory(workingDir);+ }++ @Test+ void convertEbookToPdf_rejectedDocxLeavesNoWorkDir() throws Exception {+ when(endpointConfiguration.isGroupEnabled("Calibre")).thenReturn(true);+ byte[] uploaded = "docx".getBytes(StandardCharsets.UTF_8);+ when(officeDocumentSanitizer.isSanitizableExtension("docx")).thenReturn(true);+ when(officeDocumentSanitizer.sanitize(uploaded, "docx"))+ .thenThrow(new IOException("part could not be sanitized"));++ ConvertEbookToPdfRequest request = new ConvertEbookToPdfRequest();+ request.setFileInput(+ new MockMultipartFile("fileInput", "book.docx", "application/zip", uploaded));++ Path workingDir = Files.createTempDirectory("ebook-convert-reject-test-");+ when(tempFileManager.createTempDirectory()).thenReturn(workingDir);++ try (MockedStatic<ProcessExecutor> pe = Mockito.mockStatic(ProcessExecutor.class)) {+ assertThrows(IOException.class, () -> controller.convertEbookToPdf(request));++ pe.verifyNoInteractions();+ } finally {+ deleteRecursively(workingDir);+ }++ Mockito.verify(tempFileManager).deleteTempDirectory(workingDir);}@Testdiff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertOfficeControllerTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertOfficeControllerTest.javaindex a4c28305c5..ec713ccfc7 100644--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertOfficeControllerTest.java+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertOfficeControllerTest.java@@ -15,7 +15,9 @@ import java.lang.reflect.Method;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;+import java.util.HashSet;import java.util.List;+import java.util.Set;import org.apache.pdfbox.pdmodel.PDDocument;import org.apache.pdfbox.pdmodel.PDPage;@@ -238,6 +240,71 @@ class ConvertOfficeControllerTest {}}+ @Test+ @DisplayName("a file the sanitizer refuses on the LibreOffice path leaves no work dir")+ void refusedBySanitizerLeavesNoWorkDir() throws Exception {+ when(officeToPdfService.handles("docx", null)).thenReturn(false);+ when(officeConversionService.libreOfficeAvailable()).thenReturn(true);+ when(officeDocumentSanitizer.isSanitizableExtension("docx")).thenReturn(true);+ when(officeDocumentSanitizer.sanitize(any(byte[].class), anyString()))+ .thenThrow(new IOException("part could not be sanitized"));+ Set<Path> before = officeWorkDirs();++ assertThatThrownBy(() -> controller.convertToPdf(docxFile("x".getBytes())))+ .isInstanceOf(IOException.class);++ assertThat(officeWorkDirs()).isEqualTo(before);+ }++ @Test+ @DisplayName("an unchecked failure before conversion leaves no work dir")+ void uncheckedFailureLeavesNoWorkDir() throws Exception {+ when(officeDocumentSanitizer.isSanitizableExtension("docx")).thenReturn(true);+ when(officeDocumentSanitizer.sanitize(any(byte[].class), anyString()))+ .thenThrow(new SecurityException("unsafe entry"));+ Set<Path> before = officeWorkDirs();++ when(officeToPdfService.handles("docx", null)).thenReturn(false);+ assertThatThrownBy(() -> controller.convertToPdf(docxFile("x".getBytes())))+ .isInstanceOf(SecurityException.class);+ when(officeToPdfService.handles("docx", null)).thenReturn(true);+ assertThatThrownBy(() -> controller.convertToPdf(docxFile("x".getBytes())))+ .isInstanceOf(SecurityException.class);++ assertThat(officeWorkDirs()).isEqualTo(before);+ }++ @Test+ @DisplayName("a failed LibreOffice run leaves no work dir")+ void failedLibreOfficeRunLeavesNoWorkDir() throws Exception {+ when(endpointConfiguration.isGroupEnabled("Unoconvert")).thenReturn(false);+ when(officeDocumentSanitizer.isSanitizableExtension("docx")).thenReturn(true);+ when(officeDocumentSanitizer.sanitize(any(byte[].class), anyString()))+ .thenAnswer(inv -> inv.getArgument(0));+ Set<Path> before = officeWorkDirs();++ try (MockedStatic<ProcessExecutor> pe = Mockito.mockStatic(ProcessExecutor.class)) {+ ProcessExecutorResult result = mockExecutor(pe, 3);+ ProcessExecutor executor = ProcessExecutor.getInstance(Processes.LIBRE_OFFICE);+ when(executor.runCommandWithOutputHandling(any(List.class))).thenReturn(result);++ assertThatThrownBy(() -> controller.convertToPdf(docxFile("docx".getBytes())))+ .isInstanceOf(IllegalStateException.class);+ }++ assertThat(officeWorkDirs()).isEqualTo(before);+ }++ private Set<Path> officeWorkDirs() throws IOException {+ try (var dirs =+ Files.newDirectoryStream(+ Path.of(System.getProperty("java.io.tmpdir")), "office2pdf_*")) {+ Set<Path> found = new HashSet<>();+ dirs.forEach(found::add);+ return found;+ }+ }+@Test@DisplayName("retries with LibreOffice when the in-process conversion fails")void fallsBackToLibreOffice() throws Exception {diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToEpubControllerTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToEpubControllerTest.javaindex 523989e2e9..c4aa4002b4 100644--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToEpubControllerTest.java+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToEpubControllerTest.java@@ -40,6 +40,7 @@ import stirling.software.SPDF.config.EndpointConfiguration;import stirling.software.SPDF.model.api.converters.ConvertPdfToEpubRequest;import stirling.software.SPDF.model.api.converters.ConvertPdfToEpubRequest.OutputFormat;import stirling.software.SPDF.model.api.converters.ConvertPdfToEpubRequest.TargetDevice;+import stirling.software.common.configuration.RuntimePathConfig;import stirling.software.common.util.GeneralUtils;import stirling.software.common.util.ProcessExecutor;import stirling.software.common.util.ProcessExecutor.ProcessExecutorResult;@@ -65,11 +66,15 @@ class ConvertPDFToEpubControllerTest {@Mock private TempFileManager tempFileManager;@Mock private EndpointConfiguration endpointConfiguration;+ @Mock private RuntimePathConfig runtimePathConfig;++ private static final String CALIBRE_PATH = "/opt/calibre/ebook-convert";@InjectMocks private ConvertPDFToEpubController controller;@BeforeEachvoid setUp() throws Exception {+ lenient().when(runtimePathConfig.getCalibrePath()).thenReturn(CALIBRE_PATH);lenient().when(tempFileManager.createManagedTempFile(anyString())).thenAnswer(@@ -147,12 +152,14 @@ class ConvertPDFToEpubControllerTest {ResponseEntity<Resource> response = controller.convertPdfToEpub(request);List<String> command = commandCaptor.getValue();- assertEquals(13, command.size());- assertEquals("ebook-convert", command.get(0));+ assertEquals(17, command.size());+ assertEquals(CALIBRE_PATH, command.get(0));assertEquals(expectedInput.toString(), command.get(1));assertEquals(expectedOutput.toString(), command.get(2));assertTrue(command.contains("--pdf-engine"));- assertTrue(command.contains("pdftohtml"));+ assertTrue(command.contains("calibre"));+ assertEquals("0", command.get(command.indexOf("--pdf-header-skip") + 1));+ assertEquals("0", command.get(command.indexOf("--pdf-footer-skip") + 1));assertTrue(command.contains("--enable-heuristics"));assertTrue(command.contains("--insert-blank-line"));assertTrue(command.contains("--filter-css"));@@ -243,7 +250,7 @@ class ConvertPDFToEpubControllerTest {assertTrue(command.contains("--output-profile"));assertTrue(command.contains(TargetDevice.KINDLE_EINK_TEXT.getCalibreProfile()));assertTrue(command.contains("--pdf-engine"));- assertTrue(command.contains("pdftohtml"));+ assertTrue(command.contains("calibre"));assertTrue(command.contains("--filter-css"));assertTrue(command.contains(@@ -324,11 +331,11 @@ class ConvertPDFToEpubControllerTest {ResponseEntity<Resource> response = controller.convertPdfToEpub(request);List<String> command = commandCaptor.getValue();- assertEquals("ebook-convert", command.get(0));+ assertEquals(CALIBRE_PATH, command.get(0));assertEquals(expectedInput.toString(), command.get(1));assertEquals(expectedOutput.toString(), command.get(2));assertTrue(command.contains("--pdf-engine"));- assertTrue(command.contains("pdftohtml"));+ assertTrue(command.contains("calibre"));assertTrue(command.contains("--enable-heuristics"));assertTrue(command.contains("--insert-blank-line"));assertTrue(command.contains("--filter-css"));diff --git a/app/core/src/test/java/stirling/software/SPDF/util/CalibreSandboxScriptOffLinuxTest.java b/app/core/src/test/java/stirling/software/SPDF/util/CalibreSandboxScriptOffLinuxTest.javanew file mode 100644index 0000000000..756615a447--- /dev/null+++ b/app/core/src/test/java/stirling/software/SPDF/util/CalibreSandboxScriptOffLinuxTest.java@@ -0,0 +1,72 @@+package stirling.software.SPDF.util;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertTrue;+import static org.junit.jupiter.api.Assumptions.assumeTrue;++import java.nio.charset.StandardCharsets;+import java.nio.file.Files;+import java.nio.file.Path;+import java.util.ArrayList;+import java.util.List;+import java.util.concurrent.TimeUnit;++import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.DisplayName;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.condition.DisabledOnOs;+import org.junit.jupiter.api.condition.OS;+import org.junit.jupiter.api.io.TempDir;++import stirling.software.common.util.CheckProgramInstall;+import stirling.software.common.util.GeneralUtils;++@DisabledOnOs(OS.LINUX)+class CalibreSandboxScriptOffLinuxTest {++ @TempDir Path workDir;++ private String python;+ private Path launcher;++ @BeforeEach+ void requirePython() throws Exception {+ python = CheckProgramInstall.getAvailablePythonCommand();+ assumeTrue(python != null, "python is not installed");+ launcher = GeneralUtils.extractScript("calibre_sandbox.py").toAbsolutePath();+ }++ private record Run(int exitCode, String stderr, boolean commandRan) {}++ private Run launch() throws Exception {+ Path marker = workDir.resolve("ran");+ Files.deleteIfExists(marker);+ String job = "import pathlib, sys; pathlib.Path(sys.argv[1]).touch()";+ List<String> command =+ new ArrayList<>(List.of(python, "-I", launcher.toString(), workDir.toString()));+ command.addAll(List.of(python, "-I", "-c", job, marker.toString()));+ Path stderr = workDir.resolve("stderr");+ ProcessBuilder builder = new ProcessBuilder(command).directory(workDir.toFile());+ builder.redirectOutput(ProcessBuilder.Redirect.DISCARD).redirectError(stderr.toFile());+ Process process = builder.start();+ if (!process.waitFor(60, TimeUnit.SECONDS)) {+ process.destroyForcibly();+ throw new IllegalStateException("launcher did not finish");+ }+ return new Run(+ process.exitValue(),+ Files.readString(stderr, StandardCharsets.UTF_8),+ Files.exists(marker));+ }++ @Test+ @DisplayName("refuses with the launcher's exit code and runs nothing")+ void refuses() throws Exception {+ Run run = launch();++ assertEquals(125, run.exitCode());+ assertTrue(run.stderr().startsWith("calibre-sandbox:"));+ assertFalse(run.commandRan());+ }+}diff --git a/app/core/src/test/java/stirling/software/SPDF/util/CalibreSandboxScriptTest.java b/app/core/src/test/java/stirling/software/SPDF/util/CalibreSandboxScriptTest.javaindex 912ffdf597..c68fd308c1 100644--- a/app/core/src/test/java/stirling/software/SPDF/util/CalibreSandboxScriptTest.java+++ b/app/core/src/test/java/stirling/software/SPDF/util/CalibreSandboxScriptTest.java@@ -46,7 +46,6 @@ class CalibreSandboxScriptTest {new ArrayList<>(List.of("python3", "-I", launcher.toString(), workDir.toString()));full.addAll(List.of(command));ProcessBuilder builder = new ProcessBuilder(full).directory(workDir.toFile());- builder.environment().put("STIRLING_CALIBRE_SANDBOX", "required");builder.redirectErrorStream(true).redirectOutput(ProcessBuilder.Redirect.DISCARD);Process process = builder.start();if (!process.waitFor(60, TimeUnit.SECONDS)) {diff --git a/docker/base/Dockerfile b/docker/base/Dockerfileindex 5899be18ef..159e034dfe 100644--- a/docker/base/Dockerfile+++ b/docker/base/Dockerfile@@ -40,7 +40,7 @@ RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \rm /tmp/calibre.txz; \\# We only need Qt6 WebEngine (Chromium) for ebook->PDF output.- # PDF INPUT now uses the pdftohtml engine (poppler), not Qt.+ # PDF input is parsed through pdftohtml, not Qt.rm -f /opt/calibre/lib/libQt6Designer* \/opt/calibre/lib/libQt6Multimedia* \/opt/calibre/lib/libQt6SpatialAudio.so.* \@@ -253,7 +253,6 @@ RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \/opt/calibre/ebook-convert /tmp/test.txt /tmp/test.epub; \rm -f /tmp/test.txt /tmp/test.epub; \\- # Verify pdftohtml (poppler) is available for the pdftohtml PDF engine.pdftohtml -v >/dev/null 2>&1 && echo "pdftohtml OK" || { echo "ERROR: pdftohtml not found"; exit 1; }; \echo "=== Calibre stripped successfully ==="