~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.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(latex): restrict report math to safe commands (#6993)
LearningCircuitba0d81b48072
diff --git a/changelog.d/6872.security.md b/changelog.d/6872.security.mdnew file mode 100644index 0000000000..302f87c23f--- /dev/null+++ b/changelog.d/6872.security.md@@ -0,0 +1 @@+LaTeX export no longer passes every `$...$` and `$$...$$` span through verbatim: math that fetched content places in a report could otherwise run commands such as `\input`, `\write18` or `\catcode` (or the same spelled with TeX's `^^` character encoding) when the exported `.tex` file is compiled. A span now stays math only if it has balanced braces, contains no `^^`, and holds nothing but ASCII letters and digits, the characters `+-*/=.,:;!?()[]^_<>|'`, spaces, tabs, LF or CRLF line breaks, and commands from an allowlist of built-in LaTeX math commands: Greek letters, binary operators, relations (including `\le`, `\ge` and `\ne`), arrows, other symbols, dots, big operators, named operators such as `\exp`, delimiters and their sizes (including `\{`, `\}` and `\|`), accents, `\frac`, `\sqrt`, math alphabets, math styles, spacing such as `\,` and `\quad`, `\\`, and the escaped characters `\%`, `\#`, `\&`, `\_` and `\$`. Every other span is rendered as literal text, including spans that use `\text` or `\mathbb`, which need the amsmath and amsfonts packages that the export does not load. The Quarto export is covered by the same allowlist: its front matter declares a `pdf` format, so `quarto render` would otherwise hand each span to Pandoc's LaTeX writer, which emits math verbatim. An unsafe span is backslash-escaped so Pandoc reads it as literal text rather than math or raw TeX; a safe span is kept as math.diff --git a/src/local_deep_research/text_optimization/citation_formatter.py b/src/local_deep_research/text_optimization/citation_formatter.pyindex 2903559b25..bb023eb101 100644--- a/src/local_deep_research/text_optimization/citation_formatter.py+++ b/src/local_deep_research/text_optimization/citation_formatter.py@@ -1661,6 +1661,13 @@ csl: apa.csl# Process contentprocessed_content = content+ # Report math reaches a TeX engine when ``quarto render`` builds the+ # declared pdf format, so spans that use commands outside the math+ # allowlist are escaped to literal text here, exactly as the LaTeX+ # export does. Run before the citation and cell passes so the escaped+ # brackets of a rejected span are never mistaken for a citation.+ processed_content = _defuse_report_math_for_quarto(processed_content)+# First handle comma-separated citations like [1, 2, 3]def replace_comma_citations(match):citation_nums = match.group(1)@@ -2267,6 +2274,453 @@ def _split_math_segments(text: str) -> list[tuple[str, bool]]:return segments+# Math in a report may come from retrieved pages through the LLM. TeX executes+# control sequences when a user compiles an exported .tex file, so preserving+# every matched $...$ span verbatim is unsafe. Only math commands that the+# LaTeX kernel itself defines are accepted, because the export preamble loads+# no math package: \text, \binom and \operatorname (amsmath) and \mathbb+# (amsfonts) would be undefined there, so spans using them are rendered as+# literal text. Each accepted command is a math symbol, delimiter+# or accent, or a TeX primitive or kernel macro that only typesets (boxes,+# spacing, font changes). None of them lets the report's text open or write+# a file, run a shell command, change a category code or define a macro.+# Every character in an argument is checked by the same scanner, so an+# allowed command cannot hide a second one.+_SAFE_MATH_COMMANDS = frozenset(+ {+ # Greek letters, lower case. There is no \omicron: it is "o".+ "alpha",+ "beta",+ "gamma",+ "delta",+ "epsilon",+ "varepsilon",+ "zeta",+ "eta",+ "theta",+ "vartheta",+ "iota",+ "kappa",+ "lambda",+ "mu",+ "nu",+ "xi",+ "pi",+ "varpi",+ "rho",+ "varrho",+ "sigma",+ "varsigma",+ "tau",+ "upsilon",+ "phi",+ "varphi",+ "chi",+ "psi",+ "omega",+ # Greek letters, upper case. The others (A, B, E, ...) are Latin.+ "Gamma",+ "Delta",+ "Theta",+ "Lambda",+ "Xi",+ "Pi",+ "Sigma",+ "Upsilon",+ "Phi",+ "Psi",+ "Omega",+ # Binary operators.+ "pm",+ "mp",+ "times",+ "div",+ "cdot",+ "ast",+ "star",+ "circ",+ "bullet",+ "setminus",+ "cap",+ "cup",+ "uplus",+ "sqcap",+ "sqcup",+ "vee",+ "wedge",+ "land",+ "lor",+ "oplus",+ "ominus",+ "otimes",+ "oslash",+ "odot",+ "dagger",+ "ddagger",+ "amalg",+ "diamond",+ "wr",+ "bigcirc",+ "triangleleft",+ "triangleright",+ "bigtriangleup",+ "bigtriangledown",+ # Relations, including the \le, \ge and \ne short forms and \not,+ # which overlays a slash on the relation after it.+ "leq",+ "le",+ "geq",+ "ge",+ "neq",+ "ne",+ "ll",+ "gg",+ "prec",+ "succ",+ "preceq",+ "succeq",+ "sim",+ "simeq",+ "approx",+ "cong",+ "equiv",+ "doteq",+ "propto",+ "asymp",+ "perp",+ "parallel",+ "mid",+ "models",+ "vdash",+ "dashv",+ "smile",+ "frown",+ "bowtie",+ "in",+ "ni",+ "owns",+ "notin",+ "subset",+ "supset",+ "subseteq",+ "supseteq",+ "sqsubseteq",+ "sqsupseteq",+ "not",+ # Arrows.+ "to",+ "gets",+ "leftarrow",+ "rightarrow",+ "leftrightarrow",+ "Leftarrow",+ "Rightarrow",+ "Leftrightarrow",+ "longleftarrow",+ "longrightarrow",+ "longleftrightarrow",+ "Longleftarrow",+ "Longrightarrow",+ "Longleftrightarrow",+ "iff",+ "mapsto",+ "longmapsto",+ "hookleftarrow",+ "hookrightarrow",+ "uparrow",+ "downarrow",+ "updownarrow",+ "Uparrow",+ "Downarrow",+ "Updownarrow",+ "nearrow",+ "searrow",+ "swarrow",+ "nwarrow",+ "leftharpoonup",+ "leftharpoondown",+ "rightharpoonup",+ "rightharpoondown",+ "rightleftharpoons",+ # Other symbols.+ "infty",+ "partial",+ "nabla",+ "forall",+ "exists",+ "neg",+ "lnot",+ "emptyset",+ "aleph",+ "hbar",+ "imath",+ "jmath",+ "ell",+ "wp",+ "Re",+ "Im",+ "prime",+ "top",+ "bot",+ "angle",+ "triangle",+ "surd",+ "flat",+ "natural",+ "sharp",+ "clubsuit",+ "diamondsuit",+ "heartsuit",+ "spadesuit",+ "colon",+ "ldots",+ "cdots",+ "vdots",+ "ddots",+ "dots",+ # Big operators.+ "sum",+ "prod",+ "coprod",+ "int",+ "oint",+ "smallint",+ "bigcap",+ "bigcup",+ "bigsqcup",+ "bigvee",+ "bigwedge",+ "bigodot",+ "bigoplus",+ "bigotimes",+ "biguplus",+ # Named operators, set upright like "log".+ "arccos",+ "arcsin",+ "arctan",+ "arg",+ "cos",+ "cosh",+ "cot",+ "coth",+ "csc",+ "deg",+ "det",+ "dim",+ "exp",+ "gcd",+ "hom",+ "inf",+ "ker",+ "lg",+ "lim",+ "liminf",+ "limsup",+ "ln",+ "log",+ "max",+ "min",+ "Pr",+ "sec",+ "sin",+ "sinh",+ "sup",+ "tan",+ "tanh",+ "bmod",+ "pmod",+ # Delimiters and the commands that size them (\middle is e-TeX).+ "left",+ "right",+ "middle",+ "big",+ "Big",+ "bigg",+ "Bigg",+ "bigl",+ "bigr",+ "Bigl",+ "Bigr",+ "biggl",+ "biggr",+ "Biggl",+ "Biggr",+ "bigm",+ "Bigm",+ "biggm",+ "Biggm",+ "langle",+ "rangle",+ "lfloor",+ "rfloor",+ "lceil",+ "rceil",+ "lbrace",+ "rbrace",+ "lbrack",+ "rbrack",+ "vert",+ "Vert",+ "backslash",+ "lgroup",+ "rgroup",+ "lmoustache",+ "rmoustache",+ "arrowvert",+ "Arrowvert",+ "bracevert",+ # Accents, and lines, braces and arrows set over or under a formula.+ "hat",+ "check",+ "tilde",+ "acute",+ "grave",+ "dot",+ "ddot",+ "breve",+ "bar",+ "vec",+ "mathring",+ "widehat",+ "widetilde",+ "overline",+ "underline",+ "overbrace",+ "underbrace",+ "overrightarrow",+ "overleftarrow",+ # Fractions and roots.+ "frac",+ "sqrt",+ # Math alphabets.+ "mathrm",+ "mathbf",+ "mathit",+ "mathsf",+ "mathtt",+ "mathcal",+ "mathnormal",+ # Math styles and the placement of limits.+ "displaystyle",+ "textstyle",+ "scriptstyle",+ "scriptscriptstyle",+ "limits",+ "nolimits",+ # Spacing. \medspace and \thickspace are left out: the kernel only+ # gained them in 2020, so older TeX installations lack them.+ "quad",+ "qquad",+ "thinspace",+ "negthinspace",+ "enspace",+ }+)+# Control symbols: a backslash and one non-letter. \$ and \\ are the+# literal-dollar and escaped-backslash spans the delimiter scanner already+# supports. \{, \} and \| are delimiters; \, \: \; \! and "\ " are spaces;+# \% \# \& and \_ print the character. "\^" stays out: it would let "\^^"+# hide a ^^ encoding from the check in _math_span_is_safe.+_SAFE_MATH_CONTROL_SYMBOLS = frozenset("$\\{}|,:;! %#&_")+_ASCII_MATH_LETTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"+# "'" is the prime, as in f'(x). "\r" is handled in _math_span_is_safe.+_SAFE_MATH_CHARACTERS = frozenset(+ _ASCII_MATH_LETTERS + "0123456789 \t\n+-*/=.,:;!?(){}[]^_<>|'"+)+++def _math_span_is_safe(segment: str) -> bool:+ """Accept only inert math syntax inside a matched inline/display span."""+ delimiter = "$$" if segment.startswith("$$") else "$"+ body = segment[len(delimiter) : -len(delimiter)]+ depth = 0+ position = 0+ while position < len(body):+ character = body[position]+ if character == "\\":+ position += 1+ if position == len(body):+ return False+ if body[position] in _ASCII_MATH_LETTERS:+ start = position+ while (+ position < len(body)+ and body[position] in _ASCII_MATH_LETTERS+ ):+ position += 1+ if body[start:position] not in _SAFE_MATH_COMMANDS:+ return False+ continue+ if body[position] not in _SAFE_MATH_CONTROL_SYMBOLS:+ return False+ position += 1+ continue+ if character == "\r":+ # Legacy report_content rows store CRLF newlines, and TeX reads a+ # CRLF pair as one line break. TeX also ends a line at a lone CR,+ # which _BLOCK_END does not see, so "\r\r" could hide a blank line+ # (a paragraph break) inside a span; a lone CR stays literal.+ if not body.startswith("\n", position + 1):+ return False+ position += 1+ continue+ if character not in _SAFE_MATH_CHARACTERS:+ return False+ # TeX turns ^^5c (and longer ^^ encodings) into a backslash before+ # it recognizes control sequences. A character-only allowlist would+ # otherwise accept an encoded \input with no literal backslash.+ if character == "^" and body.startswith("^^", position):+ return False+ if character == "{":+ depth += 1+ elif character == "}":+ depth -= 1+ if depth < 0:+ return False+ position += 1+ return depth == 0+++# Pandoc's markdown reader treats a backslash before any ASCII punctuation+# character as that literal character (the ``all_symbols_escapable``+# extension, on by default), so escaping every punctuation character in a+# span renders it as text: a ``$`` no longer shifts into math+# (``tex_math_dollars`` needs an unescaped ``$``) and the backslash of a+# command such as ``\input`` becomes a literal backslash, not a control+# sequence, even while ``raw_tex`` is on. Letters and digits are left as+# they are; only the characters that could carry meaning are neutralised.+_MARKDOWN_PUNCTUATION_RE = re.compile(r"[!-/:-@\[-`{-~]")+++def _escape_markdown_math_span(segment: str) -> str:+ r"""Render a rejected ``$...$``/``$$...$$`` span as inert Markdown text.++ Backslash-escapes every ASCII punctuation character, so Pandoc reads the+ span as literal characters rather than math or raw TeX.+ """+ return _MARKDOWN_PUNCTUATION_RE.sub(r"\\\g<0>", segment)+++def _defuse_report_math_for_quarto(content: str) -> str:+ r"""Escape every unsafe math span in a Quarto report body.++ The Quarto front matter declares a ``pdf`` format, so ``quarto render``+ hands each ``$...$``/``$$...$$`` span to Pandoc's LaTeX writer, which+ emits math verbatim. A span is kept as math only when+ :func:`_math_span_is_safe` accepts it — the same allowlist the LaTeX+ export applies — and every other span is escaped to literal text so it+ never reaches the TeX engine. Prose between spans is returned untouched+ for the citation and cell passes that run after it.+ """+ parts: list[str] = []+ for segment, is_math in _split_math_segments(content):+ if is_math and not _math_span_is_safe(segment):+ parts.append(_escape_markdown_math_span(segment))+ else:+ parts.append(segment)+ return "".join(parts)++# The start of a citation link as CitationFormatter writes it: the label# in double brackets, then the destination. Every hyperlinked mode uses this# shape; only the label differs ([[1]], [[arxiv.org]], [[arxiv.org-2]],@@ -2340,16 +2794,17 @@ class LaTeXExporter:entries = self._sources_entries(content)body_content = self._unlink_citations(content, entries)- # Escape special LaTeX characters but preserve math mode. A+ # Escape special LaTeX characters while preserving safe math. A# left-to-right scanner pairs $$...$$ display spans and $...$- # inline spans, which pass through verbatim; every other dollar+ # inline spans; accepted spans pass through verbatim and rejected+ # spans are rendered as literal text. Every other dollar# is prose. The previous whole-document split made ONE unpaired# dollar (a price in prose) invert the parity and silently# disable escaping for the rest of the report.escaped_parts: list[str] = []at_line_start = Truefor segment, is_math in _split_math_segments(body_content):- if is_math:+ if is_math and _math_span_is_safe(segment):escaped_parts.append(segment)else:lines = segment.split("\n")diff --git a/tests/text_optimization/test_latex_math_parity.py b/tests/text_optimization/test_latex_math_parity.pyindex e62447657a..9ab936fa8d 100644--- a/tests/text_optimization/test_latex_math_parity.py+++ b/tests/text_optimization/test_latex_math_parity.py@@ -135,7 +135,7 @@ class TestPreEscapedDollarSurvivesVerbatim:class TestMathSpansSurviveIntact:- """Matched math spans reach the output untouched."""+ """Matched, allowed math spans reach the output untouched."""def test_math_pair_after_a_lone_dollar_is_still_recognized(self):r"""A genuine pair after a lone ``$`` is math in its own right.diff --git a/tests/text_optimization/test_latex_math_security.py b/tests/text_optimization/test_latex_math_security.pynew file mode 100644index 0000000000..17e23df634--- /dev/null+++ b/tests/text_optimization/test_latex_math_security.py@@ -0,0 +1,321 @@+"""Untrusted report math must not become executable TeX on export."""++import re++import pytest++from local_deep_research.text_optimization.citation_formatter import (+ LaTeXExporter,+ QuartoExporter,+)+++def _export_body(math: str, delimiter: str) -> str:+ report = f"# Report\n\nBefore {delimiter}{math}{delimiter} after."+ result = LaTeXExporter().export_to_latex(report)+ return result.split("\\maketitle\n", 1)[1].split("\\end{document}", 1)[0]+++def _has_control_word(body: str, command: str) -> bool:+ r"""Whether TeX reads ``command`` as a control word somewhere in ``body``.++ A control word ends at the first non-letter, so the ``\text`` at the+ start of the escaper's own ``\textbackslash{}`` does not count.+ """+ return re.search(re.escape(command) + "(?![A-Za-z])", body) is not None+++ ("math", "text"),+ [+ (r"\input{/etc/passwd}", "passwd"),+ (r"\include{chapter}", "chapter"),+ (r"\write18{touch probe}", "probe"),+ (r"\immediate\write18{touch probe}", "probe"),+ (r"\openin1=/etc/passwd", "passwd"),+ (r"\read16 to\pi", "read16"),+ (r"\catcode 124=0", "catcode"),+ (r"\global\catcode`\|=0\relax", "catcode"),+ (r"\def\alpha{x}", "alpha"),+ (r"\newcommand{\pi}{3}", "newcommand"),+ (r"\csname input\endcsname{/etc/passwd}", "passwd"),+ (r"\usepackage{shellesc}", "shellesc"),+ (r"x% comment", "comment"),+ (r"\begin{document}", "document"),+ (r"\unknown{1}", "unknown"),+ (r"x^{unclosed", "unclosed"),+ ("^^5cinput{/etc/passwd}", "passwd"),+ # An allowed command (\in) followed by letters spelled with ^^:+ # TeX would read the whole name as \input.+ (r"\in^^70ut{/etc/passwd}", "passwd"),+ # ``\^`` must stay out of _SAFE_MATH_CONTROL_SYMBOLS. Were it+ # allowed, ``\^`` would consume the first caret and hide the ``^^``+ # from the encoding check, leaving a lone second caret. TeX decodes+ # the hex form ``^^69`` to ``i``, so the span is+ # ``\input{/etc/passwd}``. Pinned for both caret spellings:+ (r"\^^69nput{/etc/passwd}", "passwd"),+ # ...and the single-character form, where ``^^)`` decodes to ``i``+ # (``0x29 + 0x40``):+ (r"\^^)nput{/etc/passwd}", "passwd"),+ # The ``^^`` check must reject every ``^^``, not only the two-hex+ # form. ``^^0`` is the single-character encoding of ``p``+ # (``0x30 + 0x40``), so ``\in^^0ut`` is ``\input``; here the digit+ # after ``^^`` is followed by a non-hex letter, which a hex-only+ # check would wave through.+ (r"\in^^0ut{/etc/passwd}", "passwd"),+ ],+)[email protected]("delimiter", ["$", "$$"])+def test_unsafe_math_is_rendered_as_literal_text(math, text, delimiter):+ body = _export_body(math, delimiter)++ assert text in body+ assert delimiter.replace("$", "\\$") in body+ assert f"{delimiter}{math}{delimiter}" not in body+ assert "^^" not in body+ for command in re.findall(r"\\[A-Za-z]+", math):+ assert not _has_control_word(body, command)+++ "command",+ [+ "input",+ "include",+ "InputIfFileExists",+ "write",+ "immediate",+ "openout",+ "openin",+ "read",+ "readline",+ "catcode",+ "def",+ "edef",+ "gdef",+ "xdef",+ "let",+ "newcommand",+ "renewcommand",+ "providecommand",+ "DeclareRobustCommand",+ "csname",+ "expandafter",+ "usepackage",+ "RequirePackage",+ "documentclass",+ "special",+ "scantokens",+ "directlua",+ "ShellEscape",+ "makeatletter",+ "begin",+ "end",+ "relax",+ ],+)[email protected]("delimiter", ["$", "$$"])+def test_one_command_outside_the_allowlist_makes_the_span_literal(+ command, delimiter+):+ """Every other token here is allowed, so only this command decides."""+ math = "\\alpha \\le \\" + command + "{x} \\beta"++ body = _export_body(math, delimiter)++ assert f"{delimiter}{math}{delimiter}" not in body+ assert not _has_control_word(body, "\\" + command)+++ ("math", "packages"),+ [+ (r"\text{if } x > 0", ("amsmath", "amstext")),+ (r"\mathbb{R}^n", ("amsfonts", "amssymb")),+ ],+)[email protected]("delimiter", ["$", "$$"])+def test_commands_from_packages_the_export_does_not_load_stay_literal(+ math, packages, delimiter+):+ r"""``\text`` and ``\mathbb`` are undefined unless these packages load.++ The export preamble loads none of them, so both commands stay off the+ allowlist; allowing them would need the preamble to load the package.+ """+ result = LaTeXExporter().export_to_latex(+ f"# Report\n\nThe set {delimiter}{math}{delimiter} here."+ )+ preamble = result.split("\\begin{document}", 1)[0]++ for package in packages:+ assert package not in preamble+ assert f"{delimiter}{math}{delimiter}" not in result+++ "math",+ [+ "x_2^2 + y^2 = r^2",+ r"\frac{1}{2} + \sqrt{x} = \alpha",+ r"\sum_{i=1}^{n} i = \frac{n(n+1)}{2}",+ r"x\$y",+ pytest.param(+ r"\chi^2 + \eta\nu + \xi\kappa + \zeta\psi + \iota\upsilon"+ r" + \vartheta\varpi\varrho\varsigma",+ id="greek-lower-case",+ ),+ pytest.param(r"\Xi + \Upsilon + \Psi", id="greek-upper-case"),+ pytest.param(+ r"a \ast b \star c \circ d \bullet e \setminus f \oplus g"+ r" \otimes h \wedge i \vee j \dagger k",+ id="binary-operators",+ ),+ pytest.param(+ r"a \le b \ge c \ne d \ll e \gg f \propto g \cong h \simeq i"+ r" \perp j \parallel k \mid l \not= m \ni n \prec o \models p",+ id="relations",+ ),+ pytest.param(+ r"p \Rightarrow q \Leftrightarrow r \iff s \mapsto t"+ r" \longrightarrow u \hookrightarrow v \uparrow w \gets x",+ id="arrows",+ ),+ pytest.param(+ r"\aleph_0 + \hbar + \ell + \Re z + \Im z + \neg p + \angle A"+ r" + \wp + \top + \triangle + f\colon X \to Y",+ id="other-symbols",+ ),+ pytest.param(r"x_1, \ldots, x_n \vdots \ddots", id="dots"),+ pytest.param(+ r"\bigcup_{i=1}^{n} A_i + \bigcap_{j} B_j + \oint_C f"+ r" + \coprod_k + \bigoplus_l + \bigotimes_m",+ id="big-operators",+ ),+ pytest.param(+ r"\exp(x) + \sinh y + \det A + \sup S + \gcd(a, b) + \arg z"+ r" + a \bmod b + x \equiv y \pmod{n}",+ id="named-operators",+ ),+ pytest.param(+ r"\left\{ x \middle| x > 0 \right\} + \big( \langle u, v"+ r" \rangle \big) + \lfloor x \rfloor + \lceil y \rceil + \|v\|"+ r" + \Bigl[ z \Bigr]",+ id="delimiters",+ ),+ pytest.param(+ r"\hat{x} + \bar{y} + \tilde{z} + \vec{v} + \dot{x} + \ddot{x}"+ r" + \widehat{xy} + \overline{AB} + \underbrace{a + b}_{2}",+ id="accents",+ ),+ pytest.param(+ r"\mathcal{O}(n \log n) + \mathsf{T} + \mathtt{x}",+ id="math-alphabets",+ ),+ pytest.param(+ r"\sum\limits_{i} {\scriptstyle x} + \int\nolimits_0^1",+ id="styles-and-limits",+ ),+ pytest.param(+ r"a\,b\:c\;d\!e\ f \quad g \qquad h \enspace i \thinspace j",+ id="spacing",+ ),+ pytest.param(+ r"50\% + \#S + \mathrm{max\_iter} + A \& B",+ id="escaped-characters",+ ),+ pytest.param("f'(x) + g''(x)", id="prime"),+ pytest.param(r"25^\circ", id="degrees"),+ pytest.param("E =\r\nmc^2", id="crlf-line-break"),+ ],+)[email protected]("delimiter", ["$", "$$"])+def test_supported_math_keeps_rendering(math, delimiter):+ result = LaTeXExporter().export_to_latex(+ f"# Report\n\nThe identity {delimiter}{math}{delimiter} holds."+ )++ assert f"{delimiter}{math}{delimiter}" in result+++def test_crlf_display_block_keeps_rendering():+ """Legacy report_content rows store CRLF newlines (see ``_BLOCK_END``)."""+ report = "# Report\r\n\r\nBefore\r\n$$\r\nE = mc^2\r\n$$\r\nafter.\r\n"++ result = LaTeXExporter().export_to_latex(report)++ assert "$$\r\nE = mc^2\r\n$$" in result++[email protected]("delimiter", ["$", "$$"])+def test_math_with_a_lone_cr_stays_literal(delimiter):+ """TeX ends a line at a lone CR, so two of them make a blank line.++ ``_BLOCK_END`` only sees blank lines that end in LF, so such a span can+ reach the check; accepting it would put a paragraph break inside math.+ """+ body = _export_body("a\r\rb", delimiter)++ assert f"{delimiter}a\r\rb{delimiter}" not in body+ assert delimiter.replace("$", "\\$") in body+++# ---------------------------------------------------------------------------+# Quarto export. The front matter declares a ``pdf`` format, so a+# ``quarto render`` that builds the PDF hands each math span to Pandoc's+# LaTeX writer, which emits math verbatim. The same allowlist that guards+# the LaTeX export must therefore guard the Quarto export: an unsafe span is+# escaped to literal text, a safe span is kept as math.+++def _quarto_span_region(math: str, delimiter: str) -> str:+ """The exported ``.qmd`` body between fixed sentinels around the span."""+ report = f"# Report\n\nBefore {delimiter}{math}{delimiter} after."+ qmd = QuartoExporter().export_to_quarto(report, "Report")+ return qmd.split("Before ", 1)[1].split(" after.", 1)[0]+++ ("math", "text"),+ [+ (r"\input{/etc/passwd}", "passwd"),+ (r"\write18{touch pwn}", "pwn"),+ (r"\immediate\write18{touch pwn}", "pwn"),+ (r"\global\catcode`\|=0\relax", "catcode"),+ (r"\csname input\endcsname{/etc/passwd}", "passwd"),+ ("^^5cinput{/etc/passwd}", "passwd"),+ # The caret rules the LaTeX test pins apply on this path too.+ (r"\^^69nput{/etc/passwd}", "passwd"),+ (r"\in^^0ut{/etc/passwd}", "passwd"),+ ],+)[email protected]("delimiter", ["$", "$$"])+def test_unsafe_report_math_is_escaped_in_quarto(math, text, delimiter):+ region = _quarto_span_region(math, delimiter)++ # The span is no longer math, and nothing was dropped.+ assert f"{delimiter}{math}{delimiter}" not in region+ assert text in region+ # Dollars are escaped, so Pandoc never shifts into math on this span.+ assert "\\$" in region+ assert re.search(r"(?<!\\)\$", region) is None+ # Every backslash is escaped, so no control sequence survives for a+ # ``raw_tex``-enabled reader, and no ``^^`` encoding is left.+ assert re.search(r"(?<!\\)\\[A-Za-z]", region) is None+ assert "^^" not in region+++ "math",+ [+ r"\frac{1}{2} + \sqrt{x} = \alpha",+ r"\sum_{i=1}^{n} i = \frac{n(n+1)}{2}",+ "E = mc^2",+ ],+)[email protected]("delimiter", ["$", "$$"])+def test_safe_report_math_stays_math_in_quarto(math, delimiter):+ region = _quarto_span_region(math, delimiter)++ # A safe span is handed to Pandoc as math, unchanged.+ assert f"{delimiter}{math}{delimiter}" in regiondiff --git a/tests/web/services/test_export_generation_contracts.py b/tests/web/services/test_export_generation_contracts.pyindex 18b42bd27b..56381a9abc 100644--- a/tests/web/services/test_export_generation_contracts.py+++ b/tests/web/services/test_export_generation_contracts.py@@ -255,22 +255,13 @@ class TestLaTeXBodyEscaping:assert "\\%" in bodyassert "\\_" 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(+ def test_a_control_sequence_inside_display_math_is_literal_text(self,):- """``$$...$$`` content is emitted verbatim, control sequences included.+ """An unsupported command in ``$$...$$`` must be inert text.- ``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.+ ``test_citation_exporter_edge_cases.py`` still pins that ordinary+ display math such as ``$$E = mc^2$$`` survives unescaped."""report = "Benign report with no stray dollars.\n\n$$\\relax$$\n"