~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
security: escape LIKE wildcards across library, domain classifier, news, and journal_quality (#3094)
LearningCircuit9326c6a2ba59
diff --git a/changelog.d/3094.bugfix.md b/changelog.d/3094.bugfix.mdnew file mode 100644index 0000000000..d49b1b5f05--- /dev/null+++ b/changelog.d/3094.bugfix.md@@ -0,0 +1 @@+Fixed the news subscription-history endpoint (`/news/api/subscriptions/<id>/history`) raising an internal error for any subscription that had research runs: `get_subscription_history` called `.isoformat()` on the `created_at`/`completed_at` values, which are stored as isoformat strings, so it now returns them directly.diff --git a/changelog.d/3094.security.md b/changelog.d/3094.security.mdnew file mode 100644index 0000000000..d577b894d2--- /dev/null+++ b/changelog.d/3094.security.md@@ -0,0 +1 @@+User-supplied strings that reach SQL `LIKE` queries — library search and domain filters, domain-classifier sampling, and news subscription filters — now escape `%` and `_` wildcards. Previously a value like `100%` or `a_b` was interpreted as a wildcard and matched unrelated rows; searches and filters now match literally, closing a wildcard-injection/enumeration vector within a user's own database.diff --git a/src/local_deep_research/domain_classifier/classifier.py b/src/local_deep_research/domain_classifier/classifier.pyindex 1a3b931abc..1b6263c7a8 100644--- a/src/local_deep_research/domain_classifier/classifier.py+++ b/src/local_deep_research/domain_classifier/classifier.py@@ -9,6 +9,7 @@ from sqlalchemy.orm import Sessionfrom ..config.llm_config import get_llmfrom ..database.models import ResearchResourcefrom ..database.session_context import get_user_db_session+from ..utilities.sql_utils import escape_like as _escape_likefrom ..utilities.json_utils import extract_json, get_llm_response_textfrom .models import DomainClassification@@ -122,7 +123,11 @@ class DomainClassifier:"""resources = (session.query(ResearchResource)- .filter(ResearchResource.url.like(f"%{domain}%"))+ .filter(+ ResearchResource.url.like(+ f"%{_escape_like(domain)}%", escape="\\"+ )+ ).limit(limit).all())diff --git a/src/local_deep_research/journal_quality/db.py b/src/local_deep_research/journal_quality/db.pyindex ad3ba88510..0f45c7d172 100644--- a/src/local_deep_research/journal_quality/db.py+++ b/src/local_deep_research/journal_quality/db.py@@ -52,6 +52,7 @@ from .models import ()from ..constants import PREDATORY_WHITELIST_HINDEXfrom ..utilities.citation_normalizer import normalize_issn+from ..utilities.sql_utils import escape_likefrom .scoring import (derive_quality_score,institution_score_from_h_index,@@ -100,15 +101,6 @@ _SORT_COLUMNS = frozenset(_MAX_SEARCH_LEN = 100-def _escape_like(s: str) -> str:- """Escape SQL LIKE metacharacters so user-supplied search strings- can't force degenerate full-table scans via ``%`` or ``_``.-- Pair with ``.like(pattern, escape="/")`` at the call site.- """- return s.replace("/", "//").replace("%", "/%").replace("_", "/_")--# ---------------------------------------------------------------------------# Read-only accessor# ---------------------------------------------------------------------------@@ -830,8 +822,8 @@ class JournalQualityDB:wheres: list = []if search:- needle = _escape_like(normalize_name(search)[:_MAX_SEARCH_LEN])- wheres.append(Source.name_lower.like(f"%{needle}%", escape="/"))+ needle = escape_like(normalize_name(search)[:_MAX_SEARCH_LEN])+ wheres.append(Source.name_lower.like(f"%{needle}%", escape="\\"))if tier and tier in _TIER_RANGES:lo, hi = _TIER_RANGES[tier]wheres.append(Source.quality.between(lo, hi))@@ -885,9 +877,9 @@ class JournalQualityDB:wheres = []if search:- needle = _escape_like(normalize_name(search)[:_MAX_SEARCH_LEN])+ needle = escape_like(normalize_name(search)[:_MAX_SEARCH_LEN])wheres.append(- Institution.name_lower.like(f"%{needle}%", escape="/")+ Institution.name_lower.like(f"%{needle}%", escape="\\"))sort_col = (diff --git a/src/local_deep_research/news/api.py b/src/local_deep_research/news/api.pyindex 08eb572601..2a7fef002c 100644--- a/src/local_deep_research/news/api.py+++ b/src/local_deep_research/news/api.py@@ -11,6 +11,7 @@ import jsonfrom ..constants import ResearchStatusfrom ..llm.providers.base import normalize_provider+from ..utilities.sql_utils import escape_likefrom .exceptions import (InvalidLimitException,SubscriptionNotFoundException,@@ -145,7 +146,8 @@ def get_news_feed(# get_subscriptions and get_subscription_history below.query = query.filter(ResearchHistory.research_meta.like(- f'%"subscription_id": "{subscription_id}"%'+ f'%"subscription_id": "{escape_like(subscription_id)}"%',+ escape="\\",))@@ -525,14 +527,20 @@ def get_subscription_history(# Get all research runs that were triggered by this subscription# Look for subscription_id in the research_meta JSON# Note: JSON format has space after colon- like_pattern = f'%"subscription_id": "{subscription_id}"%'+ like_pattern = (+ f'%"subscription_id": "{escape_like(subscription_id)}"%'+ )logger.info(f"Searching for research history with pattern: {like_pattern}")history_items = (db_session.query(ResearchHistory)- .filter(ResearchHistory.research_meta.like(like_pattern))+ .filter(+ ResearchHistory.research_meta.like(+ like_pattern, escape="\\"+ )+ ).order_by(ResearchHistory.created_at.desc()).limit(limit).all()@@ -549,12 +557,13 @@ def get_subscription_history("uuid_id": h.id,"query": h.query,"status": h.status,- "created_at": h.created_at.isoformat()- if h.created_at- else None,- "completed_at": h.completed_at.isoformat()- if h.completed_at- else None,+ # created_at/completed_at are Text columns already holding+ # isoformat strings (see get_news_feed above), so use them+ # directly — calling .isoformat() on a str raises+ # AttributeError and previously broke this endpoint for any+ # subscription that had research history.+ "created_at": h.created_at,+ "completed_at": h.completed_at if h.completed_at else None,"duration_seconds": h.duration_seconds,"research_meta": h.research_meta,"report_path": h.report_path,@@ -745,11 +754,18 @@ def get_subscriptions(user_id: str) -> Dict[str, Any]:subscriptions = db_session.query(NewsSubscription).all()for sub in subscriptions:- # Count actual research runs for this subscription- like_pattern = f'%"subscription_id": "{sub.id}"%'+ # Count actual research runs for this subscription.+ # sub.id is an internal PK (not user input), but escape it+ # too so every subscription_id LIKE in this module is+ # uniformly wildcard-safe — a no-op for UUID-shaped ids.+ like_pattern = f'%"subscription_id": "{escape_like(sub.id)}"%'total_runs = (db_session.query(func.count(ResearchHistory.id))- .filter(ResearchHistory.research_meta.like(like_pattern))+ .filter(+ ResearchHistory.research_meta.like(+ like_pattern, escape="\\"+ )+ ).scalar()or 0)diff --git a/src/local_deep_research/research_library/services/library_service.py b/src/local_deep_research/research_library/services/library_service.pyindex ab160d051c..9d7fa499fe 100644--- a/src/local_deep_research/research_library/services/library_service.py+++ b/src/local_deep_research/research_library/services/library_service.py@@ -30,6 +30,7 @@ from ...database.models.research import ResearchHistory, ResearchResourcefrom ...database.session_context import get_user_db_sessionfrom ...security import PathValidatorfrom ...config.paths import get_library_directory+from ...utilities.sql_utils import escape_like as _escape_likefrom ..utils import (get_absolute_path_from_settings,get_url_hash,@@ -132,30 +133,18 @@ class LibraryService:return queryreturn query.filter(model_class.processed_at >= cutoff)- @staticmethod- def _escape_like(value: str) -> str:- """Escape SQL LIKE wildcards (%, _) and the escape char itself.-- Without this, a value like ``my_journal`` would have ``_`` interpreted- as a single-character wildcard, and ``%`` would match anything.- Used together with ``escape="\\\\"`` on the .like()/.ilike() call.- """- return (- value.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")- )-def _apply_domain_filter(self, query, model_class, domain: str):"""Apply domain filter to query for Document.The dropdown is fully data-driven (populated from get_unique_domains),so the filter is a generic substring match against original_url."""- pattern = f"%{self._escape_like(domain)}%"+ pattern = f"%{_escape_like(domain)}%"return query.filter(model_class.original_url.like(pattern, escape="\\"))def _apply_search_filter(self, query, model_class, search_query: str):"""Apply search filter to query for Document."""- search_pattern = f"%{self._escape_like(search_query)}%"+ search_pattern = f"%{_escape_like(search_query)}%"return query.filter(or_(model_class.title.ilike(search_pattern, escape="\\"),diff --git a/src/local_deep_research/utilities/sql_utils.py b/src/local_deep_research/utilities/sql_utils.pynew file mode 100644index 0000000000..f5a16a826b--- /dev/null+++ b/src/local_deep_research/utilities/sql_utils.py@@ -0,0 +1,17 @@+"""SQL helper utilities with no framework or DB-session dependencies.++Deliberately dependency-free (no flask, no encrypted_db imports) so that+lightweight, standalone modules — such as the read-only ``journal_quality``+reference DB — can escape LIKE wildcards without transitively pulling in+the web stack.+"""+++def escape_like(value: str) -> str:+ """Escape SQL LIKE metacharacters to prevent wildcard injection.++ Escapes the backslash first, then ``%`` and ``_``. Pair with+ ``escape="\\\\"`` on the ``.like()`` / ``.ilike()`` call so the database+ treats the backslash as the escape character.+ """+ return value.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")diff --git a/tests/domain_classifier/test_classifier_edge_cases.py b/tests/domain_classifier/test_classifier_edge_cases.pyindex f241327761..2121f4257f 100644--- a/tests/domain_classifier/test_classifier_edge_cases.py+++ b/tests/domain_classifier/test_classifier_edge_cases.py@@ -168,6 +168,78 @@ class TestGetDomainSamples:assert len(samples[0]["preview"]) == 200+class TestGetDomainSamplesEscaping:+ """Integration tests: LIKE wildcards in the domain must be literal.++ Uses a real in-memory SQLite session so SQLite itself evaluates the+ ``LIKE ... ESCAPE`` pattern. The other TestGetDomainSamples tests mock+ the session, so they pass regardless of escaping; these prove the+ escape path actually works. Regression coverage for the security fix+ in PR #3094 (classifier branch), which the mocked tests do not enforce.+ """++ @staticmethod+ def _session_with(resources):+ from sqlalchemy import create_engine+ from sqlalchemy.orm import sessionmaker++ from local_deep_research.database.models import ResearchResource+ from local_deep_research.database.models.research import Base++ engine = create_engine("sqlite:///:memory:")+ Base.metadata.create_all(engine)+ session = sessionmaker(bind=engine)()+ # This bare engine has no foreign_keys PRAGMA (the app enables it+ # per-engine in encrypted_db/auth_db, not globally), so the orphan+ # research_id values below commit without a real research_history row.+ session.add_all(+ ResearchResource(+ research_id=f"r{i}",+ url=url,+ title=f"resource {i}",+ created_at="2026-01-01T00:00:00",+ )+ for i, url in enumerate(resources)+ )+ session.commit()+ return session++ def test_percent_treated_as_literal(self):+ """Sampling domain '100%.com' must not pull '100pages.com' rows."""+ session = self._session_with(+ ["https://100%.com/paper", "https://100pages.com/article"]+ )+ classifier = DomainClassifier(username="test")++ urls = [+ s["url"]+ for s in classifier._get_domain_samples("100%.com", session)+ ]++ assert "https://100%.com/paper" in urls+ assert "https://100pages.com/article" not in urls++ def test_underscore_treated_as_literal(self):+ """Sampling domain 's3_bucket.example.com' must not pull 's3Xbucket…'."""+ session = self._session_with(+ [+ "https://s3_bucket.example.com/a",+ "https://s3Xbucket.example.com/b",+ ]+ )+ classifier = DomainClassifier(username="test")++ urls = [+ s["url"]+ for s in classifier._get_domain_samples(+ "s3_bucket.example.com", session+ )+ ]++ assert "https://s3_bucket.example.com/a" in urls+ assert "https://s3Xbucket.example.com/b" not in urls++class TestBuildClassificationPromptEdgeCases:"""Test _build_classification_prompt edge cases."""diff --git a/tests/journal_quality/test_db_accessors.py b/tests/journal_quality/test_db_accessors.pyindex 3cd4d0850d..cc51c165b2 100644--- a/tests/journal_quality/test_db_accessors.py+++ b/tests/journal_quality/test_db_accessors.py@@ -16,7 +16,6 @@ import pytestfrom local_deep_research.journal_quality.db import (JOURNAL_QUALITY_SCHEMA_VERSION,JournalQualityDB,- _escape_like,_sweep_stale_tmp_files,)@@ -409,23 +408,5 @@ class TestSweepStaleTmpFiles:assert other.exists()-# ----------------------------------------------------------------------------# _escape_like-# ------------------------------------------------------------------------------class TestEscapeLike:- def test_escapes_percent(self):- assert _escape_like("100%") == "100/%"-- def test_escapes_underscore(self):- assert _escape_like("a_b") == "a/_b"-- def test_escapes_slash(self):- assert _escape_like("a/b") == "a//b"-- def test_no_special_chars(self):- assert _escape_like("Nature") == "Nature"-- def test_mixed(self):- assert _escape_like("a%b_c/d") == "a/%b/_c//d"+# _escape_like was consolidated into the shared ``sql_utils.escape_like``+# (see tests/utilities/test_sql_utils.py::TestEscapeLike for its coverage).diff --git a/tests/journal_quality/test_search_like_escaping.py b/tests/journal_quality/test_search_like_escaping.pynew file mode 100644index 0000000000..bf0376107e--- /dev/null+++ b/tests/journal_quality/test_search_like_escaping.py@@ -0,0 +1,107 @@+"""Regression: LIKE wildcards in journal_quality search must be literal (#3094).++``get_journals_page`` / ``get_institutions_page`` substring-match the user's+search term against ``name_lower`` via ``LIKE``. Without escaping, a term+containing ``%`` or ``_`` acts as a SQL wildcard and returns unrelated+journals/institutions.++These inject a seeded in-memory SQLite engine into ``JournalQualityDB``+(``_ensure_engine`` short-circuits when ``_engine`` is already set), bypassing+the read-only-file machinery so SQLite itself evaluates the ``LIKE ... ESCAPE``+pattern. They fail if the escaping in ``get_journals_page`` /+``get_institutions_page`` is reverted. The bundled ``ref_db`` search tests only+use metacharacter-free terms (``"nature"``), so this is the only fail-on-revert+coverage for these two escape sites.+"""++from sqlalchemy import create_engine+from sqlalchemy.orm import sessionmaker++from local_deep_research.journal_quality.db import JournalQualityDB+from local_deep_research.journal_quality.models import (+ Institution,+ JournalQualityBase,+ Source,+)+++def _db_with(sources=(), institutions=()):+ """A JournalQualityDB backed by a seeded in-memory SQLite engine.++ Setting ``_engine``/``_SessionLocal`` directly makes ``_ensure_engine``+ return early, so the read-only-file path (``_resolve_db_path`` / ``mode=ro``+ / schema-version validation) is skipped and queries run against the seeded+ in-memory DB.+ """+ engine = create_engine("sqlite:///:memory:")+ JournalQualityBase.metadata.create_all(engine)+ session_local = sessionmaker(bind=engine, expire_on_commit=False)+ seed = session_local()+ seed.add_all(list(sources) + list(institutions))+ seed.commit()+ seed.close()++ db = JournalQualityDB()+ db._engine = engine+ db._SessionLocal = session_local+ return db+++def _source(name, name_lower):+ return Source(+ name=name,+ name_lower=name_lower,+ is_in_doaj=False,+ is_predatory=False,+ score_source="openalex",+ )+++def test_journal_search_percent_treated_as_literal():+ """Searching journals for '100%' must not match '100pages'."""+ db = _db_with(+ sources=[+ _source("Journal 100%", "journal 100%"),+ _source("Journal 100pages", "journal 100pages"),+ ]+ )+ names = [+ j["name"] for j in db.get_journals_page(search="100%", per_page=10)[0]+ ]+ assert "Journal 100%" in names+ assert "Journal 100pages" not in names+++def test_journal_search_underscore_treated_as_literal():+ """Searching journals for 'a_b' must not match 'aXb'."""+ db = _db_with(+ sources=[+ _source("Journal a_b", "journal a_b"),+ _source("Journal aXb", "journal axb"),+ ]+ )+ names = [+ j["name"] for j in db.get_journals_page(search="a_b", per_page=10)[0]+ ]+ assert "Journal a_b" in names+ assert "Journal aXb" not in names+++def test_institution_search_underscore_treated_as_literal():+ """Searching institutions for 'a_b' must not match 'aXb'."""+ db = _db_with(+ institutions=[+ Institution(+ openalex_id="I1", name="Univ a_b", name_lower="univ a_b"+ ),+ Institution(+ openalex_id="I2", name="Univ aXb", name_lower="univ axb"+ ),+ ]+ )+ names = [+ i["name"]+ for i in db.get_institutions_page(search="a_b", per_page=10)[0]+ ]+ assert "Univ a_b" in names+ assert "Univ aXb" not in namesdiff --git a/tests/news/test_news_api.py b/tests/news/test_news_api.pyindex 4e36508e91..ffef268a3b 100644--- a/tests/news/test_news_api.py+++ b/tests/news/test_news_api.py@@ -210,8 +210,11 @@ class TestGetNewsFeed:)mock_get_session.return_value.__exit__ = Mock(return_value=False)+ # Metacharacter-free id so LIKE-wildcard escaping is a no-op and+ # this test stays focused on json.dumps spacing; escaping itself+ # is covered by tests/news/test_subscription_like_escaping.py.get_news_feed(- user_id="testuser", limit=10, subscription_id="sub_abc"+ user_id="testuser", limit=10, subscription_id="sub-abc")# Pull the LIKE pattern string out of whichever captured@@ -228,7 +231,7 @@ class TestGetNewsFeed:f"No subscription_id LIKE pattern captured among "f"{len(captured_predicates)} filter calls.")- expected_fragment = json.dumps({"subscription_id": "sub_abc"})[1:-1]+ expected_fragment = json.dumps({"subscription_id": "sub-abc"})[1:-1]assert any(expected_fragment in p for p in like_patterns), (f"get_news_feed LIKE patterns {like_patterns!r} do not "f"match the json.dumps fragment {expected_fragment!r}."@@ -858,7 +861,10 @@ class TestSubscriptionHistory:from local_deep_research.news.api import get_subscription_historymock_subscription = MagicMock()- mock_subscription.id = "sub_xyz"+ # Metacharacter-free id so LIKE-wildcard escaping is a no-op and this+ # test stays focused on json.dumps spacing; escaping itself is covered+ # by tests/news/test_subscription_like_escaping.py.+ mock_subscription.id = "sub-xyz"captured_predicates = []@@ -884,7 +890,7 @@ class TestSubscriptionHistory:)mock_get_session.return_value.__exit__ = Mock(return_value=False)- get_subscription_history(subscription_id="sub_xyz", limit=10)+ get_subscription_history(subscription_id="sub-xyz", limit=10)like_patterns = []for pred in captured_predicates:@@ -897,7 +903,7 @@ class TestSubscriptionHistory:f"No subscription_id LIKE pattern captured among "f"{len(captured_predicates)} filter calls.")- expected_fragment = json.dumps({"subscription_id": "sub_xyz"})[1:-1]+ expected_fragment = json.dumps({"subscription_id": "sub-xyz"})[1:-1]assert any(expected_fragment in p for p in like_patterns), (f"LIKE patterns {like_patterns!r} do not contain the "f"json.dumps fragment {expected_fragment!r} — the spacing "diff --git a/tests/news/test_subscription_like_escaping.py b/tests/news/test_subscription_like_escaping.pynew file mode 100644index 0000000000..b4bc97cdc8--- /dev/null+++ b/tests/news/test_subscription_like_escaping.py@@ -0,0 +1,174 @@+"""Regression: subscription_id LIKE wildcards must be literal (#3094).++``get_news_feed`` filters research history by substring-matching the+caller-supplied ``subscription_id`` into a ``research_meta LIKE`` pattern.+Without escaping, a ``subscription_id`` containing ``%`` or ``_`` acts as a+SQL wildcard and pulls research rows belonging to *other* subscriptions+(a wildcard-injection / enumeration bug — reachable unvalidated via the+``news/flask_api.py`` blueprint).++These use a real in-memory SQLite session (only the per-user DB session is+patched) so SQLite itself evaluates the ``LIKE ... ESCAPE`` pattern; they+fail if the escaping at ``news/api.py`` is reverted.+"""++from contextlib import contextmanager+from datetime import datetime, UTC+from unittest.mock import patch++from sqlalchemy import create_engine+from sqlalchemy.orm import sessionmaker++from local_deep_research.database.models import Base, ResearchHistory+++@contextmanager+def _patched_user_db(seed_fn):+ """Seed a fresh in-memory DB via ``seed_fn(session)`` and patch the+ per-user DB session so ``news.api`` uses it. Only the session is+ patched; SQLite itself evaluates the real ``LIKE ... ESCAPE`` pattern.+ """+ engine = create_engine("sqlite:///:memory:")+ Base.metadata.create_all(engine)+ session_local = sessionmaker(bind=engine)++ seed = session_local()+ seed_fn(seed)+ seed.commit()+ seed.close()++ @contextmanager+ def _fake_user_db(username=None, password=None):+ db = session_local()+ try:+ yield db+ finally:+ db.close()++ with patch(+ "local_deep_research.database.session_context.get_user_db_session",+ _fake_user_db,+ ):+ yield+ engine.dispose()+++def _news_row(research_id, subscription_id, now):+ """A completed news-style research row bound to a subscription."""+ return ResearchHistory(+ id=research_id,+ query="latest news on the topic",+ title="Topic",+ mode="quick",+ status="completed",+ created_at=now,+ completed_at=now,+ report_content="Answer.",+ research_meta={+ "is_news_search": True,+ "subscription_id": subscription_id,+ },+ )+++@contextmanager+def _seeded_feed(rows):+ """Seed ResearchHistory news rows and patch the per-user DB session.++ ``rows`` is an iterable of ``(research_id, subscription_id)``. The query+ text and ``is_news_search`` flag make ``get_news_feed`` surface each row+ as a news item, so the only thing distinguishing target from decoy is+ the ``subscription_id`` the LIKE filter matches on.+ """+ now = datetime.now(UTC).isoformat()++ def _seed(session):+ for research_id, subscription_id in rows:+ session.add(_news_row(research_id, subscription_id, now))++ with _patched_user_db(_seed):+ yield+++def _feed_research_ids(subscription_id):+ from local_deep_research.news.api import get_news_feed++ result = get_news_feed(+ user_id="testuser",+ limit=20,+ use_cache=False,+ subscription_id=subscription_id,+ )+ return [it.get("research_id") for it in result.get("news_items", [])]+++def test_subscription_underscore_treated_as_literal():+ """Filtering on 'a_b' must not pull the 'aXb' subscription's rows."""+ with _seeded_feed([("target", "a_b"), ("decoy", "aXb")]):+ ids = _feed_research_ids("a_b")++ assert "target" in ids+ assert "decoy" not in ids+++def test_subscription_percent_treated_as_literal():+ """Filtering on 'sub-100%' must not pull 'sub-100X-extra' rows."""+ with _seeded_feed([("target", "sub-100%"), ("decoy", "sub-100X-extra")]):+ ids = _feed_research_ids("sub-100%")++ assert "target" in ids+ assert "decoy" not in ids+++def test_get_subscriptions_run_count_ignores_wildcard_matches():+ """get_subscriptions' per-subscription total_runs must count only the+ exact subscription: id 'a_b' must not also count the 'aXb' run.++ Real-DB fail-on-revert coverage for the get_subscriptions LIKE site.+ """+ from local_deep_research.database.models.news import NewsSubscription+ from local_deep_research.news.api import get_subscriptions++ def _seed(session):+ session.add(+ NewsSubscription(+ id="a_b", subscription_type="search", query_or_topic="q"+ )+ )+ session.add(_news_row("target", "a_b", "2026-01-01T00:00:00"))+ session.add(_news_row("decoy", "aXb", "2026-01-01T00:00:00"))++ with _patched_user_db(_seed):+ subscriptions = get_subscriptions("testuser")["subscriptions"]++ by_id = {s["id"]: s for s in subscriptions}+ assert by_id["a_b"]["total_runs"] == 1+++def test_get_subscription_history_ignores_wildcard_matches():+ """get_subscription_history for 'a_b' must not return the 'aXb'+ subscription's research runs.++ Real-DB fail-on-revert coverage for the get_subscription_history LIKE+ site. Because it exercises the full return path it also guards the+ created_at/completed_at Text handling (a reverted `.isoformat()` on the+ Text column would raise here).+ """+ from local_deep_research.database.models.news import NewsSubscription+ from local_deep_research.news.api import get_subscription_history++ def _seed(session):+ session.add(+ NewsSubscription(+ id="a_b", subscription_type="search", query_or_topic="q"+ )+ )+ session.add(_news_row("target", "a_b", "2026-01-01T00:00:00"))+ session.add(_news_row("decoy", "aXb", "2026-01-01T00:00:00"))++ with _patched_user_db(_seed):+ history = get_subscription_history("a_b")["history"]++ ids = [h["research_id"] for h in history]+ assert "target" in ids+ assert "decoy" not in idsdiff --git a/tests/research_library/services/test_library_service.py b/tests/research_library/services/test_library_service.pyindex cc57bb355c..91dae04666 100644--- a/tests/research_library/services/test_library_service.py+++ b/tests/research_library/services/test_library_service.py@@ -514,8 +514,8 @@ class TestLibraryServiceGetDocuments:class TestLibraryServiceApplyDomainFilter:"""Tests for _apply_domain_filter method."""- def test_apply_domain_filter_arxiv(self, mocker):- """Applies arxiv domain filter correctly."""+ def test_apply_domain_filter_custom_domain(self, mocker):+ """Applies custom domain filter correctly (generic branch)."""from local_deep_research.research_library.services.library_service import (LibraryService,)@@ -534,7 +534,7 @@ class TestLibraryServiceApplyDomainFilter:service = LibraryService.__new__(LibraryService)service.username = "test_user"- service._apply_domain_filter(mock_query, mock_model, "arxiv.org")+ service._apply_domain_filter(mock_query, mock_model, "example.com")# Should have called filterassert mock_query.filter.called@@ -590,6 +590,181 @@ class TestLibraryServiceApplySearchFilter:assert mock_query.filter.called+class TestLibraryServiceApplySearchFilterEscaping:+ """Integration tests: LIKE wildcards in user input must be literal.++ Uses a real in-memory SQLite session to verify that ``%`` and ``_``+ in user-supplied search/domain strings are treated as literals, not+ as SQL LIKE wildcards. Regression coverage for the security fix in+ PR #3094.+ """++ def test_search_percent_treated_as_literal(+ self, library_session, mock_source_type+ ):+ """Searching for '100%' must not match '100 pages'."""+ import hashlib+ import uuid++ from local_deep_research.database.models.library import (+ Document,+ DocumentStatus,+ )+ from local_deep_research.database.models.research import (+ ResearchResource,+ )+ from local_deep_research.research_library.services.library_service import (+ LibraryService,+ )++ target = Document(+ id=str(uuid.uuid4()),+ source_type_id=mock_source_type.id,+ document_hash=hashlib.sha256(b"target").hexdigest(),+ file_size=0,+ file_type="pdf",+ title="Discount: 100% off",+ status=DocumentStatus.COMPLETED,+ )+ decoy = Document(+ id=str(uuid.uuid4()),+ source_type_id=mock_source_type.id,+ document_hash=hashlib.sha256(b"decoy").hexdigest(),+ file_size=0,+ file_type="pdf",+ title="100 pages of notes",+ status=DocumentStatus.COMPLETED,+ )+ library_session.add_all([target, decoy])+ library_session.commit()++ with patch.object(+ LibraryService, "__init__", lambda self, username: None+ ):+ service = LibraryService.__new__(LibraryService)+ service.username = "test_user"++ query = library_session.query(Document).outerjoin(+ ResearchResource,+ (Document.resource_id == ResearchResource.id)+ | (ResearchResource.document_id == Document.id),+ )+ results = service._apply_search_filter(+ query, Document, "100%"+ ).all()+ titles = [r.title for r in results]++ assert "Discount: 100% off" in titles+ assert "100 pages of notes" not in titles++ def test_search_underscore_treated_as_literal(+ self, library_session, mock_source_type+ ):+ """Searching for 'a_b' must not match 'aXb'."""+ import hashlib+ import uuid++ from local_deep_research.database.models.library import (+ Document,+ DocumentStatus,+ )+ from local_deep_research.database.models.research import (+ ResearchResource,+ )+ from local_deep_research.research_library.services.library_service import (+ LibraryService,+ )++ target = Document(+ id=str(uuid.uuid4()),+ source_type_id=mock_source_type.id,+ document_hash=hashlib.sha256(b"target").hexdigest(),+ file_size=0,+ file_type="pdf",+ title="The a_b variable",+ status=DocumentStatus.COMPLETED,+ )+ decoy = Document(+ id=str(uuid.uuid4()),+ source_type_id=mock_source_type.id,+ document_hash=hashlib.sha256(b"decoy").hexdigest(),+ file_size=0,+ file_type="pdf",+ title="aXb variable",+ status=DocumentStatus.COMPLETED,+ )+ library_session.add_all([target, decoy])+ library_session.commit()++ with patch.object(+ LibraryService, "__init__", lambda self, username: None+ ):+ service = LibraryService.__new__(LibraryService)+ service.username = "test_user"++ query = library_session.query(Document).outerjoin(+ ResearchResource,+ (Document.resource_id == ResearchResource.id)+ | (ResearchResource.document_id == Document.id),+ )+ results = service._apply_search_filter(query, Document, "a_b").all()+ titles = [r.title for r in results]++ assert "The a_b variable" in titles+ assert "aXb variable" not in titles++ def test_domain_percent_treated_as_literal(+ self, library_session, mock_source_type+ ):+ """Domain filter for '100%.com' must not match '100X.com'."""+ import hashlib+ import uuid++ from local_deep_research.database.models.library import (+ Document,+ DocumentStatus,+ )+ from local_deep_research.research_library.services.library_service import (+ LibraryService,+ )++ target = Document(+ id=str(uuid.uuid4()),+ source_type_id=mock_source_type.id,+ document_hash=hashlib.sha256(b"target").hexdigest(),+ file_size=0,+ file_type="pdf",+ original_url="https://100%.com/paper",+ status=DocumentStatus.COMPLETED,+ )+ decoy = Document(+ id=str(uuid.uuid4()),+ source_type_id=mock_source_type.id,+ document_hash=hashlib.sha256(b"decoy").hexdigest(),+ file_size=0,+ file_type="pdf",+ original_url="https://100pages.com/article",+ status=DocumentStatus.COMPLETED,+ )+ library_session.add_all([target, decoy])+ library_session.commit()++ with patch.object(+ LibraryService, "__init__", lambda self, username: None+ ):+ service = LibraryService.__new__(LibraryService)+ service.username = "test_user"++ query = library_session.query(Document)+ results = service._apply_domain_filter(+ query, Document, "100%.com"+ ).all()+ urls = [r.original_url for r in results]++ assert "https://100%.com/paper" in urls+ assert "https://100pages.com/article" not in urls++class TestLibraryServiceGetResearchListWithStats:"""Tests for get_research_list_with_stats method."""diff --git a/tests/utilities/test_sql_utils.py b/tests/utilities/test_sql_utils.pynew file mode 100644index 0000000000..ef385f6bdb--- /dev/null+++ b/tests/utilities/test_sql_utils.py@@ -0,0 +1,40 @@+"""Tests for the dependency-free SQL helpers in utilities/sql_utils.py."""+++class TestEscapeLike:+ """Tests for escape_like — must be paired with escape='\\' at call site."""++ def test_escapes_percent(self):+ from local_deep_research.utilities.sql_utils import escape_like++ assert escape_like("100%") == "100\\%"++ def test_escapes_underscore(self):+ from local_deep_research.utilities.sql_utils import escape_like++ assert escape_like("a_b") == "a\\_b"++ def test_escapes_backslash(self):+ from local_deep_research.utilities.sql_utils import escape_like++ assert escape_like("a\\b") == "a\\\\b"++ def test_no_special_chars(self):+ from local_deep_research.utilities.sql_utils import escape_like++ assert escape_like("Nature") == "Nature"++ def test_mixed(self):+ from local_deep_research.utilities.sql_utils import escape_like++ assert escape_like("a%b_c\\d") == "a\\%b\\_c\\\\d"++ def test_empty_string(self):+ from local_deep_research.utilities.sql_utils import escape_like++ assert escape_like("") == ""++ def test_only_wildcards(self):+ from local_deep_research.utilities.sql_utils import escape_like++ assert escape_like("%_") == "\\%\\_"