~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(exporters): strip control characters from safe filenames and fall back on an empty stem (#6435)
LearningCircuitc3cd5949a6aa
diff --git a/changelog.d/6435.security.md b/changelog.d/6435.security.mdnew file mode 100644index 0000000000..daea456324--- /dev/null+++ b/changelog.d/6435.security.md@@ -0,0 +1 @@+Quarto exports no longer write CR/LF/TAB raw into archive entry names from report titles (the shared filename sanitizer keeps whitespace so the download route's percent-encoding contract is unchanged; the zip-entry sink now strips the repo's shared line-breaking-character class -- C0 controls, DEL, C1 controls, and U+2028/U+2029 -- instead of a narrower ad-hoc range), and an all-punctuation or whitespace-only title falls back to the default name instead of producing a stemless dotfile.diff --git a/src/local_deep_research/exporters/base.py b/src/local_deep_research/exporters/base.pyindex 8156a2cc3e..c611842fa0 100644--- a/src/local_deep_research/exporters/base.py+++ b/src/local_deep_research/exporters/base.py@@ -125,11 +125,22 @@ class BaseExporter(ABC):A sanitized filename with the appropriate extension"""if title:+ # NOTE: the '\\s' class (CR/LF/TAB/unicode whitespace+ # included) is load-bearing for the HTTP download route:+ # its RFC 5987 quoting percent-encodes them (%0D%0A etc.),+ # a contract pinned by the hostile-input matrix. Consumers+ # that embed the stem raw in another container (the Quarto+ # export's zip entry names) must strip control characters+ # themselves -- see QuartoExporter.export.safe_title = (re.sub(r"[^\w\s-]", "", title).strip().replace(" ", "_")[:50])else:safe_title = "research_report"+ # An all-punctuation or whitespace-only title sanitises to an+ # empty stem: fall back rather than emitting a stemless dotfile.+ if not safe_title:+ safe_title = "research_report"return f"{safe_title}{self.file_extension}"def _prepend_title_if_needed(diff --git a/src/local_deep_research/exporters/quarto_exporter.py b/src/local_deep_research/exporters/quarto_exporter.pyindex 5f3e116f33..ea4caca7fd 100644--- a/src/local_deep_research/exporters/quarto_exporter.py+++ b/src/local_deep_research/exporters/quarto_exporter.py@@ -33,9 +33,11 @@ class QuartoExporter(BaseExporter):# Import here to avoid circular importsfrom ..text_optimization.citation_formatter import (QuartoExporter as LegacyQuartoExporter,+ is_line_breaking_char,)self._legacy = LegacyQuartoExporter()+ self._is_line_breaking_char = is_line_breaking_char@propertydef format_name(self) -> str:@@ -94,6 +96,16 @@ class QuartoExporter(BaseExporter):base_filename = self._generate_safe_filename(options.title)# Remove the .zip extension that _generate_safe_filename addssafe_title = base_filename.replace(self.file_extension, "")+ # The base sanitizer deliberately keeps '\\s' whitespace so+ # the HTTP route can percent-encode it (pinned contract).+ # But this stem is embedded RAW as a zip entry name, where+ # CR/LF/TAB would corrupt the archive listing. Strip with+ # the repo's one shared line-breaking-char class (C0, DEL,+ # C1, U+2028/U+2029) at this sink, rather than a narrower+ # ad-hoc range that would drift from it again.+ safe_title = "".join(+ ch for ch in safe_title if not self._is_line_breaking_char(ch)+ )# Create a zip file in memory containing both fileszip_buffer = io.BytesIO()diff --git a/tests/exporters/test_exporter_edge_cases.py b/tests/exporters/test_exporter_edge_cases.pyindex 7a44144782..d45aa72174 100644--- a/tests/exporters/test_exporter_edge_cases.py+++ b/tests/exporters/test_exporter_edge_cases.py@@ -14,12 +14,12 @@ class TestGenerateSafeFilenameEdgeCases:return LaTeXExporter()- def test_all_special_chars_produces_extension_only(self):- """Title with only special chars: regex removes all → empty safe_title."""+ def test_all_special_chars_falls_back_to_default(self):+ """Title with only special chars sanitises to an empty stem → default."""exporter = self._get_exporter()result = exporter._generate_safe_filename("@#$%^&*()")- # safe_title is "" (truthy title enters if-branch but regex strips all)- assert result == ".tex"+ # Empty-after-sanitising falls back rather than emitting '.tex'+ assert result == "research_report.tex"def test_exactly_50_chars_preserved(self):"""Title that is exactly 50 chars after cleaning should not be truncated."""@@ -36,12 +36,12 @@ class TestGenerateSafeFilenameEdgeCases:name_part = result.replace(".tex", "")assert len(name_part) == 50- def test_all_whitespace_title_produces_extension_only(self):- """Whitespace-only title is truthy but strip() makes it empty."""+ def test_all_whitespace_title_falls_back_to_default(self):+ """Whitespace-only title is truthy but sanitises to an empty stem."""exporter = self._get_exporter()result = exporter._generate_safe_filename(" ")- # " " is truthy → enters if-branch → regex keeps spaces → strip() → ""- assert result == ".tex"+ # Empty-after-sanitising falls back rather than emitting '.tex'+ assert result == "research_report.tex"class TestPrependTitleEdgeCases:diff --git a/tests/exporters/test_filename_sanitizer_edges.py b/tests/exporters/test_filename_sanitizer_edges.pynew file mode 100644index 0000000000..268ad0374e--- /dev/null+++ b/tests/exporters/test_filename_sanitizer_edges.py@@ -0,0 +1,136 @@+"""Control-character contracts for exporter filenames.++``_generate_safe_filename`` deliberately keeps the ``\\s`` class so the+HTTP download route can percent-encode CR/LF/TAB in the+Content-Disposition (``%0D%0A``) -- a behavior locked by the+hostile-input matrix and the promoted export contracts. The one+consumer that embeds the stem RAW in another container is the Quarto+export's zip entry names, so the control-character stripping lives at+that sink. These tests pin it there, plus the empty-stem fallback in+the shared helper.+"""++from __future__ import annotations++import io+import re+import zipfile++import pytest++from local_deep_research.exporters.base import ExportOptions+from local_deep_research.exporters.quarto_exporter import QuartoExporter+from local_deep_research.exporters.ris_exporter import RISExporter+++def _zip_entry_names(export_result) -> list[str]:+ with zipfile.ZipFile(io.BytesIO(export_result.content)) as archive:+ return archive.namelist()+++# Every code point that is both (a) matched by the base helper's ``\s``+# (so it survives ``_generate_safe_filename`` unstripped) and (b) matched+# by the sink's ``is_line_breaking_char`` class -- i.e. every control+# character actually reachable at the sink. Narrowing the sink's class+# by even one of these must fail test_every_live_sink_codepoint_is_stripped+# below.+_LIVE_SINK_CODEPOINTS = [+ ("\t", "TAB"),+ ("\n", "LF"),+ ("\v", "VT"),+ ("\f", "FF"),+ ("\r", "CR"),+ ("\x1c", "FS"),+ ("\x1d", "GS"),+ ("\x1e", "RS"),+ ("\x1f", "US"),+ ("\x85", "NEL"),+ ("\u2028", "LINE_SEPARATOR"),+ ("\u2029", "PARAGRAPH_SEPARATOR"),+]+++class TestQuartoEntryNamesStripControlCharacters:+ """Control characters must not ride raw into archive entry names."""++ @pytest.mark.parametrize(+ "char,name",+ _LIVE_SINK_CODEPOINTS,+ ids=[codepoint_name for _, codepoint_name in _LIVE_SINK_CODEPOINTS],+ )+ def test_every_live_sink_codepoint_is_stripped(self, char, name):+ """Each live code point must be absent from both archive+ surfaces: the entry names and the download filename.+ """+ exporter = QuartoExporter()++ result = exporter.export(+ "Body text",+ options=ExportOptions(title=f"Report{char}X-Evil: 1"),+ )++ for entry in _zip_entry_names(result):+ assert char not in entry, (+ f"{name} ({char!r}) survived raw in entry name {entry!r}"+ )+ assert char not in result.filename, (+ f"{name} ({char!r}) survived raw in download filename "+ f"{result.filename!r}"+ )++ def test_crlf_title_yields_clean_two_entry_archive(self):+ exporter = QuartoExporter()++ result = exporter.export(+ "Body text",+ options=ExportOptions(title="a\r\nX-Evil: 1"),+ )++ entries = _zip_entry_names(result)+ # The archive always holds exactly the document and the+ # bibliography, regardless of title content -- pinning the+ # structural fact, not a specific threat.+ assert len(entries) == 2, entries+ for entry in entries:+ assert not re.search(r"[\x00-\x1f\x7f]", entry), (+ f"archive entry name {entry!r} carries control characters"+ )++ def test_tab_is_stripped_from_entries(self):+ """TAB is live at the sink: the helper keeps ``\\s``, which+ includes TAB, so it is the sink's own class removing it here --+ unlike NUL, which the helper already strips before the sink+ ever runs.+ """+ exporter = QuartoExporter()++ result = exporter.export(+ "Body text",+ options=ExportOptions(title="Re\tport_final"),+ )++ for entry in _zip_entry_names(result):+ assert not re.search(r"[\x00-\x1f\x7f]", entry), (+ f"archive entry name {entry!r} carries control characters"+ )+++class TestEmptyStemFallback:+ """Punctuation/whitespace-only titles fall back to the default stem."""++ def test_all_punctuation_title_falls_back(self):+ exporter = RISExporter()++ filename = exporter._generate_safe_filename("@#$%^&*()")++ assert filename == "research_report.ris"++ def test_quarto_empty_stem_still_names_its_entries(self):+ exporter = QuartoExporter()++ result = exporter.export(+ "Body text", options=ExportOptions(title="@#$%^&*()")+ )++ entries = _zip_entry_names(result)+ assert entries and all(not e.startswith(".") for e in entries), entriesdiff --git a/tests/web/services/test_export_generation_contracts.py b/tests/web/services/test_export_generation_contracts.pyindex 3ec8651395..236e8849e1 100644--- a/tests/web/services/test_export_generation_contracts.py+++ b/tests/web/services/test_export_generation_contracts.py@@ -647,49 +647,36 @@ class TestArchiveAndFilenameSafety:# so the assertions above are not passing on an empty string.assert any("cron" in name for name in names)- @pytest.mark.xfail(- strict=True,- reason=(- "LIVE DEFECT: _generate_safe_filename uses [^\\w\\s-], and "- "CR/LF/TAB match \\s so they are KEPT -- only the literal "- "space is replaced. The HTTP route is saved by "- "quote(filename, safe=''), but the raw value is also used "- "unquoted as a zip entry name. "- ),- )- def test_safe_filename_strips_control_characters(self):- """``_generate_safe_filename`` keeps CR, LF and TAB.+ def test_quarto_entry_names_strip_control_characters(self):+ """The shared helper keeps CR, LF and TAB -- by design.``re.sub(r"[^\\w\\s-]", "", title)`` treats them as ``\\s`` and- keeps them; only the literal space is then replaced. The export- route is saved by ``quote(filename, safe="")`` percent-encoding- them (asserted separately below), but the raw value is also used- unquoted as a zip entry name, and every future caller inherits a- sanitiser whose name promises more than it delivers.+ keeps them; the export route is saved by ``quote(filename,+ safe="")`` percent-encoding them (pinned in the route test+ below and in the hostile-input matrix, which locks ``%0D%0A``+ in the disposition). Stripping them in the shared helper would+ break that locked contract, so the raw consumer -- the Quarto+ export's zip entry names -- strips them at the sink instead:+ no archive entry may carry CR, LF or TAB."""- filename = LaTeXExporter()._generate_safe_filename(- FILENAME_HEADER_BREAKOUT+ _front, _body, names = _quarto_parts(+ "# Doc\n\nBody.\n", title=FILENAME_HEADER_BREAKOUT)- assert "Report" in filename # arrival- assert filename.endswith(".tex")- assert not any(ch in filename for ch in "\r\n\t")+ assert names+ for name in names:+ assert not any(ch in name for ch in "\r\n\t"), names+ # Arrival: the title's word characters did reach the entry+ # name, so the assertion above is not passing on an empty+ # string.+ assert any("Report" in name for name in names)- @pytest.mark.xfail(- strict=True,- reason=(- "LIVE DEFECT: an all-punctuation title sanitises to the empty "- "string, so the download is named '.tex' -- a stemless "- "dotfile. The None branch has the right fallback; the "- "empty-after-sanitising branch never reaches it. "- ),- )def test_a_title_of_only_punctuation_still_yields_a_named_file(self):- """An all-punctuation title sanitises to the empty string, so the- download is named ``.tex`` -- a dotfile with no stem, hidden on- Unix and rejected outright by some browsers. The ``None`` branch- already has the right fallback; the empty-after-sanitising branch- does not reach it.+ """An all-punctuation title sanitises to the empty string, which+ would otherwise download as ``.tex`` -- a dotfile with no stem,+ hidden on Unix and rejected outright by some browsers. The+ ``None`` branch and the empty-after-sanitising branch now share+ the same fallback (``base.py``'s empty-stem check)."""exporter = LaTeXExporter()@@ -1014,9 +1001,12 @@ class TestExportRouteContracts:in the filename, the route's percent-encoding must keep CR/LF outof the header value."""- raw_filename = LaTeXExporter()._generate_safe_filename(- FILENAME_HEADER_BREAKOUT- )+ # Route-level control: hand the route a hostile filename+ # directly, bypassing the sanitizer, so the percent-encoding+ # defence is pinned independently of it. CRLF in a title+ # reaches the route, is percent-encoded rather than stripped,+ # and never appears raw.+ raw_filename = f"{FILENAME_HEADER_BREAKOUT}.tex"response, _query, _export = _call_export_route(research_row=Mock(title="Report", query="q"),export_return=(b"content", raw_filename, "text/plain"),@@ -1026,10 +1016,10 @@ class TestExportRouteContracts:assert response.status_code == 200assert "Report" in disposition # arrival- # The CRLF the sanitiser let through is present in the header --- # percent-encoded, which is exactly what keeps it inert.- assert "%0D%0A" in disposition+ # The CRLF arrives raw at the route and leaves percent-encoded --+ # which is exactly what keeps it inert in the header value.assert not re.search(r"[\r\n]", disposition)+ assert "%0D%0A" in dispositionassert disposition.count(";") == 1def test_unknown_format_is_rejected_before_any_db_read(self):