Skip to content

~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.

fix(web): validate document source links and isolate new tabs (#7100)

LearningCircuit55bf42fef5dc
diff --git a/changelog.d/+document-source-link-policy.security.md b/changelog.d/+document-source-link-policy.security.md
new file mode 100644
index 0000000000..b618122864
--- /dev/null
+++ b/changelog.d/+document-source-link-policy.security.md
@@ -0,0 +1 @@
+Validate document source links as HTTP(S) before rendering them while preserving valid paths and query strings, and add explicit new-tab isolation to document and benchmark links.
diff --git a/src/local_deep_research/security/url_validator.py b/src/local_deep_research/security/url_validator.py
index de13f73df0..01094b43ba 100644
--- a/src/local_deep_research/security/url_validator.py
+++ b/src/local_deep_research/security/url_validator.py
@@ -282,6 +282,35 @@ class URLValidator:
return None
+ @staticmethod
+ def is_safe_http_link(url: object) -> bool:
+ """Allow absolute HTTP(S) links without interpreting path/query data.
+
+ Literal percent signs, entity-like query values and trailing-dot hosts
+ are valid in browser links. Callback-specific suspicious-pattern checks
+ would reject them. Callers must still HTML-escape the URL in a quoted
+ attribute; this policy does not authorize server-side requests.
+ """
+ if not isinstance(url, str) or not url:
+ return False
+
+ # Browsers and URL parsers can strip raw control characters. Reject
+ # those ambiguous inputs while preserving percent-encoded URL data.
+ if any(ord(char) < 0x20 or ord(char) == 0x7F for char in url):
+ return False
+
+ try:
+ parsed = urlparse(url)
+ # Accessing port also validates its numeric form and range.
+ port = parsed.port
+ return (
+ parsed.scheme in ("http", "https")
+ and bool(parsed.hostname)
+ and (port is None or 0 <= port <= 65535)
+ )
+ except ValueError:
+ return False
+
@staticmethod
def validate_http_url(url: str) -> bool:
"""
diff --git a/src/local_deep_research/web/routers/library.py b/src/local_deep_research/web/routers/library.py
index 3d3bb67aa4..bb98ec148e 100644
--- a/src/local_deep_research/web/routers/library.py
+++ b/src/local_deep_research/web/routers/library.py
@@ -36,6 +36,7 @@ from ...database.models.library import (
Collection,
)
from ...library.download_management import ResourceFilter
+from ...security.url_validator import URLValidator
from ...research_library.services.download_service import DownloadService
from ...research_library.services.library_service import LibraryService
from ...research_library.services.pdf_storage_manager import PDFStorageManager
@@ -318,10 +319,21 @@ def document_details_page(
# here; the sibling /api/ routes keep JSON.
return HTMLResponse("Document not found", status_code=404)
+ # HTML escaping does not make a stored javascript:/data: URL safe to
+ # navigate. Keep rejected values visible as text, but never as links.
+ original_url = document.get("original_url")
+ original_source_url = (
+ original_url if URLValidator.is_safe_http_link(original_url) else None
+ )
+
return templates.TemplateResponse(
request=request,
name="pages/document_details.html",
- context={"request": request, "document": document},
+ context={
+ "request": request,
+ "document": document,
+ "original_source_url": original_source_url,
+ },
)
diff --git a/src/local_deep_research/web/templates/pages/benchmark.html b/src/local_deep_research/web/templates/pages/benchmark.html
index b8a5a4ad5f..619e7c756e 100644
--- a/src/local_deep_research/web/templates/pages/benchmark.html
+++ b/src/local_deep_research/web/templates/pages/benchmark.html
@@ -189,7 +189,7 @@
</div>
<div style="font-size: 0.9rem; color: var(--text-muted); text-align: center;">
- <i aria-hidden="true" class="fas fa-info-circle"></i> To change any settings, go to <a href="/" target="_blank" style="color: var(--primary-color);">Settings Dashboard</a>
+ <i aria-hidden="true" class="fas fa-info-circle"></i> To change any settings, go to <a href="/" target="_blank" rel="noopener noreferrer" style="color: var(--primary-color);">Settings Dashboard</a>
</div>
</div>
</fieldset>
diff --git a/src/local_deep_research/web/templates/pages/document_details.html b/src/local_deep_research/web/templates/pages/document_details.html
index 324caa0fed..2d401a7bb8 100644
--- a/src/local_deep_research/web/templates/pages/document_details.html
+++ b/src/local_deep_research/web/templates/pages/document_details.html
@@ -28,13 +28,13 @@
<div class="ldr-document-actions">
{% if document.has_pdf %}
- <a href="/library/document/{{ document.id }}/pdf" target="_blank" class="ldr-btn ldr-btn-danger">
+ <a href="/library/document/{{ document.id }}/pdf" target="_blank" rel="noopener noreferrer" class="ldr-btn ldr-btn-danger">
<i aria-hidden="true" class="fas fa-file-pdf"></i> View PDF
</a>
{% endif %}
{% if document.has_text_db %}
- <a href="/library/document/{{ document.id }}/txt" target="_blank" class="ldr-btn ldr-btn-success">
+ <a href="/library/document/{{ document.id }}/txt" target="_blank" rel="noopener noreferrer" class="ldr-btn ldr-btn-success">
<i aria-hidden="true" class="fas fa-file-alt"></i> View Text
</a>
{% endif %}
@@ -45,8 +45,10 @@
</a>
{% endif %}
- {% if document.original_url %}
- <a href="{{ document.original_url }}" target="_blank" rel="noopener noreferrer" class="ldr-btn ldr-btn-secondary">
+ {% if original_source_url %}
+ {# Validated by URLValidator.is_safe_http_link in document_details_page. #}
+ {# nosemgrep: generic.html-templates.security.var-in-href.var-in-href, reason: URL validated by URLValidator.is_safe_http_link #}
+ <a href="{{ original_source_url }}" target="_blank" rel="noopener noreferrer" class="ldr-btn ldr-btn-secondary">
<i aria-hidden="true" class="fas fa-external-link-alt"></i> Original Source
</a>
{% endif %}
@@ -256,7 +258,13 @@
<h2><i aria-hidden="true" class="fas fa-link"></i> Source URL</h2>
<div class="ldr-metadata-item">
<div class="ldr-metadata-value">
- <a href="{{ document.original_url }}" target="_blank" rel="noopener noreferrer">{{ document.original_url }}</a>
+ {% if original_source_url %}
+ {# Validated HTTP(S) URL; the rejected original remains escaped text below. #}
+ {# nosemgrep: generic.html-templates.security.var-in-href.var-in-href, reason: URL validated by URLValidator.is_safe_http_link #}
+ <a href="{{ original_source_url }}" target="_blank" rel="noopener noreferrer">{{ document.original_url }}</a>
+ {% else %}
+ {{ document.original_url }}
+ {% endif %}
</div>
</div>
</div>
diff --git a/tests/security/test_url_validator.py b/tests/security/test_url_validator.py
index 58d6999b45..4fe463b898 100644
--- a/tests/security/test_url_validator.py
+++ b/tests/security/test_url_validator.py
@@ -10,6 +10,40 @@ from local_deep_research.security.url_validator import (
)
+class TestHttpLinkPolicy:
+ """Browser links must not reuse callback-specific encoding restrictions."""
+
+ @pytest.mark.parametrize(
+ "url",
+ [
+ "https://example.org/100%25Efficiency.pdf",
+ "https://example.org/paper.pdf?q=50%25effect",
+ "https://example.org/paper.pdf?formula=A&B;C",
+ "https://example.org./paper.pdf",
+ ],
+ )
+ def test_link_policy_preserves_callback_restrictions(self, url):
+ assert URLValidator.is_safe_http_link(url)
+ with pytest.raises(URLValidationError):
+ URLValidator.validate_http_url(url)
+
+ @pytest.mark.parametrize(
+ "value", [None, "", 42, b"https://example.org", {}]
+ )
+ def test_non_url_metadata_is_not_a_link(self, value):
+ assert URLValidator.is_safe_http_link(value) is False
+
+ @pytest.mark.parametrize(
+ "control", ["\x00", "\t", "\n", "\r", "\x1f", "\x7f"]
+ )
+ def test_raw_control_characters_are_not_normalized_into_links(
+ self, control
+ ):
+ assert not URLValidator.is_safe_http_link(
+ f"https://example.org/{control}paper"
+ )
+
+
class TestIsUnsafeScheme:
"""Tests for URLValidator.is_unsafe_scheme()."""
diff --git a/tests/web/routers/test_document_source_links.py b/tests/web/routers/test_document_source_links.py
new file mode 100644
index 0000000000..654ef2a224
--- /dev/null
+++ b/tests/web/routers/test_document_source_links.py
@@ -0,0 +1,138 @@
+"""Exercise stored source URLs through the route and real document template."""
+
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+from bs4 import BeautifulSoup
+from jinja2 import ChoiceLoader, DictLoader
+from starlette.requests import Request
+
+from local_deep_research.web.routers import library
+
+
+def render_document(monkeypatch):
+ env = library.templates.env.overlay(
+ loader=ChoiceLoader(
+ [
+ DictLoader({"base.html": "{% block content %}{% endblock %}"}),
+ library.templates.env.loader,
+ ]
+ )
+ )
+ monkeypatch.setattr(
+ library.templates,
+ "TemplateResponse",
+ lambda **kwargs: env.get_template(kwargs["name"]).render(
+ kwargs["context"]
+ ),
+ )
+
+ def render(url):
+ document = {
+ "id": "doc-1",
+ "document_title": "Example document",
+ "original_url": url,
+ "has_pdf": True,
+ "has_text_db": True,
+ }
+ monkeypatch.setattr(
+ library,
+ "LibraryService",
+ lambda username: SimpleNamespace(
+ get_document_by_id=lambda document_id: document
+ ),
+ )
+ request = Request({"type": "http", "method": "GET", "path": "/"})
+ html = library.document_details_page(request, "doc-1", "alice")
+ return BeautifulSoup(html, "html.parser")
+
+ return render
+
+
+ "url",
+ [
+ "javascript:alert(1)",
+ "JaVaScRiPt:alert(1)",
+ "java\nscript:alert(1)",
+ "\tjavascript:alert(1)",
+ "data:text/html,<svg onload=alert(1)>",
+ "vbscript:msgbox(1)",
+ "file:///etc/passwd",
+ "//example.com/paper",
+ "/relative/paper",
+ "#fragment",
+ "https:",
+ "https://[invalid/paper",
+ "https://:443/paper",
+ "https://example.org:invalid/paper",
+ "https://example.org:65536/paper",
+ "https://example.org/\tpaper",
+ "javascript&#58;alert(1)",
+ "javascript%3Aalert(1)",
+ 'javascript:alert(1)"><img src=x onerror=alert(1)>',
+ ],
+)
+def test_rejected_source_url_is_visible_but_never_linked(render_document, url):
+ soup = render_document(url)
+ assert url in soup.get_text()
+ assert not soup.find(
+ "a", string=lambda text: text and "Original Source" in text
+ )
+ assert [a["href"] for a in soup.find_all("a")] == [
+ "/library",
+ "/library/document/doc-1/pdf",
+ "/library/document/doc-1/txt",
+ ]
+ assert not soup.select("script, img, svg, [onerror], [onload]")
+
+
+ "url",
+ [
+ "https://example.org/paper?x=1&y=2#results",
+ "http://localhost:8080/paper",
+ "https://[2001:db8::1]/paper",
+ 'https://example.org/paper?q="quoted"',
+ # A literal percent followed by hexadecimal-looking filename/query
+ # text is not double encoding. These were rejected by callback policy.
+ "https://example.org/100%25Efficiency.pdf",
+ "https://example.org/paper.pdf?q=50%25effect",
+ "https://example.org/paper.pdf?formula=A&B;C",
+ "https://example.org./paper.pdf",
+ "https://example.org/paper.pdf?next=https%3A%2F%2Fexample.org%2Fa%2520b",
+ "HTTPS://example.org/paper.pdf",
+ 'https://example.org/paper?q="><img src=x onerror=alert(1)>&lt;script&gt;',
+ ],
+)
+def test_http_source_links_and_download_links_are_preserved(
+ render_document, url
+):
+ soup = render_document(url)
+ source_links = soup.find_all("a", href=url)
+ assert len(source_links) == 2
+ assert source_links[1].get_text() == url
+ links = soup.select('a[target="_blank"]')
+ assert len(links) == 4
+ assert all({"noopener", "noreferrer"} <= set(a["rel"]) for a in links)
+ assert not soup.select("[onerror], [onload]")
+
+
[email protected]("url", [None, ""])
+def test_absent_source_keeps_document_downloads(render_document, url):
+ soup = render_document(url)
+ assert len(soup.select('a[target="_blank"]')) == 2
+ assert "Source URL" not in soup.get_text()
+
+
+def test_benchmark_new_tab_link_is_isolated():
+ # Inspect the actual anchor; rendering the benchmark form requires its
+ # unrelated provider/model context.
+ template_dir = Path(library.templates.env.loader.searchpath[0])
+ soup = BeautifulSoup(
+ (template_dir / "pages/benchmark.html").read_text(), "html.parser"
+ )
+ link = soup.find("a", href="/", target="_blank")
+ assert {"noopener", "noreferrer"} <= set(link["rel"])