~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(quarto): escape the YAML front-matter title in the .qmd export (#6424)
LearningCircuit1b49cb1ff6d9
diff --git a/changelog.d/6424.security.md b/changelog.d/6424.security.mdnew file mode 100644index 0000000000..c7874a16f7--- /dev/null+++ b/changelog.d/6424.security.md@@ -0,0 +1 @@+Quarto export now escapes the report title to YAML double-quoted scalar rules before interpolating it into the .qmd front matter: quotes, backslashes, newlines, C0 and C1 control characters, and the Unicode line separators U+2028/U+2029 in web-derived or caller-supplied titles can no longer break front-matter parsing or inject YAML keys.diff --git a/src/local_deep_research/text_optimization/citation_formatter.py b/src/local_deep_research/text_optimization/citation_formatter.pyindex 05cfae993e..4543fef727 100644--- a/src/local_deep_research/text_optimization/citation_formatter.py+++ b/src/local_deep_research/text_optimization/citation_formatter.py@@ -1128,6 +1128,42 @@ def _defuse_quarto_cells(body: str) -> str:return body+# Characters that must be escaped inside a YAML double-quoted scalar: the+# quote and backslash the double-quoted form itself requires, plus the+# control/line-break range ``is_line_breaking_char()`` above defines once+# for every producer in this module (C0, DEL, C1, and the Unicode line+# separators U+2028/U+2029).+_YAML_DQ_SPECIALS_RE = re.compile(r'["\\\x00-\x1f\x7f-\x9f\u2028\u2029]')+++def _yaml_double_quote(value: str) -> str:+ r"""Render *value* as a YAML double-quoted scalar.++ Report titles derive from web-influenced content, so a bare+ interpolation into ``title: "..."`` lets a quote end the scalar+ early (front matter stops parsing) or a newline inject further+ front-matter keys. Escaping to YAML double-quoted rules keeps the+ value a single scalar that parses back exactly.+ """++ def _escape(match: re.Match) -> str:+ ch = match.group()+ if ch == '"':+ return '\\"'+ if ch == "\\":+ return "\\\\"+ if ch == "\n":+ return "\\n"+ if ch == "\r":+ return "\\r"+ if ch == "\t":+ return "\\t"+ code = ord(ch)+ return f"\\x{code:02x}" if code <= 0xFF else f"\\u{code:04x}"++ return '"' + _YAML_DQ_SPECIALS_RE.sub(_escape, value) + '"'++class QuartoExporter:"""Export markdown documents to Quarto (.qmd) format."""@@ -1161,7 +1197,7 @@ class QuartoExporter:current_date = datetime.now(UTC).strftime("%Y-%m-%d")yaml_header = f"""----title: "{title}"+title: {_yaml_double_quote(title)}author: "Local Deep Research"date: "{current_date}"format:diff --git a/tests/text_optimization/test_quarto_yaml_title_escaping.py b/tests/text_optimization/test_quarto_yaml_title_escaping.pynew file mode 100644index 0000000000..22c9ca33a0--- /dev/null+++ b/tests/text_optimization/test_quarto_yaml_title_escaping.py@@ -0,0 +1,107 @@+"""YAML front-matter title contracts for the Quarto exporter.++The report title derives from web-influenced content (the first heading+of the report, or a caller-supplied title) and is interpolated into the+generated ``.qmd`` front matter. The front matter must therefore always+parse back to the exact title string: a ``"`` that breaks out of the+quoted scalar turns the export into a document whose YAML header fails+parse (a render-time denial of service), and an embedded newline can+inject additional front-matter keys.++The quote-breakout and key-injection scenarios 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: backslash titles,+control characters, and the plain-title common path.+"""++from __future__ import annotations++import yaml++from local_deep_research.text_optimization.citation_formatter import (+ QuartoExporter,+)+++def _parse_front_matter(qmd: str) -> dict:+ """Parse the YAML front matter block of a rendered .qmd document."""+ assert qmd.startswith("---\n"), "document must open with a YAML block"+ end = qmd.index("\n---\n", 3)+ block = qmd[: end + 1]+ return yaml.safe_load(block[4:])+++class TestDerivedTitleStaysASingleScalar:+ """Titles pulled from the report heading must survive YAML parsing."""++ def test_backslash_in_derived_title_parses_back_exactly(self):+ exporter = QuartoExporter()+ content = "# A \\ LaTeX \\ backslash\n\nBody text.\n"+ result = exporter.export_to_quarto(content)++ front = _parse_front_matter(result)+ assert front["title"] == "A \\ LaTeX \\ backslash"+++class TestExplicitTitleCannotInjectFrontMatter:+ """Caller-supplied titles must not escape the title scalar."""++ def test_control_characters_are_escaped(self):+ exporter = QuartoExporter()+ result = exporter.export_to_quarto(+ "# Heading\n\nBody.\n", title="tab\there\x00nul"+ )++ front = _parse_front_matter(result)+ assert front["title"] == "tab\there\x00nul"+++class TestC1AndLineSeparatorTitlesRoundTrip:+ """C1 controls and the Unicode line separators must round-trip too.++ ``_yaml_double_quote`` escapes the same range ``is_line_breaking_char``+ defines elsewhere in this module: C0, DEL, the C1 block+ U+0080-U+009F, and U+2028/U+2029. YAML's printable production+ excludes C1 outright and folds U+0085 (NEL) into a space, so either+ one breaks the "parses back exactly" guarantee if left unescaped.+ """++ def test_c1_nel_and_line_separator_titles_parse_back_exactly(self):+ exporter = QuartoExporter()++ c1_front = _parse_front_matter(+ exporter.export_to_quarto(+ "# Heading\n\nBody.\n", title="Smart\x93quote heading"+ )+ )+ assert c1_front["title"] == "Smart\x93quote heading"++ nel_front = _parse_front_matter(+ exporter.export_to_quarto(+ "# Heading\n\nBody.\n", title="Before\x85after"+ )+ )+ assert nel_front["title"] == "Before\x85after"++ ls_front = _parse_front_matter(+ exporter.export_to_quarto(+ "# Heading\n\nBody.\n", title="Before\u2028after"+ )+ )+ assert ls_front["title"] == "Before\u2028after"+++class TestPlainTitleStillRenders:+ """The common case must keep working unchanged."""++ def test_plain_title_parses_with_expected_keys(self):+ exporter = QuartoExporter()+ result = exporter.export_to_quarto(+ "# Heading\n\nBody.\n", title="A plain title"+ )++ front = _parse_front_matter(result)+ assert front["title"] == "A plain title"+ assert front["author"] == "Local Deep Research"+ assert front["bibliography"] == "references.bib"diff --git a/tests/web/services/test_export_generation_contracts.py b/tests/web/services/test_export_generation_contracts.pyindex fbb6473dca..3ec8651395 100644--- a/tests/web/services/test_export_generation_contracts.py+++ b/tests/web/services/test_export_generation_contracts.py@@ -571,28 +571,19 @@ class TestQuartoCellGrammarFollowsQuarto:assert "```{.python}" in body- @pytest.mark.xfail(- strict=True,- reason=(- "LIVE DEFECT: citation_formatter.py:1026 interpolates title: "- '"{title}" unquoted, so a double quote closes the scalar '- "and following newlines open real top-level YAML keys -- "- "confirmed by round-tripping through yaml.safe_load. "- "project.pre-render names a script Quarto executes. "- ),- )def test_a_title_cannot_inject_front_matter_keys(self):- """The title is interpolated into ``title: "{title}"`` unquoted.+ """The title used to be interpolated into ``title: "{title}"``+ unquoted.- A ``"`` in the title closes the scalar and the newlines after it- open real top-level keys, so the exported document carries a- front matter the exporter never wrote. ``project.pre-render``- is the interesting one: ``quarto render`` runs it as a script- before rendering anything.+ A ``"`` in the title would close the scalar and the newlines+ after it would open real top-level keys, so the exported+ document could carry a front matter the exporter never wrote.+ ``project.pre-render`` would have been the interesting one:+ ``quarto render`` runs it as a script before rendering anything.Reachability note: the title is ``research.title orresearch.query``, i.e. the requesting user's own text, so today- this is self-directed. It is pinned because it is the same+ this is self-directed. It is pinned because it was the samemissing-quoting root cause as the LaTeX body, at a key thatexecutes rather than merely displays."""@@ -611,14 +602,6 @@ class TestQuartoCellGrammarFollowsQuarto:assert "project" not in parsedassert "attacker-script.sh" not in str(parsed.get("format", ""))- @pytest.mark.xfail(- strict=True,- reason=(- "LIVE DEFECT: same unquoted YAML scalar as above; the hostile "- "remainder escapes the title value instead of staying inside "- "it. "- ),- )def test_the_whole_hostile_title_stays_inside_the_title_scalar(self):"""Complementary framing of the same invariant: whatever thetitle contains, round-tripping the front matter must give the