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(latex): escape injected control sequences and specials in export body/heading text (#6423)

LearningCircuit8f3215431685
diff --git a/changelog.d/6423.security.md b/changelog.d/6423.security.md
new file mode 100644
index 0000000000..309f495cf9
--- /dev/null
+++ b/changelog.d/6423.security.md
@@ -0,0 +1 @@
+LaTeX export now escapes backslashes, braces, `#`, `~` and `^` in body and heading text that falls outside math-mode spans (``$...$`` and ``$$...$$``), so web-influenced report content in that text cannot smuggle live LaTeX control sequences (e.g. ``\input{...}``) into the exported `.tex`; math spans continue to pass through verbatim, as before. The bibliography title escaper also no longer corrupts literal backslashes.
diff --git a/src/local_deep_research/text_optimization/citation_formatter.py b/src/local_deep_research/text_optimization/citation_formatter.py
index 7118b2b560..05cfae993e 100644
--- a/src/local_deep_research/text_optimization/citation_formatter.py
+++ b/src/local_deep_research/text_optimization/citation_formatter.py
@@ -88,9 +88,9 @@ _BIB_SOURCES_PATTERN = re.compile(
# Single-pass character map. A sequential replace() chain would re-escape
-# the braces its own replacements introduce — the bug already present in
-# _escape_latex, where "\\" becomes "\textbackslash{}" and the later
-# brace rules then mangle it.
+# the braces its own replacements introduce — the same class of bug that
+# _escape_latex_text's single regex pass avoids below, where "\\" becomes
+# "\textbackslash{}" without a later brace rule mangling it again.
_BIBTEX_ESCAPES = {
"\\": r"\textbackslash{}",
# Balanced pairs, not backslash escapes: BibTeX's field scanner counts
@@ -158,6 +158,43 @@ def _escape_bibtex(value: str) -> str:
)
+_LATEX_TEXT_SPECIALS: dict[str, str] = {
+ "\\": r"\textbackslash{}",
+ "&": r"\&",
+ "%": r"\%",
+ "$": r"\$",
+ "#": r"\#",
+ "_": r"\_",
+ "{": r"\{",
+ "}": r"\}",
+ "~": r"\textasciitilde{}",
+ "^": r"\textasciicircum{}",
+}
+_LATEX_TEXT_SPECIALS_RE = re.compile(
+ "[" + re.escape("".join(_LATEX_TEXT_SPECIALS)) + "]"
+)
+
+
+def _escape_latex_text(text: str) -> str:
+ r"""Escape every LaTeX-special character in one pass.
+
+ One regex pass is load-bearing. Sequential ``str.replace`` passes
+ re-process their own output: the braces in ``\textbackslash{}`` get
+ escaped again and a literal backslash comes out as the invalid
+ ``\textbackslash\{\}``. ``re.sub`` never rescans replacement text,
+ so each special character is replaced exactly once.
+ """
+ return _LATEX_TEXT_SPECIALS_RE.sub(
+ lambda m: _LATEX_TEXT_SPECIALS[m.group()], text
+ )
+
+
+# Matches the leading '#' markers of an ATX heading so the heading TEXT
+# can be escaped while the marker itself survives for the
+# heading-conversion pass in export_to_latex.
+_HEADING_PREFIX_RE = re.compile(r"^(\s*#+\s+)(.*)$")
+
+
def _safe_bibtex_url(value: str) -> str:
r"""Return *value* if it is safe to place in ``url = {...}``, else "".
@@ -1543,17 +1580,20 @@ class LaTeXExporter:
# like headings (#), emphasis (*), and citations ([n])
lines = parts[i].split("\n")
for j, line in enumerate(lines):
- # Don't escape lines that start with # (headings)
- if not line.strip().startswith("#"):
- # Don't escape emphasis markers or citations for now
- # They'll be handled by their own patterns
- temp_line = line
- # Escape special chars except *, #, [, ]
- temp_line = temp_line.replace("&", r"\&")
- temp_line = temp_line.replace("%", r"\%")
- temp_line = temp_line.replace("_", r"\_")
- # Don't escape { } inside citations
- lines[j] = temp_line
+ # Escape every LaTeX-special character outside math
+ # mode. Markdown markers (*, `, [n]) are not
+ # LaTeX-special and survive for their own
+ # conversions below.
+ heading = _HEADING_PREFIX_RE.match(line)
+ if heading:
+ # Keep the '#' markers intact for the heading
+ # conversion; escape the text after them so
+ # \section{...} receives literal text only.
+ lines[j] = heading.group(1) + _escape_latex_text(
+ heading.group(2)
+ )
+ else:
+ lines[j] = _escape_latex_text(line)
parts[i] = "\n".join(lines)
body_content = "$".join(parts)
@@ -1604,24 +1644,7 @@ class LaTeXExporter:
def _escape_latex(self, text: str) -> str:
"""Escape special LaTeX characters in text."""
- # Escape special LaTeX characters
- replacements = [
- ("\\", r"\textbackslash{}"), # Must be first
- ("&", r"\&"),
- ("%", r"\%"),
- ("$", r"\$"),
- ("#", r"\#"),
- ("_", r"\_"),
- ("{", r"\{"),
- ("}", r"\}"),
- ("~", r"\textasciitilde{}"),
- ("^", r"\textasciicircum{}"),
- ]
-
- for old, new in replacements:
- text = text.replace(old, new)
-
- return text
+ return _escape_latex_text(text)
def _convert_lists(self, content: str) -> str:
"""Convert markdown lists to LaTeX format."""
diff --git a/tests/text_optimization/test_latex_body_escaping.py b/tests/text_optimization/test_latex_body_escaping.py
new file mode 100644
index 0000000000..e1d59c4475
--- /dev/null
+++ b/tests/text_optimization/test_latex_body_escaping.py
@@ -0,0 +1,87 @@
+"""LaTeX body-escaping contracts for the legacy LaTeXExporter.
+
+Report content is synthesized from fetched web pages, so body text can
+carry attacker-influenced characters. A compiled ``.tex`` must not turn
+those into live control sequences: unescaped ``\\input``/``\\write18``
+must not survive into the compiled document as file-read / shell-escape
+vectors, and that must still hold once the markdown-to-LaTeX conversions
+(headings, emphasis, citations) run.
+
+The control-sequence scenarios (``\\input`` file-read, ``\\write18``
+shell-escape, heading injection) are pinned end-to-end by the promoted
+contracts in ``tests/web/services/test_export_generation_contracts.py``;
+this file pins only the edges those suites do not cover: the remaining
+special characters in body and heading text, the markdown-conversion
+interplay, and the ``_escape_latex`` helper's exactness.
+
+These contracts pin the escaping only — they do not depend on Quarto or
+a TeX installation.
+"""
+
+from __future__ import annotations
+
+from local_deep_research.text_optimization.citation_formatter import (
+ LaTeXExporter,
+)
+
+
+class TestBodyControlSequenceInjection:
+ """Backslash commands in body text must be escaped, not live."""
+
+ def test_brace_hash_tilde_circumflex_in_body_are_escaped(self):
+ exporter = LaTeXExporter()
+ content = (
+ "# Title\n\nC# and {braces} ~ tilde ^ circumflex path\\to\\file\n"
+ )
+ result = exporter.export_to_latex(content)
+
+ assert "C\\#" in result
+ assert "\\{braces\\}" in result
+ assert "\\textasciitilde{}" in result
+ assert "\\textasciicircum{}" in result
+ assert "\\textbackslash{}" in result
+ assert "path\\textbackslash{}to\\textbackslash{}file" in result
+
+
+class TestHeadingTextInjection:
+ """Heading text must be escaped the same as body text."""
+
+ def test_heading_special_characters_are_escaped(self):
+ exporter = LaTeXExporter()
+ content = "# C# & F# — 100% {styled}\n"
+ result = exporter.export_to_latex(content)
+
+ assert "\\section{" in result
+ assert "C\\#" in result
+ assert "\\{styled\\}" in result
+
+
+class TestMarkdownConversionSurvivesEscaping:
+ """Escaping must not break the downstream markdown conversions."""
+
+ def test_emphasis_and_citations_still_convert(self):
+ exporter = LaTeXExporter()
+ content = "# Title\n\n**bold{x}** and *italic* cite [1].\n"
+ result = exporter.export_to_latex(content)
+
+ assert "\\textbf{bold\\{x\\}}" in result
+ assert "\\textit{italic}" in result
+ assert "\\cite{1}" in result
+
+
+class TestEscapeLatexHelper:
+ """_escape_latex must produce valid LaTeX for its own replacements."""
+
+ def test_single_backslash_is_not_double_escaped(self):
+ exporter = LaTeXExporter()
+
+ # The replacement for \ contains literal braces; a sequential
+ # pass then escapes those braces again and corrupts the output.
+ assert exporter._escape_latex("\\") == "\\textbackslash{}"
+
+ def test_backslash_among_other_specials(self):
+ exporter = LaTeXExporter()
+
+ assert (
+ exporter._escape_latex("a\\b&c%d") == "a\\textbackslash{}b\\&c\\%d"
+ )
diff --git a/tests/web/services/test_export_generation_contracts.py b/tests/web/services/test_export_generation_contracts.py
index 49d967c9cd..fbb6473dca 100644
--- a/tests/web/services/test_export_generation_contracts.py
+++ b/tests/web/services/test_export_generation_contracts.py
@@ -29,8 +29,9 @@ its *control sequence* does not.
Sections
--------
-1. LaTeX body escaping (the exporter's own ``_escape_latex`` is applied to
- the bibliography but not to the body -- section 2 pins the contrast).
+1. LaTeX body escaping (body and heading text are escaped through
+ ``_escape_latex_text``, the bibliography through ``_escape_latex`` --
+ section 2 pins that both regions meet the same bar).
2. Bibliography path, as a positive control.
3. Quarto ``.qmd`` promotion and front matter.
4. Archive entry names (zip-slip) and download-filename sanitising.
@@ -184,28 +185,16 @@ class _WriteWatchingOpen:
class TestLaTeXBodyEscaping:
"""Report prose must reach the .tex file as text, not as TeX code."""
- @pytest.mark.xfail(
- strict=True,
- reason=(
- "LIVE DEFECT: citation_formatter.py:1424-1451 escapes only & "
- "% _ in the document body and never the backslash, so "
- "LLM-generated prose reaches the .tex verbatim. Not "
- "server-side RCE (no TeX binary runs in src/) -- the payload "
- "detonates when the researcher compiles the file they "
- "downloaded. Fix: escape the backslash FIRST, as the sibling "
- "_escape_latex already does. "
- ),
- )
@TEX_PAYLOADS
def test_report_prose_must_not_carry_live_control_sequences(
self, payload, control_sequence, surviving_text
):
- """A control sequence in LLM prose becomes live TeX in the export.
+ """A control sequence in LLM prose must not become live TeX.
- The exporter escapes only ``&``, ``%`` and ``_``. A backslash is
- passed through untouched, so every one of these payloads survives
- into the ``.tex`` file exactly as written and is executed by the
- first ``pdflatex`` run.
+ The exporter escapes the backslash along with ``&``, ``%`` and
+ ``_`` in body text, so none of these payloads survive into the
+ ``.tex`` file as something the first ``pdflatex`` run would
+ execute.
"""
report = (
"## Findings\n\n"
@@ -221,25 +210,15 @@ class TestLaTeXBodyEscaping:
assert control_sequence not in body
assert payload not in body
- @pytest.mark.xfail(
- strict=True,
- reason=(
- "LIVE DEFECT: the escape loop is guarded by `if not "
- "line.strip().startswith('#')`, and the line is then "
- "rewritten into \\section{...} -- so headings skip escaping "
- "entirely. Even & % _ land raw there, which is a plain "
- "compile failure as well as an injection point. "
- ),
- )
- def test_markdown_headings_are_exempt_from_escaping_entirely(self):
- """Lines starting with ``#`` skip the escaper by construction.
-
- ``export_to_latex`` guards its escaping loop with
- ``if not line.strip().startswith("#")``, then rewrites the line
- into ``\\section{...}``. Anything the LLM put in a heading lands
- inside the section argument unmodified -- including a control
- sequence, and including the ``&``/``%``/``_`` that *are* escaped
- one line lower and that make TeX fail to compile.
+ def test_markdown_headings_are_escaped_like_body_text(self):
+ """A heading line is escaped, then rewritten into a section.
+
+ ``export_to_latex`` matches the leading ``#`` markers with
+ ``_HEADING_PREFIX_RE``, escapes the heading text the same way it
+ escapes a body line, and only then rewrites the line into
+ ``\\section{...}``. So a control sequence -- or the ``&``/``%``/
+ ``_`` that would otherwise break compilation -- lands inside the
+ section argument neutralised, same as it would one line lower.
"""
report = f"# Results for R&D spend {TEX_FILE_READ}\n\nBody text.\n"
@@ -283,12 +262,37 @@ class TestLaTeXBodyEscaping:
assert "\\%" in body
assert "\\_" in body
+ @pytest.mark.xfail(
+ strict=True,
+ reason=(
+ "math spans are passed through verbatim; escaping inside them "
+ "needs math-aware handling"
+ ),
+ )
+ def test_a_control_sequence_inside_display_math_still_reaches_the_tex(
+ self,
+ ):
+ """``$$...$$`` content is emitted verbatim, control sequences included.
+
+ ``test_citation_exporter_edge_cases.py`` pins that display math such
+ as ``$$E = mc^2$$`` must survive unescaped so legitimate LaTeX math
+ keeps rendering. The same exemption means a control sequence placed
+ inside a ``$$...$$`` span in report prose is emitted unescaped too.
+ """
+ report = "Benign report with no stray dollars.\n\n$$\\relax$$\n"
+
+ body = _tex_body(_export_latex(report))
+
+ assert "relax" in body # arrival
+ assert "\\relax" not in body
+
def test_escaper_that_would_fix_this_already_exists_in_the_module(self):
"""Positive control: the neutralising routine is present and works.
- ``LaTeXExporter._escape_latex`` handles the backslash correctly.
- The body path simply never calls it -- so the gap above is a
- wiring omission, not a missing capability.
+ ``LaTeXExporter._escape_latex`` handles the backslash correctly,
+ and the body path applies the same escaping through
+ ``_escape_latex_text`` -- this pins that the shared helper's own
+ output is correct, independent of where it is called from.
"""
from local_deep_research.text_optimization.citation_formatter import (
LaTeXExporter as LegacyLaTeXExporter,
@@ -307,25 +311,15 @@ class TestLaTeXBodyEscaping:
class TestLaTeXBibliographyIsAlreadyHardened:
- """Same payload, same document, different region: only one is escaped."""
+ """Same payload, same document, two regions -- one escaped by each."""
- @pytest.mark.xfail(
- strict=True,
- reason=(
- "LIVE DEFECT: LaTeXExporter._escape_latex (line 1498) handles "
- "the backslash correctly and is applied to bibliography "
- "titles -- same document, same payload, escaped there and raw "
- "in the body. A wiring omission, not missing code. "
- ),
- )
def test_body_must_meet_the_same_bar_as_the_bibliography(self):
"""One document, one payload, two regions -- one bar.
- The bibliography half of this test passes today: the exporter
- already treats attacker-controlled text as needing escaping when
- that text is a source title. That is what makes the body gap a
- defect rather than a design decision, and it is why the fix is a
- wiring change rather than new code.
+ The bibliography and the body are escaped by different helpers
+ (``_escape_latex`` for the bibliography, ``_escape_latex_text``
+ for the body), so this test pins that both regions meet the same
+ bar rather than trusting that they happen to agree.
"""
report = (
f"The claim {TEX_FILE_READ} appears in the survey.\n\n"