~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(security): build journal-data response from structured state (CodeQL #7684) (#3572)
LearningCircuite7af3d9a79de
diff --git a/src/local_deep_research/journal_quality/downloader.py b/src/local_deep_research/journal_quality/downloader.pyindex 4a922b7760..2e21389e7f 100644--- a/src/local_deep_research/journal_quality/downloader.py+++ b/src/local_deep_research/journal_quality/downloader.py@@ -65,6 +65,15 @@ _download_state: dict = {"sources": {},"db_build": {"state": "pending", "detail": ""},"error_msg": None,+ # Per-source final counts from the most recently COMPLETED download.+ # Set to a dict only on the success path; explicitly invalidated to+ # None on every other return in `download_journal_data` (up-to-date,+ # disk-space, sentinel-race, required-failure, DB-build-failure) so+ # callers cannot read stale counts from a prior successful run.+ # Callers rendering a user-facing summary should prefer this+ # structured field over parsing the `(success, message)` tuple's+ # string.+ "counts": None,}@@ -75,6 +84,7 @@ def get_download_state() -> dict:serialize this to JSON and would otherwise race with live updates.We copy the nested dicts too."""+ counts = _download_state["counts"]return {"state": _download_state["state"],"started_at": _download_state["started_at"],@@ -82,6 +92,7 @@ def get_download_state() -> dict:"db_build": dict(_download_state["db_build"]),"error_msg": _download_state["error_msg"],"sources": {k: dict(v) for k, v in _download_state["sources"].items()},+ "counts": dict(counts) if counts is not None else None,}@@ -285,6 +296,10 @@ def download_journal_data(force: bool = False) -> tuple[bool, str]:if not force:status = get_journal_data_status()if status["available"] and not status["needs_update"]:+ # No fresh fetch ran, so invalidate any counts cached from a+ # previous in-process download. Callers keying a "what just+ # happened" summary off `counts` must see None here.+ _download_state["counts"] = Nonereturn True, "Journal data is already up to date"# Disk-space pre-check. The five data sources uncompress to ~1 GB@@ -305,6 +320,9 @@ def download_journal_data(force: bool = False) -> tuple[bool, str]:free_bytes is not Noneand free_bytes < JOURNAL_QUALITY_MIN_FREE_DISK_BYTES):+ # No fetch ran → invalidate any stale counts from a prior call+ # so `get_download_state()["counts"]` cannot leak them.+ _download_state["counts"] = Nonereturn False, (f"Insufficient disk space: "f"{free_bytes / (1024**3):.1f} GB available, "@@ -380,8 +398,10 @@ def download_journal_data(force: bool = False) -> tuple[bool, str]:if not _try_claim_sentinel():# Lost a race with another caller reclaiming the same# stale sentinel — bow out cleanly.+ _download_state["counts"] = Nonereturn False, "Download already in progress"else:+ _download_state["counts"] = Nonereturn False, "Download already in progress"try:start = time.time()@@ -394,6 +414,10 @@ def download_journal_data(force: bool = False) -> tuple[bool, str]:_download_state["started_at"] = start_download_state["finished_at"] = None_download_state["error_msg"] = None+ # Invalidate counts from any prior run — callers inspecting the+ # structured summary must not see stale data if this download+ # fails or is still running.+ _download_state["counts"] = None_download_state["db_build"] = {"state": "pending", "detail": ""}_download_state["sources"] = {src.key: {@@ -574,6 +598,10 @@ def download_journal_data(force: bool = False) -> tuple[bool, str]:_download_state["state"] = "success"_download_state["error_msg"] = None_download_state["finished_at"] = time.time()+ # Publish structured counts for callers that want to render a+ # user-facing summary without echoing `success_msg`. All values+ # are ints populated from source `.fetch()` returns above.+ _download_state["counts"] = dict(counts)return True, success_msgfinally:diff --git a/src/local_deep_research/web/routes/metrics_routes.py b/src/local_deep_research/web/routes/metrics_routes.pyindex 20d9bea6cd..77c4c0b4aa 100644--- a/src/local_deep_research/web/routes/metrics_routes.py+++ b/src/local_deep_research/web/routes/metrics_routes.py@@ -2190,42 +2190,50 @@ def api_journal_data_download():try:from ...journal_quality.downloader import (download_journal_data,+ get_download_state,)+ from ...journal_quality.data_sources import ALL_SOURCESfrom ...journal_quality.db import (build_reference_db,)from ...config.paths import get_journal_data_directoryforce = request.json.get("force", False) if request.is_json else False- success, message = download_journal_data(force=force)- if success:- data_dir = get_journal_data_directory()- build_reference_db(- data_dir=data_dir,- output_path=data_dir / "journal_reference.db",+ success, internal_message = download_journal_data(force=force)+ if not success:+ logger.warning(f"Journal data download failed: {internal_message}")+ return jsonify({"success": False, "message": "Download failed"})++ data_dir = get_journal_data_directory()+ build_reference_db(+ data_dir=data_dir,+ output_path=data_dir / "journal_reference.db",+ )+ # Reset singleton so it picks up the new DB+ from ...journal_quality.db import reset_db++ reset_db()++ # Build the user-facing message locally from structured state+ # (ints + developer-authored source labels). We deliberately do+ # NOT echo `internal_message` from download_journal_data: keeping+ # the response safe-by-construction means a future refactor that+ # lets arbitrary strings (exception info, user input, PII) slip+ # into the downloader's message cannot reach the client.+ counts = get_download_state().get("counts")+ if counts is not None:+ parts = [+ f"{int(counts.get(src.key) or 0)} {src.count_label}"+ for src in ALL_SOURCES+ ]+ user_message = (+ f"Fetched {' + '.join(parts)}. Database rebuilt successfully.")- # Reset singleton so it picks up the new DB- from ...journal_quality.db import reset_db-- reset_db()- message += ". Database rebuilt successfully."- if success:- # The ``message`` echoed here is trace-free by construction.- # download_journal_data() returns only status literals on- # success, and the DB-build-failed branch in downloader.py- # reduces any exception to ``str(SchemaDriftError)`` (a- # developer-authored literal) or ``exc.__class__.__name__``- # — see downloader.py:539-551. CodeQL bot comments cited- # alerts 7650/7684 (``py/stack-trace-exposure``) against an- # earlier snapshot; the current scan does not raise them- # and replacing this with a fixed literal would regress UX- # (users rely on the per-source counts in the dashboard- # popup: "[100%] Complete — Fetched 200K OpenAlex + ..."- # in journal_quality.html:857). Do not strip `message`- # without a new, reproducible security issue.- return jsonify({"success": True, "message": message})- logger.warning(f"Journal data download failed: {message}")- return jsonify({"success": False, "message": "Download failed"})+ else:+ # `counts` is None when download_journal_data took its+ # early-return "already up to date" branch (no fetch ran).+ user_message = "Journal data is already up to date."+ return jsonify({"success": True, "message": user_message})except Exception:logger.exception("Error downloading journal data")return jsonify({"success": False, "message": "Download failed"}), 500diff --git a/tests/journal_quality/test_downloader.py b/tests/journal_quality/test_downloader.pyindex b967b227ba..bd78804e16 100644--- a/tests/journal_quality/test_downloader.py+++ b/tests/journal_quality/test_downloader.py@@ -260,6 +260,103 @@ class TestDownloadJournalData:assert "SchemaDriftError" not in msg+class TestDownloadStateCountsLifecycle:+ """Verify `_download_state["counts"]` is populated only on success and+ cleared on every other return path, so the `/api/journal-data/download`+ route (and any other reader of `get_download_state()`) cannot observe+ stale counts from a prior run.+ """++ def _get_counts(self):+ from local_deep_research.journal_quality.downloader import (+ get_download_state,+ )++ return get_download_state().get("counts")++ def test_counts_none_on_already_up_to_date(self, tmp_data_dir):+ _write_openalex(tmp_data_dir)+ (tmp_data_dir / "doaj_journals.json").write_text("{}")+ (tmp_data_dir / "version.json").write_text(+ json.dumps({"version": JOURNAL_DATA_VERSION})+ )+ success, _ = download_journal_data()+ assert success is True+ assert self._get_counts() is None++ def test_counts_none_on_disk_space_failure(self, tmp_data_dir):+ class _LowDisk:+ total = 10 * 1024**3+ used = total - 500 * 1024**2+ free = 500 * 1024**2++ with patch("shutil.disk_usage", return_value=_LowDisk()):+ success, _ = download_journal_data(force=True)+ assert success is False+ assert self._get_counts() is None++ def test_counts_none_on_concurrent_download_block(self, tmp_data_dir):+ import os++ (tmp_data_dir / ".downloading").write_text(str(os.getpid()))+ success, _ = download_journal_data()+ assert success is False+ assert self._get_counts() is None++ @patch("local_deep_research.journal_quality.downloader._fetch_institutions")+ @patch(+ "local_deep_research.journal_quality.downloader"+ "._fetch_jabref_abbreviations"+ )+ @patch("local_deep_research.journal_quality.downloader._fetch_predatory")+ @patch(+ "local_deep_research.journal_quality.downloader._fetch_openalex_sources"+ )+ @patch(+ "local_deep_research.journal_quality.downloader._fetch_doaj_journals"+ )+ @patch("local_deep_research.journal_quality.db.build_db")+ def test_counts_populated_on_success_then_cleared_on_up_to_date(+ self,+ mock_build_db,+ mock_doaj,+ mock_openalex,+ mock_pred,+ mock_jabref,+ mock_inst,+ tmp_data_dir,+ ):+ """The key anti-stale-leak scenario: a successful download+ populates counts, then a subsequent "already up to date" call+ must invalidate them so the route cannot render last-run's+ numbers as if they came from the new (non-existent) fetch.+ """+ mock_openalex.return_value = 100+ mock_doaj.return_value = 50+ mock_pred.return_value = 0+ mock_jabref.return_value = 0+ mock_inst.return_value = 0+ mock_build_db.return_value = None+ _write_openalex(tmp_data_dir)++ success, _ = download_journal_data(force=True)+ assert success is True+ counts = self._get_counts()+ assert counts is not None+ assert counts["openalex"] == 100+ assert counts["doaj"] == 50++ # Stamp the version.json that the real success path would have+ # written, so the next call takes the "already up to date" branch.+ (tmp_data_dir / "doaj_journals.json").write_text("{}")+ (tmp_data_dir / "version.json").write_text(+ json.dumps({"version": JOURNAL_DATA_VERSION})+ )+ success, _ = download_journal_data()+ assert success is True+ assert self._get_counts() is None++class TestEnsureJournalData:def test_files_in_user_dir(self, tmp_data_dir):_write_openalex(tmp_data_dir)diff --git a/tests/web/routes/test_metrics_routes.py b/tests/web/routes/test_metrics_routes.pyindex 09e14973a5..b457f9f90c 100644--- a/tests/web/routes/test_metrics_routes.py+++ b/tests/web/routes/test_metrics_routes.py@@ -1072,3 +1072,91 @@ class TestApiJournalDataDownload:json={"force": False},)assert response.status_code not in (401, 302)++ def test_response_does_not_echo_internal_message_on_success(+ self, authenticated_client+ ):+ """CodeQL #7684 regression guard: the JSON body must be built+ from structured counts + developer-authored labels, never from+ the raw `(success, message)` string returned by the downloader.++ We seed the downloader with a message that contains a unique+ canary. If the response body includes the canary, a future+ refactor has reintroduced the taint path.+ """+ canary = "TAINT-CANARY-8f3a9e-do-not-leak"+ internal_msg = f"Fetched 42 OpenAlex sources ... {canary}"++ with (+ patch(+ "local_deep_research.journal_quality.downloader.download_journal_data",+ return_value=(True, internal_msg),+ ),+ patch(+ "local_deep_research.journal_quality.downloader.get_download_state",+ return_value={+ "counts": {+ "openalex": 42,+ "doaj": 7,+ "jabref": 3,+ "predatory": 1,+ "institutions": 5,+ }+ },+ ),+ patch("local_deep_research.journal_quality.db.build_reference_db"),+ patch("local_deep_research.journal_quality.db.reset_db"),+ ):+ response = authenticated_client.post(+ f"{METRICS_PREFIX}/api/journal-data/download",+ json={"force": True},+ )++ # Skip if CSRF/rate-limit short-circuits (those paths don't+ # reach the response-construction code we're guarding).+ if response.status_code != 200:+ pytest.skip(+ f"Route gated by CSRF/rate-limit (status={response.status_code})"+ )+ body = response.get_data(as_text=True)+ assert canary not in body, (+ "Response leaked the downloader's internal_message — "+ "CodeQL py/stack-trace-exposure has regressed."+ )+ data = response.get_json()+ assert data["success"] is True+ # Structured counts reach the user-facing message.+ assert "42" in data["message"]++ def test_response_up_to_date_message_when_counts_none(+ self, authenticated_client+ ):+ """When `get_download_state()["counts"]` is None (the downloader+ took the early-return up-to-date branch), the route must emit+ the fixed up-to-date literal — not fall through to an empty+ "Fetched ." string.+ """+ with (+ patch(+ "local_deep_research.journal_quality.downloader.download_journal_data",+ return_value=(True, "Journal data is already up to date"),+ ),+ patch(+ "local_deep_research.journal_quality.downloader.get_download_state",+ return_value={"counts": None},+ ),+ patch("local_deep_research.journal_quality.db.build_reference_db"),+ patch("local_deep_research.journal_quality.db.reset_db"),+ ):+ response = authenticated_client.post(+ f"{METRICS_PREFIX}/api/journal-data/download",+ json={"force": False},+ )++ if response.status_code != 200:+ pytest.skip(+ f"Route gated by CSRF/rate-limit (status={response.status_code})"+ )+ data = response.get_json()+ assert data["success"] is True+ assert "up to date" in data["message"].lower()