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(content-fetcher): match academic sources on the URL's host (#6839)

Lukasf564f32ba8e9
diff --git a/changelog.d/6835.security.md b/changelog.d/6835.security.md
new file mode 100644
index 0000000000..758a85a98e
--- /dev/null
+++ b/changelog.d/6835.security.md
@@ -0,0 +1 @@
+A link is classified as a PubMed, PubMed Central, Semantic Scholar, bioRxiv, medRxiv, DOI or arXiv source only when the host it points to belongs to that source. A source domain in another site's path or query (`https://evil.example/doi.org/10.1234/x`), a look-alike host (`fakedoi.org`), a backslash in the authority (`https://evil.example\@doi.org/…`, which browsers and requests send to evil.example) or a port that is not a number no longer earns the source's tag, such as `[[doi-1]]`, or reaches that source's downloader, which could fetch the real article in the link's place.
diff --git a/src/local_deep_research/content_fetcher/url_classifier.py b/src/local_deep_research/content_fetcher/url_classifier.py
index 09beb2090a..576aada048 100644
--- a/src/local_deep_research/content_fetcher/url_classifier.py
+++ b/src/local_deep_research/content_fetcher/url_classifier.py
@@ -7,12 +7,13 @@ Determines the type of URL to route to the appropriate downloader.
import re
from enum import Enum
from typing import Optional
-from urllib.parse import urlparse
+from urllib.parse import ParseResult, urlparse
from ..utilities.arxiv import (
extract_arxiv_id as extract_arxiv_id_from_url,
is_arxiv_paper_url,
)
+from ..utilities.host_match import http_authority_host, is_host_or_subdomain
class URLType(Enum):
@@ -37,39 +38,46 @@ DANGEROUS_SCHEMES = {"javascript", "data", "file", "vbscript", "about"}
class URLClassifier:
"""Classifies URLs to determine the appropriate downloader."""
+ # Each source is a list of (host, path) pairs: the URL's host must be that
+ # host or a subdomain of it, and its path must start with the pattern.
+ # Both are read from the parsed URL. The patterns used to be searched for
+ # anywhere in the URL string, which also found them in another site's
+ # path or query (https://evil.example/doi.org/10.1234/x) and inside
+ # look-alike hosts (fakedoi.org), so such a URL was routed to the source's
+ # downloader and cited under its trusted tag (#6835).
+ # Note: paths are matched lowercased, as the whole URL was before.
+
# PubMed patterns
PUBMED_PATTERNS = [
- r"pubmed\.ncbi\.nlm\.nih\.gov/\d+",
- r"ncbi\.nlm\.nih\.gov/pubmed/\d+",
+ ("pubmed.ncbi.nlm.nih.gov", r"/\d+"),
+ ("ncbi.nlm.nih.gov", r"/pubmed/\d+"),
]
# PMC patterns (PubMed Central - full text)
- # Note: patterns match lowercase since URLs are lowercased before matching
PMC_PATTERNS = [
- r"ncbi\.nlm\.nih\.gov/pmc/articles/pmc",
- r"europepmc\.org/article/pmc",
- r"europepmc\.org/articles/pmc",
+ ("ncbi.nlm.nih.gov", r"/pmc/articles/pmc"),
+ ("europepmc.org", r"/article/pmc"),
+ ("europepmc.org", r"/articles/pmc"),
]
# Semantic Scholar patterns
SEMANTIC_SCHOLAR_PATTERNS = [
- r"semanticscholar\.org/paper/",
- r"api\.semanticscholar\.org/",
+ ("semanticscholar.org", r"/paper/"),
+ ("api.semanticscholar.org", r"/"),
]
# BioRxiv/MedRxiv patterns
BIORXIV_PATTERNS = [
- r"biorxiv\.org/content/",
+ ("biorxiv.org", r"/content/"),
]
MEDRXIV_PATTERNS = [
- r"medrxiv\.org/content/",
+ ("medrxiv.org", r"/content/"),
]
- # DOI patterns
+ # DOI patterns (dx.doi.org is a subdomain of doi.org)
DOI_PATTERNS = [
- r"doi\.org/10\.",
- r"dx\.doi\.org/10\.",
+ ("doi.org", r"/10\."),
]
@classmethod
@@ -109,33 +117,43 @@ class URLClassifier:
return URLType.PDF
# Check specific academic sources
- for pattern in cls.PMC_PATTERNS:
- if re.search(pattern, url_lower):
- return URLType.PMC
-
- for pattern in cls.PUBMED_PATTERNS:
- if re.search(pattern, url_lower):
- return URLType.PUBMED
-
- for pattern in cls.SEMANTIC_SCHOLAR_PATTERNS:
- if re.search(pattern, url_lower):
- return URLType.SEMANTIC_SCHOLAR
-
- for pattern in cls.BIORXIV_PATTERNS:
- if re.search(pattern, url_lower):
- return URLType.BIORXIV
-
- for pattern in cls.MEDRXIV_PATTERNS:
- if re.search(pattern, url_lower):
- return URLType.MEDRXIV
-
- for pattern in cls.DOI_PATTERNS:
- if re.search(pattern, url_lower):
- return URLType.DOI
+ host, path = cls._host_and_path(parsed, url_lower)
+ for url_type, patterns in (
+ (URLType.PMC, cls.PMC_PATTERNS),
+ (URLType.PUBMED, cls.PUBMED_PATTERNS),
+ (URLType.SEMANTIC_SCHOLAR, cls.SEMANTIC_SCHOLAR_PATTERNS),
+ (URLType.BIORXIV, cls.BIORXIV_PATTERNS),
+ (URLType.MEDRXIV, cls.MEDRXIV_PATTERNS),
+ (URLType.DOI, cls.DOI_PATTERNS),
+ ):
+ for domain, path_pattern in patterns:
+ if is_host_or_subdomain(host, domain) and re.match(
+ path_pattern, path
+ ):
+ return url_type
# Default to HTML for web pages
return URLType.HTML
+ @staticmethod
+ def _host_and_path(parsed: ParseResult, url_lower: str) -> tuple[str, str]:
+ """The host and path the source patterns are matched against.
+
+ A URL without a scheme ("doi.org/10.1234/x"), or with too few slashes
+ after it ("https:/doi.org/10.1234/x"), passes the scheme check in
+ ``classify``, and ``urlparse`` reads its host as part of the path. So
+ what follows the scheme is read again as a network-path reference,
+ which is how browsers read it. An authority the HTTP stack would read
+ differently has no host (``http_authority_host``) and matches nothing.
+ """
+ if not parsed.netloc:
+ rest = url_lower.split(":", 1)[1] if parsed.scheme else url_lower
+ try:
+ parsed = urlparse("//" + rest.lstrip("/"))
+ except ValueError:
+ return "", ""
+ return http_authority_host(parsed) or "", parsed.path
+
@classmethod
def _is_pdf_url(cls, url: str) -> bool:
"""Check if URL points directly to a PDF.
diff --git a/src/local_deep_research/utilities/arxiv.py b/src/local_deep_research/utilities/arxiv.py
index 82c4f7db1b..d59b2fd466 100644
--- a/src/local_deep_research/utilities/arxiv.py
+++ b/src/local_deep_research/utilities/arxiv.py
@@ -4,6 +4,8 @@ import re
from typing import Final, NewType
from urllib.parse import urlparse
+from .host_match import http_authority_host, is_host_or_subdomain
+
ArxivId = NewType("ArxivId", str)
_ID_PATTERN: Final = (
@@ -30,14 +32,11 @@ def _normalize_http_hostname(scheme: str, hostname: str | None) -> str | None:
def _normalized_http_hostname(url: str) -> str | None:
try:
parsed = urlparse(url)
- _ = parsed.port
- return _normalize_http_hostname(parsed.scheme, parsed.hostname)
except ValueError:
return None
-
-
-def _is_host_family(hostname: str, domain: str) -> bool:
- return hostname == domain or hostname.endswith(f".{domain}")
+ if parsed.scheme.lower() not in {"http", "https"}:
+ return None
+ return http_authority_host(parsed)
def is_arxiv_family_url(url: str) -> bool:
@@ -54,14 +53,15 @@ def is_arxiv_family_url(url: str) -> bool:
"""
hostname = _normalized_http_hostname(url)
return hostname is not None and any(
- _is_host_family(hostname, domain) for domain in _ARXIV_FAMILY_DOMAINS
+ is_host_or_subdomain(hostname, domain)
+ for domain in _ARXIV_FAMILY_DOMAINS
)
def is_ar5iv_url(url: str) -> bool:
"""Return whether an HTTP(S) URL targets the ar5iv host family."""
hostname = _normalized_http_hostname(url)
- return hostname is not None and _is_host_family(hostname, "ar5iv.org")
+ return hostname is not None and is_host_or_subdomain(hostname, "ar5iv.org")
def is_arxiv_paper_url(url: str) -> bool:
diff --git a/src/local_deep_research/utilities/host_match.py b/src/local_deep_research/utilities/host_match.py
new file mode 100644
index 0000000000..b3d26d408c
--- /dev/null
+++ b/src/local_deep_research/utilities/host_match.py
@@ -0,0 +1,41 @@
+"""Host membership shared by URL routing and source labels.
+
+Kept free of project imports so any module can use it: ``utilities/arxiv.py``
+and the content fetcher's ``URLClassifier`` both do, and a helper in
+``url_utils.py`` would have pulled the security package into their import graph.
+"""
+
+from urllib.parse import ParseResult
+
+
+def http_authority_host(parsed: ParseResult) -> str | None:
+ """Return the host an HTTP client would connect to, or ``None``.
+
+ The host is lower-cased and loses the root dot of a fully qualified name.
+ ``None`` means urllib and the HTTP stack disagree about the authority, so
+ no host can be trusted. That happens in two cases. urllib keeps a
+ backslash inside the authority, while browsers and requests end the
+ authority there, so ``https://evil.example\\@doi.org/`` has the host
+ ``doi.org`` for urllib and connects to ``evil.example``. And a port that
+ is not a number (``host:443.evil.example``) hides the rest of the
+ authority from ``hostname``, while requests refuses the URL.
+ """
+ if "\\" in parsed.netloc:
+ return None
+ try:
+ _ = parsed.port
+ except ValueError:
+ return None
+ host = parsed.hostname
+ return host.rstrip(".") if host else None
+
+
+def is_host_or_subdomain(hostname: str, domain: str) -> bool:
+ """Return whether ``hostname`` is ``domain`` itself or a subdomain of it.
+
+ Both arguments are expected lower-cased, without port, userinfo or a
+ trailing root dot. The dot boundary is the point of the check: a
+ substring test also accepts ``doi.org.evil.example`` as ``doi.org``, and
+ a suffix test without the dot accepts ``notdoi.org``.
+ """
+ return hostname == domain or hostname.endswith(f".{domain}")
diff --git a/tests/content_fetcher/test_url_classifier.py b/tests/content_fetcher/test_url_classifier.py
index 3985b9bb8e..76fd8c3a41 100644
--- a/tests/content_fetcher/test_url_classifier.py
+++ b/tests/content_fetcher/test_url_classifier.py
@@ -4,6 +4,7 @@ Tests for URL classifier.
import pytest
+from local_deep_research.content_fetcher.fetcher import ContentFetcher
from local_deep_research.content_fetcher.url_classifier import (
URLClassifier,
URLType,
@@ -39,6 +40,8 @@ class TestArxivFamilyURL:
"https:///arxiv.org/not-an-arxiv-id",
"https://[arxiv.org",
"https://arxiv.org:not-a-port/not-an-arxiv-id",
+ "https://evil.example\\@arxiv.org/abs/2301.12345",
+ "https://evil.example\\.arxiv.org/abs/2301.12345",
),
)
def test_non_http_malformed_and_lookalike_urls_are_unowned(self, url):
@@ -240,6 +243,120 @@ class TestURLClassifier:
assert URLClassifier.classify(url) == URLType.HTML
+class TestAcademicSourceHostAnchoring:
+ """The academic sources are matched on the URL's host and path (#6835).
+
+ Searching for them anywhere in the URL string also found them in another
+ site's path or query and inside look-alike hosts. Such a URL was then
+ routed to the source's downloader and cited under its tag.
+ """
+
+ @pytest.mark.parametrize(
+ "url",
+ (
+ "https://evil.example/doi.org/10.1234/x",
+ "https://evil.example/?x=doi.org/10.1234/x",
+ "https://evil.example/redirect?u=pubmed.ncbi.nlm.nih.gov/12345",
+ "https://evil.example/ncbi.nlm.nih.gov/pubmed/12345",
+ "https://evil.example/ncbi.nlm.nih.gov/pmc/articles/PMC123",
+ "https://evil.example/europepmc.org/article/PMC/123",
+ "https://evil.example/semanticscholar.org/paper/abc",
+ "https://evil.example/api.semanticscholar.org/graph/v1",
+ "https://evil.example/biorxiv.org/content/10.1101/x",
+ "https://evil.example/medrxiv.org/content/10.1101/x",
+ ),
+ )
+ def test_a_source_domain_in_another_sites_path_or_query_is_html(self, url):
+ assert URLClassifier.classify(url) == URLType.HTML
+
+ @pytest.mark.parametrize(
+ "url",
+ (
+ "https://fakedoi.org/10.1234/x",
+ "https://notbiorxiv.org/content/10.1101/x",
+ "https://evilmedrxiv.org/content/10.1101/x",
+ "https://mysemanticscholar.org/paper/abc",
+ "https://fakeeuropepmc.org/article/PMC/123",
+ "https://pubmed.ncbi.nlm.nih.gov.evil.example/12345",
+ ),
+ )
+ def test_a_lookalike_host_is_html(self, url):
+ assert URLClassifier.classify(url) == URLType.HTML
+
+ @pytest.mark.parametrize(
+ "url,url_type",
+ (
+ ("https://pubmed.ncbi.nlm.nih.gov:443/12345", URLType.PUBMED),
+ ("https://DOI.ORG/10.1234/x", URLType.DOI),
+ ("https://doi.org./10.1234/x", URLType.DOI),
+ ("doi.org/10.1234/x", URLType.DOI),
+ ("https://europepmc.org/articles/PMC123", URLType.PMC),
+ ("https://ncbi.nlm.nih.gov/pubmed/12345", URLType.PUBMED),
+ ("https:/doi.org/10.1234/x", URLType.DOI),
+ ("https:doi.org/10.1234/x", URLType.DOI),
+ ),
+ )
+ def test_the_real_host_keeps_its_type_however_it_is_written(
+ self, url, url_type
+ ):
+ assert URLClassifier.classify(url) == url_type
+
+ def test_the_path_pattern_is_a_prefix(self):
+ # A bioRxiv collection page, not an article: /content/ appears only
+ # further down its path.
+ url = "https://connect.biorxiv.org/relate/content/181"
+ assert URLClassifier.classify(url) == URLType.HTML
+
+ @pytest.mark.parametrize(
+ "url",
+ (
+ "https://evil.example\\@doi.org/10.1234/x",
+ "https://evil.example\\.doi.org/10.1234/x",
+ "https://evil.example\\@pubmed.ncbi.nlm.nih.gov/12345",
+ "https://evil.example\\@ncbi.nlm.nih.gov/pmc/articles/PMC123",
+ "https://evil.example\\@europepmc.org/article/PMC/123",
+ "https://evil.example\\@semanticscholar.org/paper/abc",
+ "https://evil.example\\@biorxiv.org/content/10.1101/x",
+ "https://evil.example\\@medrxiv.org/content/10.1101/x",
+ "https://evil.example\\@arxiv.org/abs/2301.12345",
+ "https://evil.example\\.arxiv.org/abs/2301.12345",
+ ),
+ )
+ def test_a_backslash_in_the_authority_earns_no_source(self, url):
+ # urllib reads the host after the backslash; browsers and requests
+ # end the authority at it and connect to evil.example.
+ assert URLClassifier.classify(url) == URLType.HTML
+
+ @pytest.mark.parametrize(
+ "url",
+ (
+ "https://pubmed.ncbi.nlm.nih.gov:443.evil.example/12345",
+ "https://doi.org:99999/10.1234/x",
+ ),
+ )
+ def test_a_port_that_is_not_a_port_earns_no_source(self, url):
+ assert URLClassifier.classify(url) == URLType.HTML
+
+ def test_an_authority_urllib_cannot_parse_is_html(self):
+ assert URLClassifier.classify("[evil.example/x") == URLType.HTML
+
+ @pytest.mark.parametrize(
+ "url",
+ (
+ "https://evil.example/ncbi.nlm.nih.gov/pmc/articles/PMC123",
+ "https://evil.example\\@ncbi.nlm.nih.gov/pmc/articles/PMC123",
+ ),
+ )
+ def test_the_fetcher_does_not_route_an_impostor_to_a_source(self, url):
+ # Routed as PMC, this link's content was the real article PMC123:
+ # PubMedDownloader reads the PMC id from anywhere in the URL and asks
+ # Europe PMC for that article's text.
+ info = ContentFetcher().get_url_info(url)
+
+ assert info["url_type"] == "html"
+ assert info["extracted_id"] is None
+
+
class TestURLClassifierExtractID:
"""Test ID extraction from URLs."""
diff --git a/tests/text_optimization/test_citation_formatter_contracts.py b/tests/text_optimization/test_citation_formatter_contracts.py
index ab466738af..e071b17ef6 100644
--- a/tests/text_optimization/test_citation_formatter_contracts.py
+++ b/tests/text_optimization/test_citation_formatter_contracts.py
@@ -716,8 +716,8 @@ class TestSourceLabelFidelity:
This PR routes arXiv detection through
``utilities.arxiv.is_arxiv_paper_url``, which parses the actual
hostname and identifier instead of substring-matching the raw URL,
- closing this specific case. DOI and PubMed still delegate to a bare
- ``re.search`` and remain vulnerable -- see the xfail below.
+ closing this specific case. The other academic sources are now
+ matched on the parsed host as well (#6835) -- see the test below.
"""
label = CitationFormatter()._extract_source_label(
"https://evil.example/arxiv.org/abs/1234"
@@ -732,23 +732,13 @@ class TestSourceLabelFidelity:
"https://evil.example/pubmed.ncbi.nlm.nih.gov/12345",
"pubmed",
),
+ ("https://evil.example\\@doi.org/10.1234/x", "doi"),
+ (
+ "https://pubmed.ncbi.nlm.nih.gov:443.evil.example/12345",
+ "pubmed",
+ ),
],
)
- @pytest.mark.xfail(
- strict=True,
- reason=(
- "SECURITY DEFECT: _extract_source_label delegates to "
- "URLClassifier.classify, whose DOI/PubMed patterns are "
- "re.search'ed against the whole URL string rather than the "
- "host, so an attacker-controlled path or query segment earns "
- "the academic-source tag. SOURCE_TAGGED mode then renders "
- "[[doi-1]] or [[pubmed-1]] on a link to evil.example. Root "
- "cause lives in content_fetcher/url_classifier.py; "
- "citation_formatter consumes it without re-checking the "
- "host. (The arXiv case of this defect is fixed -- see "
- "test_arxiv_in_the_path_does_not_earn_its_tag above.)"
- ),
- )
def test_known_source_in_the_path_does_not_earn_its_tag(
self, url, impostor
):