~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(web): restore download filename fallbacks (#7290)
LearningCircuit5a85f00ab6fc
diff --git a/changelog.d/5929.bugfix.md b/changelog.d/5929.bugfix.mdnew file mode 100644index 0000000000..e761a9789f--- /dev/null+++ b/changelog.d/5929.bugfix.md@@ -0,0 +1 @@+Restore ASCII download filenames for clients that do not support Unicode filename headers when exporting research or saving library PDFs, while preserving the original Unicode names for modern clients.diff --git a/src/local_deep_research/web/routers/library.py b/src/local_deep_research/web/routers/library.pyindex 983c3aec64..e58e62e57b 100644--- a/src/local_deep_research/web/routers/library.py+++ b/src/local_deep_research/web/routers/library.py@@ -19,6 +19,7 @@ from ..dependencies.threadpool import (run_db_sync,)from ..template_config import templates+from ..utils.download_headers import build_content_dispositionimport osimport json@@ -578,12 +579,6 @@ def _serve_pdf(f"Serving PDF for document {document_id} ({len(pdf_bytes)} bytes)")filename = document.filename or "document.pdf"- # Filenames come from the DB (originally user-supplied at- # upload). A quote or CR/LF in the raw value would break out- # of the header. Use RFC 5987 encoding for a safe round-trip.- from urllib.parse import quote as _url_quote-- safe_filename = _url_quote(filename, safe="")# Plain Response, not StreamingResponse: the bytes are already# fully in memory, and iterating a BytesIO yields *lines* — it# splits on every 0x0A, which in binary PDF data occurs roughly@@ -593,8 +588,8 @@ def _serve_pdf(content=pdf_bytes,media_type="application/pdf",headers={- "Content-Disposition": (- f"inline; filename*=UTF-8''{safe_filename}"+ "Content-Disposition": build_content_disposition(+ filename, inline=True)},)diff --git a/src/local_deep_research/web/routers/research.py b/src/local_deep_research/web/routers/research.pyindex 734378ceea..8e4387ac35 100644--- a/src/local_deep_research/web/routers/research.py+++ b/src/local_deep_research/web/routers/research.py@@ -18,6 +18,7 @@ from ..dependencies.threadpool import (run_db_sync,)from ..template_config import templates+from ..utils.download_headers import build_content_disposition# Bounded preview for untrusted request-body values in log lines (#6191).from .notes import _log_value_preview@@ -3204,21 +3205,14 @@ def export_research_report(# ``Content-Length`` so the browser gets no download# progress. Same fix already applied to library.py's PDF# route; this is its sibling call site.- from urllib.parse import quotefrom fastapi.responses import Response- # The filename derives from the research title, which- # is user-supplied and may contain non-latin-1 text- # (CJK, Cyrillic, ...). Raw interpolation would raise- # at header encoding and 500 the export — use RFC 5987- # filename* encoding, same as library.py's PDF route.- safe_filename = quote(filename, safe="")return Response(content=export_content,media_type=mimetype,headers={- "Content-Disposition": (- f"attachment; filename*=UTF-8''{safe_filename}"+ "Content-Disposition": build_content_disposition(+ filename),},)diff --git a/src/local_deep_research/web/utils/download_headers.py b/src/local_deep_research/web/utils/download_headers.pynew file mode 100644index 0000000000..2df930a8cd--- /dev/null+++ b/src/local_deep_research/web/utils/download_headers.py@@ -0,0 +1,32 @@+"""Content-Disposition headers for in-memory downloads."""++import re+import unicodedata+from urllib.parse import quote+++def build_content_disposition(filename: str, *, inline: bool = False) -> str:+ """Keep Unicode names and offer a safe ASCII name to older clients.++ The fallback is deliberately conservative: punctuation that needs quoting+ or escaping, percent escapes and control characters become underscores.+ The extended parameter retains the original name using RFC 5987 encoding.+ """+ ascii_name = (+ unicodedata.normalize("NFKD", filename)+ .encode("ascii", "ignore")+ .decode("ascii")+ )+ ascii_name = ascii_name.replace("\\", "/").rsplit("/", 1)[-1]+ fallback = re.sub(r"[^a-zA-Z0-9._() -]", "_", ascii_name).strip()+ if not fallback.strip("."):+ fallback = "download"+ elif fallback.startswith("."):+ # An entirely non-Latin stem can leave only the file extension.+ fallback = "download" + fallback++ disposition = "inline" if inline else "attachment"+ return (+ f'{disposition}; filename="{fallback}"; '+ f"filename*=UTF-8''{quote(filename, safe='')}"+ )diff --git a/tests/security/test_hostile_input_matrix.py b/tests/security/test_hostile_input_matrix.pyindex d23808cc34..8afaf15e3e 100644--- a/tests/security/test_hostile_input_matrix.py+++ b/tests/security/test_hostile_input_matrix.py@@ -47,6 +47,7 @@ import ioimport itertoolsimport jsonimport os+import reimport threadingimport uuidfrom contextlib import suppress@@ -944,7 +945,8 @@ def test_export_content_disposition_cannot_be_injected_by_title(client):Under Flask this was ``send_file``; the port hand-builds the header, soa raw CR/LF or a non-latin-1 character in the title is the classicresponse-splitting / header-encoding-crash pair. The route uses- RFC 5987 ``filename*=UTF-8''`` with ``quote(filename, safe="")``.+ a quoted ASCII fallback plus RFC 5987 ``filename*=UTF-8''`` with+ ``quote(filename, safe="")``."""from local_deep_research.exporters import ExporterRegistry@@ -963,7 +965,8 @@ def test_export_content_disposition_cannot_be_injected_by_title(client):assert resp.status_code == 200, resp.text[:200]assert (resp.headers["content-disposition"]- == "attachment; filename*=UTF-8''My_Report.ris"+ == 'attachment; filename="My_Report.ris"; '+ "filename*=UTF-8''My_Report.ris"), resp.headers["content-disposition"]for title, must_not_contain, must_contain in (@@ -979,7 +982,9 @@ def test_export_content_disposition_cannot_be_injected_by_title(client):resp = _export(title)assert resp.status_code == 200, f"{title!r} -> {resp.text[:200]}"header = resp.headers["content-disposition"]- assert header.startswith("attachment; filename*=UTF-8''"), header+ plain, encoded = header.split("; filename*=UTF-8''")+ assert re.fullmatch(r'attachment; filename="[A-Za-z0-9._() -]+"', plain)+ assert ";" not in encoded, headerfor bad in must_not_contain:assert bad not in header, (f"{title!r} -> {header!r} contains {bad!r}"diff --git a/tests/security/test_injection_and_template_safety.py b/tests/security/test_injection_and_template_safety.pyindex 693cb81601..ce4df4b985 100644--- a/tests/security/test_injection_and_template_safety.py+++ b/tests/security/test_injection_and_template_safety.py@@ -453,6 +453,15 @@ def _sanitized(node: ast.expr, bindings: dict, depth: int = 0) -> bool:)if name in _SANITIZERS:return True+ # Removing surrounding whitespace cannot introduce header syntax,+ # but stripping an unsanitized value does not make it safe.+ if (+ isinstance(func, ast.Attribute)+ and func.attr == "strip"+ and not node.args+ and not node.keywords+ ):+ return _sanitized(func.value, bindings, depth + 1)return Falseif isinstance(node, ast.Name):bound = bindings.get(node.id)@@ -467,6 +476,10 @@ def _sanitized(node: ast.expr, bindings: dict, depth: int = 0) -> bool:)if isinstance(node, ast.BoolOp):return all(_sanitized(v, bindings, depth + 1) for v in node.values)+ if isinstance(node, ast.IfExp):+ return _sanitized(node.body, bindings, depth + 1) and _sanitized(+ node.orelse, bindings, depth + 1+ )return False@@ -555,6 +568,35 @@ def test_disposition_scanner_follows_a_sanitizer_through_two_hops():assert find_unsanitized_disposition(safe) == []+ "disposition,filename,offenders",+ [+ (+ '"inline" if inline else "attachment"',+ 're.sub(r"[^a-zA-Z0-9._() -]", "_", raw).strip()',+ [],+ ),+ ('raw if inline else "attachment"', "quote(raw)", ["disposition"]),+ ('"inline" if inline else raw', "quote(raw)", ["disposition"]),+ ('"attachment"', "raw.strip()", ["fallback"]),+ ('"attachment"', "quote(raw).strip(raw)", ["fallback"]),+ ('"attachment"', 'quote(raw).replace("safe", raw)', ["fallback"]),+ ],+)+def test_disposition_scanner_traces_choices_and_trimmed_names(+ disposition, filename, offenders+):+ source = (+ "def header(raw, inline):\n"+ f" disposition = {disposition}\n"+ f" fallback = {filename}\n"+ " return f'{disposition}; filename=\"{fallback}\"'\n"+ )+ assert [+ expr for _, expr in find_unsanitized_disposition(source)+ ] == offenders++def test_every_download_filename_is_sanitized():offenders = [f"{rel}:{line} {expr}"@@ -565,21 +607,38 @@ def test_every_download_filename_is_sanitized():def test_disposition_scanner_sees_the_real_download_headers():- """The census must be looking at actual header construction."""- count = 0- for _rel, src in _py_sources(SRC / "web"):+ """Pin both header builders and the shared helper's real route callers."""+ builders = set()+ shared_callers = set()+ for rel, src in _py_sources(SRC / "web"):tree = ast.parse(src)for node in ast.walk(tree):- if not isinstance(node, ast.JoinedStr):- continue- literal = "".join(- v.value- for v in node.values- if isinstance(v, ast.Constant) and isinstance(v.value, str)- )- if "filename" in literal.lower():- count += 1- assert count >= 3, f"expected the known download routes, found {count}"+ if isinstance(node, ast.JoinedStr):+ literal = "".join(+ v.value+ for v in node.values+ if isinstance(v, ast.Constant) and isinstance(v.value, str)+ )+ if "filename" in literal.lower():+ builders.add(rel)+ if isinstance(node, ast.Dict):+ for key, value in zip(node.keys, node.values):+ if (+ isinstance(key, ast.Constant)+ and key.value == "Content-Disposition"+ and isinstance(value, ast.Call)+ and isinstance(value.func, ast.Name)+ and value.func.id == "build_content_disposition"+ ):+ shared_callers.add(rel)+ assert {+ "web/routers/research.py",+ "web/utils/download_headers.py",+ } <= builders, builders+ assert {+ "web/routers/library.py",+ "web/routers/research.py",+ } <= shared_callers, shared_callersdef test_open_file_location_endpoints_accept_no_path():diff --git a/tests/web/routers/test_export_filename_encoding.py b/tests/web/routers/test_export_filename_encoding.pyindex 9dad79173e..d199d86cc1 100644--- a/tests/web/routers/test_export_filename_encoding.py+++ b/tests/web/routers/test_export_filename_encoding.py@@ -6,8 +6,8 @@ UnicodeEncodeError and 500'd the export whenever the title contained CJK,Cyrillic, or any other non-latin-1 text (the exporter's_generate_safe_filename keeps Unicode word characters — \\w isUnicode-aware). Flask's send_file handled this via RFC 2231/5987 encoding;-the route now does the same with filename*=UTF-8'' (matching library.py's-PDF route).+the route now emits filename*=UTF-8'' plus a plain ASCII fallback (matching+library.py's PDF route)."""from contextlib import contextmanager@@ -72,7 +72,8 @@ def test_non_latin1_filenames_export_without_crashing(filename):assert resp.status_code == 200disposition = resp.headers["content-disposition"]- assert disposition.startswith("attachment; filename*=UTF-8''")+ assert disposition.startswith('attachment; filename="')+ assert "filename*=UTF-8''" in dispositionassert quote(filename, safe="") in dispositiondiff --git a/tests/web/services/test_export_generation_contracts.py b/tests/web/services/test_export_generation_contracts.pyindex 62730638a9..c1301471a2 100644--- a/tests/web/services/test_export_generation_contracts.py+++ b/tests/web/services/test_export_generation_contracts.py@@ -1016,7 +1016,10 @@ class TestExportRouteContracts:# which is exactly what keeps it inert in the header value.assert not re.search(r"[\r\n]", disposition)assert "%0D%0A" in disposition- assert disposition.count(";") == 1+ # Only the two filename parameters may introduce separators.+ assert disposition.count(";") == 2+ assert 'filename="' in disposition+ assert "filename*=UTF-8''" in dispositiondef test_unknown_format_is_rejected_before_any_db_read(self):from local_deep_research.web.routers.research import (diff --git a/tests/web/test_encoding_and_non_ascii.py b/tests/web/test_encoding_and_non_ascii.pyindex 68fb0b3c3b..b8454310e5 100644--- a/tests/web/test_encoding_and_non_ascii.py+++ b/tests/web/test_encoding_and_non_ascii.py@@ -11,11 +11,11 @@ What this file covers, and what it deliberately leaves to its neighbours:* **Invalid UTF-8 in a JSON body** -- the headline defect (#5761), and thefull sweep of how far it reaches. Not covered anywhere else.-* **``Content-Disposition``** -- specifically the *missing plain- ``filename=`` fallback*. ``tests/web/routers/test_export_filename_+* **``Content-Disposition``** -- specifically the plain+ ``filename=`` fallback. ``tests/web/routers/test_export_filename_encoding.py`` already pins that the RFC 5987 ``filename*`` form isproduced and is injection-safe; it never asks whether a client that does- not implement RFC 5987 gets a usable name. It does not.+ not implement RFC 5987 gets a usable name. These tests cover both forms.* **A multipart part whose only name is ``filename*=UTF-8''...``** --Werkzeug parsed it as a file, Starlette does not parse it as a file atall.@@ -47,7 +47,9 @@ import asyncioimport ioimport jsonimport re+import uuidfrom pathlib import Path+from urllib.parse import quoteimport pytest@@ -561,7 +563,7 @@ class TestNonAsciiSurvivesTheResponseSide:# ===========================================================================-# 3. Content-Disposition: the missing plain filename= fallback+# 3. Content-Disposition: the plain filename= fallback# ===========================================================================#: A legacy client scans the header for a ``filename`` parameter. RFC 5987@@ -571,22 +573,6 @@ class TestNonAsciiSurvivesTheResponseSide:_PLAIN_FILENAME_PARAM = re.compile(r"(?:^|;)\s*filename\s*=")-def _content_disposition_expressions(path: Path) -> list[str]:- """Source of every ``"Content-Disposition": <value>`` in a module."""- tree = ast.parse(path.read_text(encoding="utf-8"))- found = []- for node in ast.walk(tree):- if not isinstance(node, ast.Dict):- continue- for key, value in zip(node.keys, node.values):- if (- isinstance(key, ast.Constant)- and key.value == "Content-Disposition"- ):- found.append(ast.unparse(value))- return found--class TestContentDispositionFilenameFallback:def test_werkzeug_always_emitted_a_plain_filename_parameter(self):"""EXECUTION-VERIFIED baseline (werkzeug 3.1.8).@@ -595,8 +581,7 @@ class TestContentDispositionFilenameFallback:download_name=...)``. Werkzeug's ``send_file`` emits ``filename=``alone for an ASCII name, and for a non-ASCII name emits BOTH: anNFKD-folded ASCII ``filename=`` and the RFC 5987 ``filename*=``.- It never emits ``filename*`` on its own -- which is what the port- does.+ It never emits ``filename*`` on its own."""from werkzeug.test import EnvironBuilderfrom werkzeug.utils import send_file@@ -617,7 +602,7 @@ class TestContentDispositionFilenameFallback:)def test_port_still_emits_the_rfc5987_form(self):- """Control for the two xfails below.+ """Control for the fallback tests below.They assert an ADDITION. If ``filename*`` had been dropped insteadof the fallback being missing, the diagnosis would be different --@@ -628,25 +613,6 @@ class TestContentDispositionFilenameFallback:assert "filename*=UTF-8''" in dispositionassert "%E7%A0%94" in disposition, disposition- @pytest.mark.xfail(- strict=True,- reason=(- "DEFECT: routers/research.py::export_research_report builds "- 'Content-Disposition as f"attachment; '- "filename*=UTF-8''{quote(filename)}\" and stops there. There "- "is no plain filename= parameter for ANY name, ASCII included "- "-- 'report.tex' ships as filename*=UTF-8''report.tex and "- "nothing else. Per RFC 6266 s4.3 a recipient that does not "- "implement RFC 5987 ignores filename* entirely and falls back "- "to the last path segment of the URL, so the export lands as "- "a file named after the research id with no extension. "- "werkzeug's send_file (what main used, see "- "test_werkzeug_always_emitted_a_plain_filename_parameter) "- "always emitted the plain parameter as well. Fix: emit "- '\'attachment; filename="<ascii-folded>"; '- "filename*=UTF-8''<quoted>', mirroring werkzeug's NFKD fold."- ),- )@pytest.mark.parametrize("filename",[@@ -661,33 +627,57 @@ class TestContentDispositionFilenameFallback:assert _PLAIN_FILENAME_PARAM.search(disposition), disposition- @pytest.mark.xfail(- strict=True,- reason=(- "DEFECT, same shape, sibling route: routers/library.py's PDF "- "view builds f\"inline; filename*=UTF-8''{quote(filename)}\" "- "with no plain filename= parameter. main served it with "- "send_file(..., as_attachment=False, "- "download_name=document.filename), which emitted one. A "- "browser that saves the inline PDF gets the document id "- "instead of the stored filename. Asserted statically because "- "reaching this route needs a user database, an encrypted "- "session and a stored PDF blob; the header template is a "- "literal in the source and that is the thing that is wrong."- ),+ @pytest.mark.parametrize("route_prefix", ["/library", "/library/api"])+ @pytest.mark.parametrize(+ "filename", ["report.pdf", "研究报告_2026.pdf", "исследование.pdf"])- def test_library_pdf_view_offers_an_ascii_filename_fallback(self):- expressions = _content_disposition_expressions(- SRC_WEB / "routers" / "library.py"+ def test_library_pdf_view_offers_an_ascii_filename_fallback(+ self, authenticated_client, route_prefix, filename+ ):+ """Read the real response for an authenticated, stored PDF."""+ from local_deep_research.database.models.library import (+ Document,+ DocumentBlob,+ SourceType,)- assert expressions, (- "no Content-Disposition header found in routers/library.py -- "- "the scan has stopped matching the source"+ from local_deep_research.database.session_context import (+ get_user_db_session,)- for expression in expressions:- assert "filename*=UTF-8''" in expression, expression- assert _PLAIN_FILENAME_PARAM.search(expression), expression+ username = authenticated_client.get("/auth/check").json()["username"]+ document_id = str(uuid.uuid4())+ pdf_bytes = b"%PDF-1.4\nfixture PDF\n%%EOF\n"+ with get_user_db_session(username) as session:+ source_type = session.query(SourceType).first()+ assert source_type is not None+ session.add(+ Document(+ id=document_id,+ source_type_id=source_type.id,+ document_hash=uuid.uuid4().hex,+ file_size=len(pdf_bytes),+ file_type="pdf",+ filename=filename,+ title="Download header fixture",+ status="completed",+ )+ )+ session.flush()+ session.add(+ DocumentBlob(document_id=document_id, pdf_binary=pdf_bytes)+ )+ session.commit()++ response = authenticated_client.get(+ f"{route_prefix}/document/{document_id}/pdf"+ )+ assert response.status_code == 200, response.text[:300]+ assert response.content == pdf_bytes+ assert response.headers["content-type"] == "application/pdf"+ disposition = response.headers["content-disposition"]+ assert disposition.startswith('inline; filename="')+ assert _PLAIN_FILENAME_PARAM.search(disposition), disposition+ assert f"filename*=UTF-8''{quote(filename, safe='')}" in dispositiondef _export_content_disposition(filename: str) -> str:diff --git a/tests/web/utils/test_download_headers.py b/tests/web/utils/test_download_headers.pynew file mode 100644index 0000000000..06b6df52a7--- /dev/null+++ b/tests/web/utils/test_download_headers.py@@ -0,0 +1,52 @@+"""Download names remain usable by both plain and extended-header clients."""++from urllib.parse import unquote++import pytest+from starlette.responses import Response+from werkzeug.http import parse_options_header++from local_deep_research.web.utils.download_headers import (+ build_content_disposition,+)++[email protected]("inline", [False, True], ids=["attachment", "inline"])+ ("filename", "fallback"),+ [+ ("report.pdf", "report.pdf"),+ ("Annual report (2026).tex", "Annual report (2026).tex"),+ ("Bericht über Käfer.pdf", "Bericht uber Kafer.pdf"),+ ("研究报告_2026.tex", "_2026.tex"),+ ("исследование.pdf", "download.pdf"),+ ("研究.tar.gz", "download.tar.gz"),+ ("研究", "download"),+ ("résumé 🚀.pdf", "resume .pdf"),+ ('report";extra="value.pdf', "report__extra__value.pdf"),+ ("report\r\nX-Injected: 1.pdf", "report__X-Injected_ 1.pdf"),+ ("report\x00\x1f\x7f.pdf", "report___.pdf"),+ ("report%22%0d%0a.pdf", "report_22_0d_0a.pdf"),+ ("../reports/report.pdf", "report.pdf"),+ (r"C:\reports\report.pdf", "report.pdf"),+ (" report.pdf ", "report.pdf"),+ ("", "download"),+ ("..", "download"),+ ],+)+def test_plain_and_extended_names(filename, fallback, inline):+ header = build_content_disposition(filename, inline=inline)+ response = Response(b"download", headers={"Content-Disposition": header})+ plain, extended = response.headers["content-disposition"].split(+ "; filename*=UTF-8''"+ )++ # Parse each form independently, like a legacy or an RFC 5987 client.+ disposition, options = parse_options_header(plain)+ assert disposition == ("inline" if inline else "attachment")+ assert options == {"filename": fallback}+ assert unquote(extended) == filename+ assert header.isascii()+ assert all(32 <= ord(char) < 127 for char in header)+ assert "x-injected" not in response.headers+ assert response.body == b"download"