~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(citations): gate a citation's link destination on its scheme (#6496)
Lukas0f4f57100523
diff --git a/changelog.d/6392.security.md b/changelog.d/6392.security.mdnew file mode 100644index 0000000000..ab7395f477--- /dev/null+++ b/changelog.d/6392.security.md@@ -0,0 +1,29 @@+Citation hyperlinks are built only from destinations that can safely be+followed, and only from the sanitized value. A source URL whose scheme is+outside `http`/`https` (`javascript:`, `data:`, `vbscript:`, `blob:`) no longer+reaches the `](url)` of a generated markdown link, whatever citation format is+selected; the citation degrades to a plain `[N]` bracket instead (#6392).++Further shapes are refused or neutralized, because a scheme check alone can be+walked around. A destination carrying a control character is refused: the+parser strips tabs, newlines and leading C0 controls only in order to read the+scheme, so they survive into the link, and a newline ends the destination and+turns the rest of the URL into document body. The scheme and control-character+checks also run on the destination with its HTML character references decoded:+marked and Python-Markdown copy it into the `href` as written, and the browser+then decodes `javascript:alert(1)` into a live `javascript:` link. The URL+is still emitted as written, so `&`-joined query strings keep working. A+scheme-less destination that names a host (`//host/x`, `///host/x`) is refused.+Characters markdown reads as syntax (unbalanced parentheses, spaces, angle+brackets, quotes) are percent-encoded, so a URL can no longer close the citation+link early and write a second, live link after it. IPv6 literals keep their+brackets and ordinary URLs keep resolving, since a server decodes `%29` back to+`)`.++Only `SOURCE_TAGGED_HYPERLINKS` checked the destination before, so every other+format relied on the browser's DOMPurify pass to strip a hostile href. An+exported `.md`, `.qmd` or `.tex` never went through that pass at all. Both+places that build the citation map are covered: the Sources block parsed out of+the model's prose, and the structured search-result list used when the model+emits no Sources block. Relative URLs, which a library document uses, still+link as before.diff --git a/src/local_deep_research/text_optimization/citation_formatter.py b/src/local_deep_research/text_optimization/citation_formatter.pyindex 4543fef727..69a32c5107 100644--- a/src/local_deep_research/text_optimization/citation_formatter.py+++ b/src/local_deep_research/text_optimization/citation_formatter.py@@ -1,15 +1,131 @@"""Citation formatter for adding hyperlinks and alternative citation styles."""+import htmlimport refrom enum import Enumfrom typing import Any, Dict, List, Optional, Tuple-from urllib.parse import urlparse+from urllib.parse import urlparse, urlsplitfrom loguru import loggerfrom slugify import slugifyfrom ..content_fetcher.url_classifier import URLClassifier, URLType+# Schemes a citation may carry into a markdown link. An allowlist rather than a+# list of known-bad schemes: the formatter's job here is deciding what may be+# rendered, and `javascript:`, `data:`, `vbscript:`, `blob:` and whatever comes+# next all fail the same test without having to be enumerated. A relative URL+# stays allowed, because a library document is cited as `/library/...`. A+# destination that only looks scheme-less is still checked: its HTML-character-+# reference-decoded form must pass too (`javascript:` renders as a live+# `javascript:` href), and one that names a host (`//host/x`) is refused.+_LINKABLE_URL_SCHEMES = frozenset({"http", "https"})++# A scheme check alone is not enough. The destination is interpolated into+# `](...)`, so anything markdown would read as the end of that destination+# lets a source URL reopen markdown and write its own link past the gate.+# Percent-encoding keeps the link resolvable, since a server decodes `%20`+# back to a space. `[` and `]` are deliberately NOT encoded: they do not end a+# destination, and encoding them would break IPv6 literals (`http://[::1]/x`).+_DESTINATION_ESCAPES = {+ " ": "%20",+ "<": "%3C",+ ">": "%3E",+ '"': "%22",+ "'": "%27",+ "\\": "%5C",+ "`": "%60",+}++# Parentheses are the exception, and they are why this is two tables rather+# than one. CommonMark ends a bare destination at the first *unbalanced* `)`+# and carries balanced pairs through unharmed, so encoding them unconditionally+# rewrites ordinary URLs that nothing was wrong with -- Wikipedia alone titles+# thousands of articles `..._(disambiguation)` -- and the reader is shown a URL+# that is not the one the source served. A balanced destination is therefore+# left verbatim, and only an unbalanced one is encoded, which is exactly the+# case that would otherwise end early.+_PARENTHESIS_ESCAPES = {"(": "%28", ")": "%29"}+++def _parentheses_are_balanced(url: str) -> bool:+ """Whether markdown will carry every `(`/`)` in ``url`` inside the link."""+ depth = 0+ for character in url:+ if character == "(":+ depth += 1+ elif character == ")":+ depth -= 1+ if depth < 0:+ return False+ return depth == 0+++def _destination_is_refused(form: str) -> bool:+ """Whether one spelling of a destination fails the control or scheme rule."""+ if any(+ ord(character) < 0x20 or ord(character) == 0x7F for character in form+ ):+ return True+ try:+ scheme = urlsplit(form).scheme+ except ValueError:+ return True+ if scheme:+ return scheme not in _LINKABLE_URL_SCHEMES+ # No scheme reads as relative, except where a browser takes the host from+ # it: `//host/x`, and equally `///host/x` or `/\host/x`, which it resolves+ # the same way and ``urlsplit`` does not. Rendered from a file on disk,+ # an exported report resolves it to `file://host/x`.+ return form.lstrip().replace("\\", "/").startswith("//")+++def _safe_link_destination(url: str) -> str:+ """Return ``url`` ready to be interpolated into ``](...)``, or "" to refuse.++ Three things have to hold, and what comes back is the string that was+ checked rather than the one that came in:++ 1. No control character survives. ``urlsplit`` removes tabs and newlines+ and strips leading C0 controls only in order to *parse*; they stay in+ the string. A destination carrying a newline ends there and the rest is+ emitted as document body. NUL is not stripped at all, so+ ``java\x00script:`` parses as scheme-less and would otherwise pass.+ 2. The scheme is ``http``, ``https``, or absent. Looser than+ ``CitationFormatter._is_linkable_url``, which requires a scheme and is+ what SOURCE_TAGGED uses to decide whether to render a link at all; the+ other modes keep linking the relative URLs a library document uses. A+ scheme-less destination that names a host (``//host/x``) is refused.+ 3. What markdown would read as syntax is percent-encoded, so the gate+ cannot be walked around by ending the destination early.++ Rules 1 and 2 are checked on the character-reference-decoded form too.+ marked and Python-Markdown copy the destination into ``href`` as written,+ and the HTML parser then decodes ``javascript:alert(1)`` into a live+ ``javascript:`` URL. The decoded form is only checked, never emitted:+ rewriting ``&`` would break every query string with more than one+ parameter.++ The rendered markdown reaches the browser through DOMPurify, which strips a+ ``javascript:`` href before it reaches the DOM. That is one layer, and it is+ the only one today: an exported .md / .qmd / .tex and every other markdown+ consumer gets whatever this returns.++ Callers already skip sources whose URL is empty, so a refused destination+ leaves the citation as a plain ``[N]`` bracket instead of dropping it.+ """+ candidate = url.strip()+ if not candidate:+ return ""+ if _destination_is_refused(candidate) or _destination_is_refused(+ html.unescape(candidate)+ ):+ return ""+ escapes = dict(_DESTINATION_ESCAPES)+ if not _parentheses_are_balanced(candidate):+ escapes.update(_PARENTHESIS_ESCAPES)+ return "".join(escapes.get(character, character) for character in candidate)+# Marker emitted by ``IntegratedReportGenerator._format_final_report``# around the ``## Sources`` block it appends to the end of a detailed-mode@@ -493,7 +609,7 @@ class CitationFormatter:# though the Sources section beneath was fully populated. Accept# both keys so the hyperlink fallback works regardless of engine.def _src_url(s):- return s.get("url") or s.get("link") or ""+ return _safe_link_destination(s.get("url") or s.get("link") or "")adapted: Dict[str, Tuple[str, str]] = {str(s["index"]): (s.get("title", "Untitled"), _src_url(s))@@ -566,7 +682,7 @@ class CitationFormatter:for match in matches:citation_nums_str = match.group(1)title = match.group(2).strip()- url = match.group(3).strip() if match.group(3) else ""+ url = _safe_link_destination(match.group(3) or "")# Handle comma-separated citation numbers like [36, 3]# Split by comma and strip whitespace@@ -946,14 +1062,20 @@ class CitationFormatter:def _is_linkable_url(url: str) -> bool:"""Return True iff ``url`` is a http(s) URL safe to wrap in amarkdown hyperlink. Empty strings and file:// / local: schemes- are not linkable."""- if not url:+ are not linkable.++ Built on ``_safe_link_destination`` so the scheme and control-character+ rules live in one place; the only thing added here is that a scheme has+ to be PRESENT. SOURCE_TAGGED uses that to decide whether to render a+ link at all, which is why it, alone among the modes, does not link a+ relative URL.+ """+ if not _safe_link_destination(url):return Falsetry:- scheme = (urlparse(url).scheme or "").lower()- except (ValueError, AttributeError):+ return urlsplit(url.strip()).scheme in _LINKABLE_URL_SCHEMES+ except ValueError:return False- return scheme in ("http", "https")def _extract_source_label(self, url: str, collection: str | None = Nonediff --git a/tests/text_optimization/test_citation_formatter_contracts.py b/tests/text_optimization/test_citation_formatter_contracts.pyindex b21d3fc069..ab466738af 100644--- a/tests/text_optimization/test_citation_formatter_contracts.py+++ b/tests/text_optimization/test_citation_formatter_contracts.py@@ -22,6 +22,7 @@ failure, which is the signal to delete the marker. Each one names thedefect in its ``reason``."""+import htmlimport reimport time@@ -59,6 +60,23 @@ def answer_of(document: str) -> str:return document.split("## Sources")[0]+def cite_through_both_entry_points(mode: CitationMode, url: str) -> list:+ """Render ``See [1].`` with ``url`` as source 1, once per map builder.++ The Sources-block regex ends a URL at the first newline and ``\\s*`` eats+ leading whitespace, so only the structured source list hands the gate a+ destination that still carries them.+ """+ formatter = CitationFormatter(mode)+ document = make_doc("See [1].", f"[1] Evil\nURL: {url}")+ return [+ answer_of(formatter.format_document(document)),+ formatter.apply_inline_hyperlinks(+ "See [1].", [{"index": 1, "title": "Evil", "url": url}]+ ),+ ]++def bibliography_of_latex(latex: str) -> str:start = latex.index("\\begin{thebibliography}")end = latex.index("\\end{thebibliography}")@@ -362,19 +380,6 @@ class TestUrlSchemeHandling:"data:text/html;base64,PHNjcmlwdD5hbGVydCgxKTwvc2NyaXB0Pg==",],)- @pytest.mark.xfail(- strict=True,- reason=(- "SECURITY DEFECT: every mode except SOURCE_TAGGED interpolates "- "the Sources URL straight into '](url)' with no scheme check, "- "so a javascript:/data: URL supplied by a search result (or by "- "the LLM inventing a Sources line) becomes the href of the "- "citation. The web UI happens to run DOMPurify, but exported "- ".md/.qmd/.tex/.pdf and any other markdown consumer get the "- "live scheme. _is_linkable_url already exists and is only "- "wired into SOURCE_TAGGED."- ),- )def test_dangerous_scheme_is_never_emitted_as_a_destination(self, mode, url):@@ -383,18 +388,6 @@ class TestUrlSchemeHandling:assert "javascript:" not in resultassert "data:text/html" not in result- @pytest.mark.xfail(- strict=True,- reason=(- "SECURITY DEFECT: the URL is not escaped for the markdown link "- "destination, so a ')' in it closes the citation link early and "- "the remainder of the URL is emitted as live markdown. A "- "hostile source URL therefore injects an extra, "- "attacker-labelled hyperlink into the report prose. "- "_safe_bibtex_url guards the BibTeX path; the markdown path "- "has no equivalent."- ),- )def test_source_url_cannot_inject_a_second_markdown_link(self):hostile = ("https://good.example/x) [click here](https://evil.example/pwn"@@ -403,6 +396,276 @@ class TestUrlSchemeHandling:result = answer_of(CitationFormatter().format_document(document))assert "[click here](https://evil.example/pwn)" not in result+ @pytest.mark.parametrize("mode", UNGATED_LINK_MODES, ids=lambda m: m.value)+ @pytest.mark.parametrize(+ "url",+ [+ pytest.param("JaVaScRiPt:alert(1)", id="mixed case"),+ pytest.param(" javascript:alert(1)", id="leading spaces"),+ pytest.param(+ "\tjava\nscript:alert(1)", id="tab and newline inside"+ ),+ pytest.param("\x01javascript:alert(1)", id="leading control char"),+ pytest.param("vbscript:msgbox(1)", id="vbscript"),+ pytest.param("blob:https://good.example/x", id="blob"),+ pytest.param("javascript:alert(1)", id="named colon"),+ pytest.param("javascript:alert(1)", id="decimal colon"),+ pytest.param("javascript:alert(1)", id="decimal letter"),+ pytest.param("java	script:alert(1)", id="named tab"),+ ],+ )+ def test_a_dangerous_scheme_survives_no_spelling_of_itself(self, mode, url):+ """A browser lowercases the scheme, strips leading C0 controls and+ spaces, and removes tabs and newlines before it reads one. A check on+ the raw string therefore passes strings that still execute, which is+ why the allowlist is applied to the trimmed form.++ Before any of that, the HTML parser decodes character references in an+ ``href``, and marked and Python-Markdown copy the destination there as+ written, so ``javascript:`` is a spelling as well. The result is+ decoded and lowercased the same way before it is searched.++ ``blob:`` is in here for the other half: an allowlist is what makes a+ scheme nobody enumerated fail by default.+ """+ for result in cite_through_both_entry_points(mode, url):+ as_the_browser_reads_it = html.unescape(result).lower()++ assert "script:" not in as_the_browser_reads_it+ assert "blob:" not in as_the_browser_reads_it++ @pytest.mark.parametrize("mode", UNGATED_LINK_MODES, ids=lambda m: m.value)+ def test_an_unparseable_url_is_refused_rather_than_passed_through(+ self, mode+ ):+ """``urlsplit`` raises on a broken authority, and a dangerous scheme+ can carry one: ``javascript://[`` raises before the scheme is read.+ Treating "cannot parse" as "nothing to object to" would hand that+ straight to the renderer.+ """+ document = make_doc(+ "See [1].", "[1] Evil\nURL: javascript://[/alert(1)"+ )++ result = answer_of(CitationFormatter(mode).format_document(document))++ assert "javascript:" not in result++ def test_a_structured_source_list_is_gated_the_same_way(self):+ """The other entry point. ``format_document_with_sources`` is the+ fallback used when the LLM emits no Sources block, and it builds the+ same map from search-result dicts, where the URL came from a search+ engine rather than from the model.+ """+ sources = [+ {"index": 1, "title": "Evil", "url": "javascript:alert(1)"},+ {"index": 2, "title": "Real", "link": "https://good.example/x"},+ ]++ result = CitationFormatter().apply_inline_hyperlinks(+ "See [1] and [2].", sources+ )++ assert "javascript:" not in result+ assert "](https://good.example/x)" in result++ @pytest.mark.parametrize("mode", UNGATED_LINK_MODES, ids=lambda m: m.value)+ @pytest.mark.parametrize(+ "url",+ [+ pytest.param(+ "https://ok.example/x\n\n<img src=x onerror=alert(1)>",+ id="newline ends the destination",+ ),+ pytest.param("java\x00script:alert(1)", id="NUL inside the scheme"),+ pytest.param(+ "https://ok.example/\x07bell", id="bell inside the path"+ ),+ ],+ )+ def test_a_control_character_refuses_the_destination(self, mode, url):+ """``urlsplit`` removes tabs and newlines and strips leading C0+ controls to PARSE, and leaves them in the string. A destination that+ carries one ends there, and what follows is emitted as document body:+ an exported .md or .qmd then contains attacker-written markdown that+ never meets DOMPurify. NUL is not stripped at all, so it turns a+ dangerous scheme into a scheme-less string that would otherwise pass.+ """+ for result in cite_through_both_entry_points(mode, url):+ assert "onerror" not in result+ assert "script:" not in result+ assert "\x00" not in result+ assert "\x07" not in result++ @pytest.mark.parametrize("mode", UNGATED_LINK_MODES, ids=lambda m: m.value)+ def test_a_closing_paren_cannot_reopen_markdown(self, mode):+ """The scheme gate reads the whole string; markdown reads only up to+ the first unbalanced ``)``. Without escaping, everything after it is+ document body, so a destination can write its own link and put back+ exactly the scheme the gate refuses.+ """+ hostile = "https://good.example/x) [click here](javascript:alert(1)"+ document = make_doc("See [1].", f"[1] Benign\nURL: {hostile}")++ result = answer_of(CitationFormatter(mode).format_document(document))++ assert "](javascript:" not in result+ assert "javascript:alert(1))" not in result++ @pytest.mark.parametrize("mode", UNGATED_LINK_MODES, ids=lambda m: m.value)+ @pytest.mark.parametrize(+ ("character", "encoded"),+ [+ pytest.param(" ", "%20", id="space"),+ pytest.param("<", "%3C", id="angle open"),+ pytest.param(">", "%3E", id="angle close"),+ pytest.param('"', "%22", id="double quote"),+ pytest.param("'", "%27", id="single quote"),+ pytest.param("\\", "%5C", id="backslash"),+ pytest.param("`", "%60", id="backtick"),+ ],+ )+ def test_the_other_destination_escapes_each_close_the_same_breakout(+ self, mode, character, encoded+ ):+ """A paren is not the only way out of ``](...)``.++ Whitespace ends a bare destination outright and can open a title;+ ``<`` at the head switches markdown to the angle-bracket form, whose+ ``>`` then ends it; a quote or a backtick hands the rest of the line to+ another inline construct. Each one puts the attacker's text back into+ document body with markdown active, which is the same breakout the+ paren cell measures, so each is pinned rather than trusted to the table+ being complete.+ """+ hostile = f"https://good.example/x{character}TAIL"+ document = make_doc("See [1].", f"[1] Benign\nURL: {hostile}")++ result = answer_of(CitationFormatter(mode).format_document(document))++ # The whole destination, closing paren included: asserting only that+ # the character was encoded would still pass if everything after it had+ # been emitted as document body.+ assert f"](https://good.example/x{encoded}TAIL)" in result++ def test_a_balanced_pair_of_parens_is_left_verbatim(self):+ """Accept control for the escaping, and the reason it is not applied to+ every paren.++ Markdown ends a bare destination at the first *unbalanced* ``)`` and+ carries a balanced pair through unharmed, so there is nothing to defend+ against here. Encoding anyway rewrites an ordinary citation into a URL+ the source never served, which the reader sees and copies, and+ Wikipedia alone titles thousands of articles ``..._(disambiguation)``.+ """+ document = make_doc(+ "See [1].",+ "[1] Foo\nURL: https://en.wikipedia.org/wiki/Foo_(bar)",+ )++ result = answer_of(CitationFormatter().format_document(document))++ assert "](https://en.wikipedia.org/wiki/Foo_(bar))" in result+ assert "%28" not in result++ def test_an_unbalanced_paren_is_encoded(self):+ """The case the encoding exists for, and the one the balanced rule must+ not let through. A lone ``)`` ends the destination where it stands, so+ everything the source put after it would be emitted as document body+ with markdown active.+ """+ document = make_doc(+ "See [1].",+ "[1] Evil\nURL: https://example.com/a)[x](javascript:alert(1))",+ )++ result = answer_of(CitationFormatter().format_document(document))++ assert "https://example.com/a%29" in result+ assert "](javascript:" not in result++ def test_parens_that_balance_by_count_but_not_in_order_are_encoded(self):+ """Counting parens is not the same as balancing them. ``a)b(c`` has one+ of each and still ends the destination at the ``)``, so a rule that only+ compared totals would hand the attacker the same breakout with one+ character added.+ """+ document = make_doc(+ "See [1].",+ "[1] Evil\nURL: https://example.com/a)b(c",+ )++ result = answer_of(CitationFormatter().format_document(document))++ assert "https://example.com/a%29b%28c" in result++ def test_an_opener_that_is_never_closed_is_encoded(self):+ """The other direction. An unmatched ``(`` does not end the destination+ early, it makes the link fail to parse at all, so the citation renders+ as literal text with its URL exposed instead of as a link.+ """+ document = make_doc(+ "See [1].",+ "[1] Truncated\nURL: https://example.com/a(b",+ )++ result = answer_of(CitationFormatter().format_document(document))++ assert "https://example.com/a%28b" in result++ def test_an_ipv6_literal_is_left_alone(self):+ """Second accept control: brackets delimit an IPv6 host and do not end+ a markdown destination, so they must not be encoded.+ """+ document = make_doc("See [1].", "[1] Local\nURL: http://[::1]/x")++ result = answer_of(CitationFormatter().format_document(document))++ assert "](http://[::1]/x)" in result++ @pytest.mark.parametrize("mode", UNGATED_LINK_MODES, ids=lambda m: m.value)+ @pytest.mark.parametrize(+ "url",+ [+ pytest.param("https://good.example/q?b=1&c=2", id="amp"),+ pytest.param(+ "https://good.example/q?b=1&c=2©=3", id="bare ampersands"+ ),+ pytest.param("https://good.example/q?q=x<y", id="lt"),+ ],+ )+ def test_a_query_string_with_character_references_stays_linkable(+ self, mode, url+ ):+ """Accept control for the decoded check. Each of these decodes to+ another ``https`` URL, so it is linked, and linked as written: encoding+ ``&`` to ``%26`` would merge every multi-parameter query into one.+ """+ for result in cite_through_both_entry_points(mode, url):+ assert f"]({url})" in result++ @pytest.mark.parametrize("mode", UNGATED_LINK_MODES, ids=lambda m: m.value)+ @pytest.mark.parametrize(+ "url",+ [+ pytest.param("//evil.example/x", id="two slashes"),+ pytest.param("///evil.example/x", id="three slashes"),+ pytest.param("/\evil.example/x", id="encoded backslash"),+ pytest.param("//evil.example/x", id="encoded slashes"),+ pytest.param(" //evil.example/x", id="encoded leading space"),+ ],+ )+ def test_a_scheme_less_destination_cannot_name_a_host(self, mode, url):+ """A relative URL stays linkable because a library document is cited+ as ``/library/...``. On an http(s) page a browser reads all of these+ as a link to ``evil.example`` instead, and a report opened from disk+ resolves the two-slash and backslash forms to+ ``file://evil.example/x``. ``urlsplit`` gives the three-slash form an+ empty netloc, which is why the rule is not a netloc check.+ """+ for result in cite_through_both_entry_points(mode, url):+ assert "evil.example" not in result+def test_relative_url_still_produces_a_readable_label(self):"""Control: a benign non-http URL must not be dropped silently."""document = make_doc(