Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

fix(security): bound the ODT export's pandoc subprocess (#6542)

LearningCircuit2ced973aa85c
diff --git a/changelog.d/6542.security.md b/changelog.d/6542.security.md
new file mode 100644
index 0000000000..7ae29bc9ef
--- /dev/null
+++ b/changelog.d/6542.security.md
@@ -0,0 +1 @@
+ODT exports now run their pandoc conversion under a 120-second timeout and a 1 GiB GHC heap cap, reject pandoc output larger than 512 MiB (checked after the output has been captured), and log only the last 2,000 characters of pandoc's error output; previously a pathological report could hang the export worker or leak report content through unbounded pandoc stderr. On pandoc 2.15 or newer the conversion also runs with `--sandbox`, which stops pandoc from reading local files or fetching network resources referenced in report markdown (closing a local-file-read and server-side request forgery path); as a consequence, remote images referenced in a report are no longer embedded in its ODT export. If sandbox support is unavailable or cannot be verified, or the pandoc build rejects the heap-cap flags, export fails instead of processing the report without these bounds.
diff --git a/src/local_deep_research/exporters/odt_exporter.py b/src/local_deep_research/exporters/odt_exporter.py
index 74c4333fa8..ca1b5e0a2e 100644
--- a/src/local_deep_research/exporters/odt_exporter.py
+++ b/src/local_deep_research/exporters/odt_exporter.py
@@ -8,6 +8,7 @@ markdown features natively. Note: Requires Pandoc to be installed on the
system or use pypandoc_binary which bundles it.
"""
+import functools
import subprocess
from typing import Optional
@@ -41,6 +42,35 @@ class ODTExporter(BaseExporter):
to pandoc's stdin and capturing ODT output from stdout.
"""
+ #: Conversion wall clock; a pathological report must not pin an
+ #: export worker indefinitely.
+ DEFAULT_CONVERSION_TIMEOUT_S = 120
+ #: Output-size ceiling, checked after pandoc's stdout has been
+ #: captured in full, so it rejects oversized output rather than
+ #: bounding capture memory. The ODT of a maximum-size report stays
+ #: far below this.
+ DEFAULT_MAX_OUTPUT_BYTES = 512 * 1024 * 1024
+ #: The bundled pandoc accepts GHC RTS heap limits. Other builds that
+ #: reject RTS flags fail the conversion rather than running uncapped.
+ DEFAULT_MAX_HEAP_MB = 1024
+
+ def __init__(
+ self,
+ *,
+ conversion_timeout_s: int = DEFAULT_CONVERSION_TIMEOUT_S,
+ max_output_bytes: int = DEFAULT_MAX_OUTPUT_BYTES,
+ max_heap_mb: int = DEFAULT_MAX_HEAP_MB,
+ ):
+ if not isinstance(max_heap_mb, int) or not (
+ 0 < max_heap_mb <= self.DEFAULT_MAX_HEAP_MB
+ ):
+ raise ValueError(
+ f"max_heap_mb must be between 1 and {self.DEFAULT_MAX_HEAP_MB}"
+ )
+ self._conversion_timeout_s = conversion_timeout_s
+ self._max_output_bytes = max_output_bytes
+ self._max_heap_mb = max_heap_mb
+
@property
def format_name(self) -> str:
return "odt"
@@ -53,6 +83,21 @@ class ODTExporter(BaseExporter):
def mimetype(self) -> str:
return "application/vnd.oasis.opendocument.text"
+ @staticmethod
+ @functools.lru_cache(maxsize=1)
+ def _pandoc_supports_sandbox() -> bool:
+ """Whether pandoc knows ``--sandbox`` (added in pandoc 2.15, 2021).
+
+ Cached: the check spawns a pandoc --version subprocess, and
+ exports are rare enough that one probe per process is plenty.
+ Raises if the version cannot be determined; lru_cache does not
+ cache exceptions, so a transient probe failure is retried on the
+ next export instead of disabling the sandbox for the process.
+ """
+ version = str(pypandoc.get_pandoc_version()).strip()
+ parts = tuple(int(x) for x in version.split(".")[:2])
+ return parts >= (2, 15)
+
def export(
self,
markdown_content: str,
@@ -114,17 +159,58 @@ class ODTExporter(BaseExporter):
# Convert in memory: pipe markdown via stdin, capture ODT from stdout
pandoc_path = pypandoc.get_pandoc_path()
- cmd = [pandoc_path, "-f", "markdown", "-t", "odt", "-o", "-"]
+ # --sandbox keeps pandoc from reading local files or fetching
+ # network resources referenced in the (web-influenced) report
+ # markdown. Refuse the export if its support cannot be verified:
+ # running without the flag would restore arbitrary file reads
+ # and SSRF through markdown image references.
+ try:
+ supports_sandbox = self._pandoc_supports_sandbox()
+ except Exception as exc:
+ logger.warning(
+ "Could not verify pandoc sandbox support ({})",
+ type(exc).__name__,
+ )
+ raise RuntimeError(
+ "ODT export requires pandoc 2.15 or newer with --sandbox"
+ ) from None
+ if not supports_sandbox:
+ raise RuntimeError( # noqa: TRY301 — fail closed before subprocess
+ "ODT export requires pandoc 2.15 or newer with --sandbox"
+ )
+ # A report far below BaseExporter.MAX_CONTENT_SIZE can make
+ # pandoc consume several GiB. The shipped GHC build honours
+ # -M; builds without RTS support reject the command before
+ # processing markdown, and we never retry without the cap.
+ cmd = [
+ pandoc_path,
+ "+RTS",
+ f"-M{self._max_heap_mb}m",
+ "-RTS",
+ "--sandbox",
+ ]
+ cmd.extend(["-f", "markdown", "-t", "odt", "-o", "-"])
cmd.extend(extra_args)
- result = subprocess.run(
- cmd,
- input=content_with_footer.encode("utf-8"),
- capture_output=True,
- check=True,
- )
+ try:
+ result = subprocess.run(
+ cmd,
+ input=content_with_footer.encode("utf-8"),
+ capture_output=True,
+ check=True,
+ timeout=self._conversion_timeout_s,
+ )
+ except subprocess.TimeoutExpired as exc:
+ raise RuntimeError(
+ f"ODT export timed out after {self._conversion_timeout_s}s"
+ ) from exc
odt_bytes = result.stdout
+ if len(odt_bytes) > self._max_output_bytes:
+ raise RuntimeError( # noqa: TRY301 — same pattern as the no-output raise below
+ "ODT export output is larger than "
+ f"{self._max_output_bytes} bytes"
+ )
if not odt_bytes:
raise RuntimeError( # noqa: TRY301 — except only adds logging before re-raise
@@ -144,12 +230,15 @@ class ODTExporter(BaseExporter):
)
except subprocess.CalledProcessError as e:
- stderr = (
+ # pandoc's stderr quotes input lines — i.e. report content.
+ # Bound what reaches logs and error surfaces.
+ stderr_full = (
e.stderr.decode("utf-8", errors="replace")
if e.stderr
else "unknown error"
)
- logger.exception(f"Pandoc conversion failed: {stderr}")
+ stderr = stderr_full[-2000:]
+ logger.exception("Pandoc conversion failed: {}", stderr)
raise RuntimeError(f"Pandoc conversion failed: {stderr}") from e
except Exception:
logger.exception("Error generating ODT")
diff --git a/tests/exporters/conftest.py b/tests/exporters/conftest.py
index 279a937d9e..53afb5dfce 100644
--- a/tests/exporters/conftest.py
+++ b/tests/exporters/conftest.py
@@ -2,6 +2,20 @@
import pytest
+from local_deep_research.exporters.odt_exporter import ODTExporter
+
+
[email protected](autouse=True)
+def _clear_odt_sandbox_probe_cache():
+ """``ODTExporter._pandoc_supports_sandbox`` is lru_cached per
+ process. Clear it around every exporter test so no result depends
+ on which test (real pandoc or a mocked ``pypandoc``) probed first.
+ """
+ probe = ODTExporter._pandoc_supports_sandbox
+ probe.cache_clear()
+ yield
+ probe.cache_clear()
+
@pytest.fixture
def sample_markdown():
diff --git a/tests/exporters/test_odt_export_pandoc_bounds.py b/tests/exporters/test_odt_export_pandoc_bounds.py
new file mode 100644
index 0000000000..e080747c45
--- /dev/null
+++ b/tests/exporters/test_odt_export_pandoc_bounds.py
@@ -0,0 +1,356 @@
+"""Bounds for the ODT export's pandoc subprocess.
+
+The ODT exporter pipes the user's report markdown into a pandoc
+subprocess: ``subprocess.run(cmd, input=..., capture_output=True,
+check=True)`` with **no timeout** and **unbounded captured stdout**,
+and it logs the *full* pandoc stderr on failure — which quotes input
+lines, i.e. report content. A pathological report can pin an export
+worker indefinitely, and file and URL references in the markdown are
+resolved by pandoc (local reads, network fetches) unless sandboxed.
+
+These contracts pin: a wall-clock timeout that reaches the subprocess,
+typed failure on hang, an output-size ceiling, a sandboxed argv with a
+GHC heap cap, refusal when sandbox support is unavailable or unknown,
+and truncated stderr in both the raised error and the log call.
+"""
+
+from __future__ import annotations
+
+import io
+import subprocess
+import threading
+import zipfile
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+
+import pytest
+
+from local_deep_research.exporters.odt_exporter import ODTExporter
+
+
[email protected](autouse=True)
+def _fresh_sandbox_probe():
+ """The version probe is lru_cached per process; never let a value
+ cached by one test (or another module's pypandoc mock) leak."""
+ cached_probe = ODTExporter._pandoc_supports_sandbox
+ cached_probe.cache_clear()
+ yield
+ cached_probe.cache_clear()
+
+
+class _RecordingLogger:
+ def __init__(self):
+ self.calls: list[tuple[str, tuple, dict]] = []
+
+ def __getattr__(self, level):
+ def record(*args, **kwargs):
+ self.calls.append((level, args, kwargs))
+
+ return record
+
+ def rendered(self, level: str) -> list[str]:
+ return [
+ " ".join(str(a) for a in args)
+ for lvl, args, _ in self.calls
+ if lvl == level
+ ]
+
+
+def _patched_logger(monkeypatch) -> _RecordingLogger:
+ from local_deep_research.exporters import odt_exporter as mod
+
+ recorder = _RecordingLogger()
+ monkeypatch.setattr(mod, "logger", recorder)
+ return recorder
+
+
+def _exporter() -> ODTExporter:
+ return ODTExporter()
+
+
+def _patched_run(monkeypatch, **behavior):
+ from local_deep_research.exporters import odt_exporter as mod
+
+ recorded: dict = {}
+
+ def fake_run(cmd, **kwargs):
+ recorded.update(kwargs)
+ recorded["cmd"] = cmd
+ if "raise_timeout" in behavior:
+ raise subprocess.TimeoutExpired(cmd, kwargs.get("timeout", 0))
+ if "raise_called" in behavior:
+ raise subprocess.CalledProcessError(
+ 1, cmd, stderr=behavior["raise_called"]
+ )
+ return subprocess.CompletedProcess(
+ cmd, 0, stdout=behavior.get("stdout", b"PK-odt-bytes")
+ )
+
+ monkeypatch.setattr(mod.subprocess, "run", fake_run)
+ monkeypatch.setattr(mod, "PYPANDOC_AVAILABLE", True)
+ monkeypatch.setattr(
+ mod.pypandoc, "get_pandoc_path", lambda: "/usr/bin/pandoc"
+ )
+ return recorded
+
+
+class TestPandocBounds:
+ def test_the_timeout_reaches_the_subprocess(self, monkeypatch):
+ recorded = _patched_run(monkeypatch)
+
+ try:
+ _exporter().export("# T\n\nbody")
+ except RuntimeError:
+ pass # the fake's output may fail later checks; shape first
+
+ assert recorded.get("timeout") is not None and (
+ recorded["timeout"] >= 30
+ ), f"pandoc runs without a wall-clock timeout: {recorded}"
+
+ def test_hang_surfaces_as_typed_error(self, monkeypatch):
+ _patched_run(monkeypatch, raise_timeout=True)
+
+ with pytest.raises(RuntimeError) as excinfo:
+ _exporter().export("# T\n\nbody")
+
+ assert "timed out" in str(excinfo.value).lower()
+
+ def test_runaway_stdout_is_refused(self, monkeypatch):
+ _patched_run(monkeypatch, stdout=b"\x00" * 1000)
+
+ with pytest.raises(RuntimeError) as excinfo:
+ ODTExporter(max_output_bytes=100).export("# T\n\nbody")
+
+ assert "larger than" in str(excinfo.value).lower()
+
+ def test_pandoc_argv_is_sandboxed_when_supported(self, monkeypatch):
+ recorded = _patched_run(monkeypatch)
+ monkeypatch.setattr(
+ ODTExporter,
+ "_pandoc_supports_sandbox",
+ staticmethod(lambda: True),
+ )
+
+ try:
+ _exporter().export("# T\n\nbody")
+ except RuntimeError:
+ pass
+
+ assert "--sandbox" in recorded.get("cmd", []), (
+ f"pandoc argv not sandboxed: {recorded.get('cmd')}"
+ )
+
+ def test_heap_cap_reaches_pandoc(self, monkeypatch):
+ recorded = _patched_run(monkeypatch)
+ monkeypatch.setattr(
+ ODTExporter,
+ "_pandoc_supports_sandbox",
+ staticmethod(lambda: True),
+ )
+
+ _exporter().export("# T\n\nbody")
+
+ assert recorded["cmd"][1:4] == ["+RTS", "-M1024m", "-RTS"]
+ assert "--sandbox" in recorded["cmd"]
+
+ @pytest.mark.parametrize("max_heap_mb", [0, -1, 1025, "1024"])
+ def test_heap_limit_cannot_be_disabled(self, max_heap_mb):
+ with pytest.raises(ValueError, match="max_heap_mb"):
+ ODTExporter(max_heap_mb=max_heap_mb)
+
+ def test_unsupported_rts_fails_without_uncapped_retry(self, monkeypatch):
+ from local_deep_research.exporters import odt_exporter as mod
+
+ _patched_run(monkeypatch)
+ monkeypatch.setattr(
+ ODTExporter,
+ "_pandoc_supports_sandbox",
+ staticmethod(lambda: True),
+ )
+ calls = []
+
+ def reject_rts(cmd, **kwargs):
+ calls.append(cmd)
+ raise subprocess.CalledProcessError(
+ 1, cmd, stderr=b"Most RTS options are disabled"
+ )
+
+ monkeypatch.setattr(mod.subprocess, "run", reject_rts)
+ with pytest.raises(RuntimeError, match="Pandoc conversion failed"):
+ _exporter().export("# T\n\nbody")
+ assert len(calls) == 1
+ assert "+RTS" in calls[0]
+
+ def test_older_pandoc_refuses_export(self, monkeypatch):
+ """An older pandoc must never receive untrusted report markdown."""
+ recorded = _patched_run(monkeypatch)
+ monkeypatch.setattr(
+ ODTExporter,
+ "_pandoc_supports_sandbox",
+ staticmethod(lambda: False),
+ )
+
+ with pytest.raises(RuntimeError, match="requires pandoc 2.15"):
+ _exporter().export("# T\n\nbody")
+ assert "cmd" not in recorded
+
+ def test_stderr_is_bounded_in_failures(self, monkeypatch, tmp_path):
+ huge_stderr = b"E" * 100_000
+ _patched_run(monkeypatch, raise_called=huge_stderr)
+
+ with pytest.raises(RuntimeError) as excinfo:
+ _exporter().export("# T\n\nbody")
+
+ assert len(str(excinfo.value)) < 10_000, (
+ "unbounded pandoc stderr propagates into error surfaces"
+ )
+
+ def test_stderr_is_truncated_to_its_tail_in_the_log(self, monkeypatch):
+ """pandoc's stderr quotes report lines; the log call must carry
+ only the truncated tail, never the head of a large stderr."""
+ stderr = (
+ b"HEAD-SENTINEL-REPORT-LINE " + b"E" * 50_000 + b" TAIL-SENTINEL"
+ )
+ _patched_run(monkeypatch, raise_called=stderr)
+ log = _patched_logger(monkeypatch)
+
+ with pytest.raises(RuntimeError) as excinfo:
+ _exporter().export("# T\n\nbody")
+
+ logged = log.rendered("exception") + log.rendered("error")
+ assert logged, f"pandoc failure was not logged: {log.calls}"
+ for line in logged:
+ assert "HEAD-SENTINEL" not in line, "full stderr reached logs"
+ assert len(line) < 10_000, "unbounded stderr reached logs"
+ assert any("TAIL-SENTINEL" in line for line in logged), (
+ "the diagnostic tail of stderr should still be logged"
+ )
+ assert "HEAD-SENTINEL" not in str(excinfo.value)
+
+
+class TestSandboxVersionProbe:
+ """The real ``_pandoc_supports_sandbox`` probe, driven through
+ ``pypandoc.get_pandoc_version`` (not monkeypatched away)."""
+
+ @pytest.mark.parametrize(
+ ("version", "supported"),
+ [
+ ("3.9", True),
+ ("2.15", True),
+ ("2.14", False),
+ ("2.13", False),
+ ("2.12", False),
+ # Lexically ">= 2.15" but numerically older: catches a
+ # string comparison of version components.
+ ("2.9.2.1", False),
+ ],
+ )
+ def test_sandbox_flag_follows_pandoc_version(
+ self, monkeypatch, version, supported
+ ):
+ from local_deep_research.exporters import odt_exporter as mod
+
+ recorded = _patched_run(monkeypatch)
+ monkeypatch.setattr(mod.pypandoc, "get_pandoc_version", lambda: version)
+
+ if supported:
+ result = _exporter().export("# T\n\nbody")
+ assert "--sandbox" in recorded["cmd"]
+ assert result.content == b"PK-odt-bytes"
+ else:
+ with pytest.raises(RuntimeError, match="requires pandoc 2.15"):
+ _exporter().export("# T\n\nbody")
+ assert "cmd" not in recorded
+
+ def test_probe_failure_refuses_export_without_leaking_path(
+ self, monkeypatch
+ ):
+ from local_deep_research.exporters import odt_exporter as mod
+
+ secret = "/home/someone/private/path"
+
+ def broken_probe():
+ raise OSError(f"cannot run {secret}")
+
+ recorded = _patched_run(monkeypatch)
+ monkeypatch.setattr(mod.pypandoc, "get_pandoc_version", broken_probe)
+ log = _patched_logger(monkeypatch)
+
+ with pytest.raises(RuntimeError, match="requires pandoc 2.15"):
+ _exporter().export("# T\n\nbody")
+ assert "cmd" not in recorded
+ warnings = log.rendered("warning")
+ assert any("OSError" in w for w in warnings), (
+ f"probe failure was not logged: {log.calls}"
+ )
+ assert not any(secret in w for w in warnings), (
+ "warning must carry the exception type name only"
+ )
+
+ def test_probe_failure_is_not_cached(self, monkeypatch):
+ """A transient probe failure must not disable the sandbox for
+ the rest of the process."""
+ from local_deep_research.exporters import odt_exporter as mod
+
+ versions = iter([OSError("transient"), "3.1"])
+
+ def flaky_probe():
+ value = next(versions)
+ if isinstance(value, Exception):
+ raise value
+ return value
+
+ recorded = _patched_run(monkeypatch)
+ monkeypatch.setattr(mod.pypandoc, "get_pandoc_version", flaky_probe)
+ _patched_logger(monkeypatch)
+
+ with pytest.raises(RuntimeError, match="requires pandoc 2.15"):
+ _exporter().export("# T\n\nbody")
+ assert "cmd" not in recorded
+
+ _exporter().export("# T\n\nbody")
+ assert "--sandbox" in recorded["cmd"]
+
+ def test_real_pandoc_cannot_fetch_local_or_loopback_images(self, tmp_path):
+ """Exercise the actual converter, not just the constructed argv."""
+ from local_deep_research.exporters import odt_exporter as mod
+
+ if not mod.PYPANDOC_AVAILABLE:
+ pytest.skip("pypandoc is unavailable")
+ if not ODTExporter._pandoc_supports_sandbox():
+ pytest.skip("installed pandoc cannot run safely")
+
+ marker = b"ODT-PRIVATE-FILE-MARKER"
+ private = tmp_path / "private.gif"
+ private.write_bytes(marker)
+ hits = []
+
+ class Handler(BaseHTTPRequestHandler):
+ def do_GET(self):
+ hits.append(self.path)
+ self.send_response(200)
+ self.send_header("Content-Type", "image/gif")
+ self.end_headers()
+ self.wfile.write(b"GIF89a")
+
+ def log_message(self, *args):
+ pass
+
+ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ try:
+ report = (
+ f"![local](file://{private})\n\n"
+ f"![remote](http://127.0.0.1:{server.server_port}/image.gif)\n"
+ )
+ result = _exporter().export(report)
+ finally:
+ server.shutdown()
+ server.server_close()
+ thread.join(timeout=2)
+
+ assert hits == []
+ with zipfile.ZipFile(io.BytesIO(result.content)) as archive:
+ assert marker not in b"".join(
+ archive.read(name) for name in archive.namelist()
+ )
diff --git a/tests/exporters/test_odt_sanitize_metadata.py b/tests/exporters/test_odt_sanitize_metadata.py
index 997ddb7fac..c897d2bb9c 100644
--- a/tests/exporters/test_odt_sanitize_metadata.py
+++ b/tests/exporters/test_odt_sanitize_metadata.py
@@ -146,6 +146,14 @@ class TestExportNulSafety:
mock_pypandoc.get_pandoc_path.return_value = "/fake/pandoc"
monkeypatch.setattr(odt_module, "pypandoc", mock_pypandoc)
monkeypatch.setattr(odt_module, "PYPANDOC_AVAILABLE", True)
+ # The sandbox probe would otherwise parse the MagicMock's
+ # version string (or reuse a value another test cached) and
+ # refuse the export; these tests pin the argv, not the probe.
+ monkeypatch.setattr(
+ odt_module.ODTExporter,
+ "_pandoc_supports_sandbox",
+ MagicMock(return_value=True),
+ )
fake_odt = b"PK\x03\x04fake-odt-bytes"
mock_run = MagicMock(
diff --git a/tests/web/services/test_export_generation_contracts.py b/tests/web/services/test_export_generation_contracts.py
index dfb2e611c2..62730638a9 100644
--- a/tests/web/services/test_export_generation_contracts.py
+++ b/tests/web/services/test_export_generation_contracts.py
@@ -830,6 +830,9 @@ def _stubbed_pandoc(stdout=b"PK\x03\x04odt-bytes"):
with (
patch.object(module, "PYPANDOC_AVAILABLE", True),
patch.object(module, "pypandoc", fake_pypandoc),
+ patch.object(
+ ODTExporter, "_pandoc_supports_sandbox", return_value=True
+ ),
patch.object(
module.subprocess, "run", return_value=completed
) as run_mock,