~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): refuse hostile-snapshot record floods in journal-quality fetchers (#7973)
LearningCircuit433af5c39bf2
diff --git a/changelog.d/7973.security.md b/changelog.d/7973.security.mdnew file mode 100644index 0000000000..aadc64f1e5--- /dev/null+++ b/changelog.d/7973.security.md@@ -0,0 +1 @@+Journal-quality dataset fetchers now refuse snapshots carrying implausibly many records (1M OpenAlex sources, 500K institutions plus 2.5M combined institution id/ROR/name-index entries, 500K abbreviations, 200K DOAJ journals, 50K predatory entries per list). A compromised dataset origin could previously pass every transport check and fill the decompression caps with millions of minimal records, exhausting server memory before any of the existing "suspiciously few records" floors fired. The ceilings are checked per record, before the record is stored, and bound the number of accumulated entries only: individual field lengths are not capped by this change, and the DOAJ, JabRef and predatory fetchers still hold each downloaded body in memory whole, bounded only by the existing transport size cap.diff --git a/src/local_deep_research/journal_quality/data_sources/base.py b/src/local_deep_research/journal_quality/data_sources/base.pyindex af0ae7c256..b3c5a9ceab 100644--- a/src/local_deep_research/journal_quality/data_sources/base.py+++ b/src/local_deep_research/journal_quality/data_sources/base.py@@ -18,6 +18,20 @@ from typing import Anyfrom loguru import logger+class HostileSnapshotError(RuntimeError):+ """A dataset body carried implausibly many records.++ Raised by a fetcher's accumulation loop once record count crosses+ the source's ceiling — a hostile or grossly malformed upstream can+ pass every transport check (the manifest self-certifies+ content_length and md5) and otherwise fill the decompressed-char+ caps with minimal records until the process OOMs. Deliberately a+ distinct type so a per-file ``except Exception: continue`` handler+ (JabRef) can re-raise it instead of treating a hostile snapshot as+ one flaky file.+ """++def atomic_replace(tmp: Path, output: Path) -> None:"""Move a fully-written temp file onto ``output``, overwriting it.diff --git a/src/local_deep_research/journal_quality/data_sources/doaj.py b/src/local_deep_research/journal_quality/data_sources/doaj.pyindex 097d3595b1..cce33bf479 100644--- a/src/local_deep_research/journal_quality/data_sources/doaj.py+++ b/src/local_deep_research/journal_quality/data_sources/doaj.py@@ -18,7 +18,7 @@ from pathlib import Pathfrom loguru import loggerfrom ...utilities.citation_normalizer import normalize_issn-from .base import DataSource, atomic_replace+from .base import DataSource, HostileSnapshotError, atomic_replace# Public CSV of the full DOAJ journal list. CC0 metadata._DOAJ_CSV_URL = "https://doaj.org/csv"@@ -41,6 +41,17 @@ _COL_PUBLISHER = "Publisher"# existing good data file._MIN_DOAJ_JOURNALS = 5_000+# Upper bound on accumulated journals — the missing half of the floor+# above. A compromised DOAJ origin can serve a maximally-sized body+# (safe_get caps transport at 1 GiB) of minimal CSV rows whose ISSNs+# are unique, OOM-ing the process through this dict before any floor+# fires. ~22K live journals today; 200_000 keeps ~9x growth headroom.+# This bounds the number of accumulated journals (checked per row,+# before the row is stored). It does not bound field lengths, and the+# downloaded body (``resp.content`` plus its decoded text) is held+# whole — limited only by safe_get's transport size cap.+_MAX_DOAJ_JOURNALS = 200_000+class DOAJSource(DataSource):key = "doaj" # gitleaks:allow@@ -82,6 +93,13 @@ class DOAJSource(DataSource):journals: dict = {}for row in reader:+ if len(journals) >= _MAX_DOAJ_JOURNALS:+ raise HostileSnapshotError(+ f"DOAJ: suspiciously many journals "+ f"({len(journals):,} >= {_MAX_DOAJ_JOURNALS:,}); "+ "refusing to accumulate a possibly hostile snapshot. "+ "Possible CSV schema change upstream."+ )# Prefer print ISSN, fall back to electronic. The CSV uses# empty strings for missing values. Normalize to the# 8-char no-dash canonical form so lookups (which alsodiff --git a/src/local_deep_research/journal_quality/data_sources/institutions.py b/src/local_deep_research/journal_quality/data_sources/institutions.pyindex 746cc8107d..9f32d4eea5 100644--- a/src/local_deep_research/journal_quality/data_sources/institutions.py+++ b/src/local_deep_research/journal_quality/data_sources/institutions.py@@ -32,7 +32,7 @@ from ._openalex_common import (validate_manifest_entries,)from ..scoring import normalize_name-from .base import DataSource, atomic_replace+from .base import DataSource, HostileSnapshotError, atomic_replace_OPENALEX_INSTITUTIONS_MANIFEST = (f"{OPENALEX_S3_BASE}/data/jsonl/institutions/manifest.json"@@ -43,6 +43,33 @@ _OPENALEX_INSTITUTIONS_MANIFEST = (# change, empty partitions, or broken manifest)._MIN_INSTITUTIONS = 50_000+# Upper bounds on what the fetch accumulates — the missing half of the+# floor above. A hostile (or grossly malformed) manifest can pass every+# transport check (it self-declares content_length and md5) and fill+# the decompressed-char cap with minimal records, OOM-ing the process+# before any floor fires.+#+# Three structures grow: ``institutions`` (one entry per distinct id),+# ``ror_index`` (one per distinct ror) and ``name_index`` (one per+# distinct normalised display name *and* per distinct alternative+# name). Counting only ``institutions`` is not enough: records that+# repeat one id with fresh ror/display_name values, or a single record+# carrying a huge ``display_name_alternatives`` list, grow the indexes+# without growing ``institutions``. So two ceilings apply:+#+# * ``_MAX_INSTITUTIONS`` — distinct institution ids. ~120-200K live+# records today; 500_000 keeps generous growth headroom.+# * ``_MAX_INSTITUTION_INDEX_ENTRIES`` — the combined entry count of all+# three structures, checked before every insertion (including inside+# the alternatives loop, so one oversized record cannot overshoot).+# Live data adds roughly one ror plus a few names per institution;+# 2_500_000 leaves ~5 entries per record at the record ceiling.+#+# These bound entry *counts* only; individual string lengths are+# limited by the per-line cap in ``_openalex_common``, not here.+_MAX_INSTITUTIONS = 500_000+_MAX_INSTITUTION_INDEX_ENTRIES = 2_500_000+class InstitutionSource(DataSource):key = "institutions" # gitleaks:allow@@ -117,6 +144,20 @@ class InstitutionSource(DataSource):name_index: dict = {}start = time.time()+ def _check_index_ceiling() -> None:+ # Combined entry count across every growing structure. The+ # per-record call leaves room for that record's id, ror and+ # primary name (at most 3 entries); each alternative name is+ # checked individually before it is inserted.+ entries_held = len(institutions) + len(ror_index) + len(name_index)+ if entries_held >= _MAX_INSTITUTION_INDEX_ENTRIES:+ raise HostileSnapshotError(+ f"OpenAlex institutions: suspiciously many index "+ f"entries ({entries_held:,} >= "+ f"{_MAX_INSTITUTION_INDEX_ENTRIES:,}); refusing to "+ "accumulate a possibly hostile snapshot"+ )+for idx, total_parts, records in iter_partitions(entries,data_dir,@@ -125,6 +166,14 @@ class InstitutionSource(DataSource):safe_get=safe_get,):for inst in records:+ if len(institutions) >= _MAX_INSTITUTIONS:+ raise HostileSnapshotError(+ f"OpenAlex institutions: suspiciously many records "+ f"({len(institutions):,} >= {_MAX_INSTITUTIONS:,}); "+ "refusing to accumulate a possibly hostile "+ "snapshot"+ )+ _check_index_ceiling()inst_id = (inst.get("id") or "").split("/")[-1]if not inst_id:continue@@ -152,6 +201,7 @@ class InstitutionSource(DataSource):for alt in inst.get("display_name_alternatives") or []:alt_lower = normalize_name(alt or "")if alt_lower and alt_lower not in name_index:+ _check_index_ceiling()name_index[alt_lower] = inst_idif (idx + 1) % 5 == 0 or idx == total_parts - 1:diff --git a/src/local_deep_research/journal_quality/data_sources/jabref.py b/src/local_deep_research/journal_quality/data_sources/jabref.pyindex e20819c481..233601a931 100644--- a/src/local_deep_research/journal_quality/data_sources/jabref.py+++ b/src/local_deep_research/journal_quality/data_sources/jabref.py@@ -14,11 +14,21 @@ from pathlib import Pathfrom loguru import logger-from .base import DataSource, atomic_replace+from .base import DataSource, HostileSnapshotError, atomic_replace_JABREF_BASE = ("https://raw.githubusercontent.com/JabRef/abbrv.jabref.org/main/journals")++# Upper bound on accumulated abbreviations. A compromised GitHub raw+# origin can serve maximal CSV bodies of unique abbreviation rows,+# OOM-ing the process through this dict — the only existing guard is+# the too-few floor below. ~66K live mappings today; 500_000 keeps+# ~7x growth headroom. This bounds the number of accumulated mappings+# (checked per row, before the row is stored). It does not bound field+# lengths, and each downloaded CSV body (``resp.text``) is held whole —+# limited only by safe_get's transport size cap.+_MAX_JABREF_ABBREVS = 500_000_JABREF_FILES = ["journal_abbreviations_entrez.csv","journal_abbreviations_ubc.csv",@@ -69,6 +79,13 @@ class JabRefSource(DataSource):resp.raise_for_status()reader = csv.reader(io.StringIO(resp.text))for row in reader:+ if len(abbrev_to_full) >= _MAX_JABREF_ABBREVS:+ raise HostileSnapshotError( # noqa: TRY301 — re-raised by the except HostileSnapshotError handler below so a hostile body aborts the fetch+ f"JabRef: suspiciously many abbreviations "+ f"({len(abbrev_to_full):,} >= "+ f"{_MAX_JABREF_ABBREVS:,}); refusing to "+ "accumulate a possibly hostile snapshot"+ )if len(row) < 2:continuefull_name = row[0].strip().strip('"')@@ -105,6 +122,12 @@ class JabRefSource(DataSource):f"{full_name!r}")abbrev_to_full[no_dots] = full_name+ except HostileSnapshotError:+ # A hostile/grossly-malformed body is a property of the+ # upstream, not one flaky file — abort the whole fetch+ # rather than continue past the ceiling with the next+ # file.+ raiseexcept Exception:# Preserve traceback — operators diagnosing partial# fetch failures need the exception type (timeout,diff --git a/src/local_deep_research/journal_quality/data_sources/openalex.py b/src/local_deep_research/journal_quality/data_sources/openalex.pyindex e974aac061..a257d075e3 100644--- a/src/local_deep_research/journal_quality/data_sources/openalex.py+++ b/src/local_deep_research/journal_quality/data_sources/openalex.py@@ -31,7 +31,7 @@ from pathlib import Pathfrom loguru import loggerfrom ...utilities.citation_normalizer import normalize_issn-from .base import DataSource, atomic_replace+from .base import DataSource, HostileSnapshotError, atomic_replacefrom ._openalex_common import (OPENALEX_S3_BASE,@@ -43,6 +43,19 @@ _OPENALEX_SOURCES_MANIFEST = (f"{OPENALEX_S3_BASE}/data/jsonl/sources/manifest.json")+# Upper bound on accumulated source records — the missing half of the+# ``_MIN_OPENALEX_SOURCES`` floor. The manifest self-certifies its+# partitions (content_length + md5 both come from the same fetch), so a+# hostile origin can serve valid-schema minimal records up to the+# decompressed-char cap (~4 GiB ≈ 23M records at ~183 chars each) and+# OOM the process through this dict before any floor fires. The real+# snapshot carries ~280K sources; 1_000_000 keeps >3x growth headroom.+# This bounds the number of accumulated records, not their size: each+# stored field is limited only by the per-line cap in+# ``_openalex_common`` (10M chars), so the ceiling caps entry count+# rather than guaranteeing a specific memory figure.+_MAX_OPENALEX_SOURCES = 1_000_000+class SchemaDriftError(RuntimeError):"""OpenAlex renamed / removed a required field in the snapshot.@@ -148,6 +161,13 @@ class OpenAlexSource(DataSource):safe_get=safe_get,):for rec in records:+ if len(sources) >= _MAX_OPENALEX_SOURCES:+ raise HostileSnapshotError(+ f"OpenAlex sources: suspiciously many records "+ f"({len(sources):,} >= {_MAX_OPENALEX_SOURCES:,}); "+ "refusing to accumulate a possibly hostile "+ "snapshot"+ )parsed_records += 1src_id = (rec.get("id") or "").split("/")[-1]if not src_id:diff --git a/src/local_deep_research/journal_quality/data_sources/predatory.py b/src/local_deep_research/journal_quality/data_sources/predatory.pyindex f87e908f91..b76b28b5fd 100644--- a/src/local_deep_research/journal_quality/data_sources/predatory.py+++ b/src/local_deep_research/journal_quality/data_sources/predatory.py@@ -11,11 +11,12 @@ from __future__ import annotationsimport csvimport ioimport json+from collections.abc import Iteratorfrom pathlib import Pathfrom loguru import logger-from .base import DataSource, atomic_replace+from .base import DataSource, HostileSnapshotError, atomic_replace_PREDATORY_BASE = ("https://raw.githubusercontent.com/stop-predatory-journals/"@@ -34,6 +35,17 @@ _PREDATORY_FILES = {# filtering for everyone._MIN_PREDATORY_TOTAL = 100+# Upper bound per list — the missing half of the floor above. A+# compromised GitHub raw origin can serve maximal CSV bodies of unique+# names, OOM-ing the process through these lists before any floor+# fires. The live lists carry thousands of entries; 50_000 per list is+# >10x headroom. This bounds the number of parsed rows kept per list+# (checked per row, before the row is stored); it does not bound the+# length of individual fields, and it does not bound the downloaded+# body, which is held whole and limited only by safe_get's transport+# size cap.+_MAX_PREDATORY_PER_LIST = 50_000+class PredatorySource(DataSource):key = "predatory" # gitleaks:allow@@ -67,29 +79,51 @@ class PredatorySource(DataSource):journals: list[dict] = []hijacked: list[dict] = []- def _read_csv(filename: str) -> list[dict]:+ def _read_csv(filename: str) -> Iterator[dict]:+ # A generator, not a list: the per-list ceiling below is+ # checked as each row is parsed, so a hostile body is refused+ # after at most ceiling+1 parsed rows instead of being+ # materialised as one dict per row first. The response body+ # itself (``resp.text``) is still held whole; that is bounded+ # only by safe_get's transport size cap, not by this ceiling.url = f"{_PREDATORY_BASE}/{filename}"resp = safe_get(url, timeout=30, consume_body=True, require_https=True)resp.raise_for_status()reader = csv.DictReader(io.StringIO(resp.text))- return [- {k: (v or "").strip() for k, v in row.items() if k}- for row in reader- ]+ for row in reader:+ yield {k: (v or "").strip() for k, v in row.items() if k}for row in _read_csv(_PREDATORY_FILES["publishers"]):+ if len(publishers) >= _MAX_PREDATORY_PER_LIST:+ raise HostileSnapshotError(+ f"Predatory publishers: suspiciously many records "+ f"({len(publishers):,} >= {_MAX_PREDATORY_PER_LIST:,}); "+ "refusing to accumulate a possibly hostile snapshot"+ )name = row.get("name", "")if name:publishers.append({"name": name, "url": row.get("url", "")})for row in _read_csv(_PREDATORY_FILES["journals"]):+ if len(journals) >= _MAX_PREDATORY_PER_LIST:+ raise HostileSnapshotError(+ f"Predatory journals: suspiciously many records "+ f"({len(journals):,} >= {_MAX_PREDATORY_PER_LIST:,}); "+ "refusing to accumulate a possibly hostile snapshot"+ )name = row.get("name", "")if name:journals.append({"name": name, "url": row.get("url", "")})for row in _read_csv(_PREDATORY_FILES["hijacked"]):+ if len(hijacked) >= _MAX_PREDATORY_PER_LIST:+ raise HostileSnapshotError(+ f"Predatory hijacked: suspiciously many records "+ f"({len(hijacked):,} >= {_MAX_PREDATORY_PER_LIST:,}); "+ "refusing to accumulate a possibly hostile snapshot"+ )# Upstream column names: hijacked, hijackedabbr, hijackedurl,# althijackedurl, authentic, authenticabbr, authenticurl.# The rest of the codebase reads `hijacked_name`, so map across.diff --git a/tests/journal_quality/test_snapshot_record_ceilings.py b/tests/journal_quality/test_snapshot_record_ceilings.pynew file mode 100644index 0000000000..988b699d9e--- /dev/null+++ b/tests/journal_quality/test_snapshot_record_ceilings.py@@ -0,0 +1,422 @@+"""Hostile-snapshot record-count ceilings for the journal-quality datasets.++Threat model (the module's own — see ``db.py``'s ``_as_number``+docstring and ``_openalex_common.py``'s manifest-allowlist comment):+a compromised dataset origin. The manifest self-declares+``meta.content_length`` and ``meta.md5``, so the existing transport+checks pass by construction for a hostile origin, and the+decompressed-char caps permit ~23M minimal records per OpenAlex+partition (~183 chars each against the 4 GiB default cap) — which+accumulates into a multi-gigabyte in-process dict and OOM-kills the+server long before any *floor* ("suspiciously few records") fires.++These contracts pin the missing upper bound on *entry count*: every+fetcher refuses to accumulate entries past its ceiling, checked+*inside* the accumulation loop before each entry is stored — the+counting-reader tests assert that at most ceiling+1 rows are consumed+when the ceiling trips, so a check moved after the loop (or a reader+that materialises every row first) fails them. For institutions every+growing structure (ids, ROR index, name index including alternative+names) counts against a combined ceiling. Realistic fleet-sized+payloads continue to pass.++What these ceilings do NOT bound: the length of individual fields+(limited only by the OpenAlex per-line cap or the CSV body size), and+the whole-body buffering of the DOAJ, JabRef and predatory responses,+which are held in memory whole and limited only by safe_get's+transport size cap.+"""++from __future__ import annotations++import gzip+import hashlib+import io+import json+from unittest.mock import MagicMock++import pytest++from local_deep_research.journal_quality.data_sources import (+ doaj,+ jabref,+ openalex,+)+from local_deep_research.journal_quality.data_sources.base import (+ HostileSnapshotError,+)+from local_deep_research.journal_quality.data_sources import (+ institutions as inst_mod,+)+from local_deep_research.journal_quality.data_sources import (+ predatory as pred_mod,+)+from local_deep_research.security import safe_requests+++def _gz_records(records: list[dict]) -> bytes:+ buf = io.BytesIO()+ with gzip.GzipFile(fileobj=buf, mode="wb") as gz:+ for rec in records:+ gz.write(json.dumps(rec, separators=(",", ":")).encode() + b"\n")+ return buf.getvalue()+++def _response(content: bytes) -> MagicMock:+ resp = MagicMock()+ resp.raise_for_status = MagicMock()+ resp.content = content+ return resp+++def _text_response(text: str) -> MagicMock:+ resp = MagicMock()+ resp.raise_for_status = MagicMock()+ resp.text = text+ resp.content = text.encode("utf-8")+ return resp+++def _manifest_for(part: bytes, record_count: int) -> MagicMock:+ """Manifest whose single partition self-certifies (length + md5)."""+ manifest = {+ "files": [+ {+ "url": "s3://openalex/data/jsonl/x/part_0.gz",+ "meta": {+ "content_length": len(part),+ "md5": hashlib.md5(part, usedforsecurity=False).hexdigest(),+ "record_count": record_count,+ },+ }+ ]+ }+ resp = MagicMock()+ resp.raise_for_status = MagicMock()+ resp.json = MagicMock(return_value=manifest)+ return resp+++def _patch_safe_get(monkeypatch, responses: list[MagicMock]) -> dict:+ """Patch safe_get_with_retries; return the kwargs it was called with."""+ calls = {"kwargs": None}+ seq = list(responses)++ def fake(url, **kwargs):+ calls["kwargs"] = kwargs+ return seq.pop(0)++ monkeypatch.setattr(safe_requests, "safe_get_with_retries", fake)+ return calls+++def _openalex_record(i: int) -> dict:+ return {+ "id": f"https://openalex.org/S{i:09d}",+ "display_name": f"Journal {i}",+ "type": "journal",+ "cited_by_count": 1,+ "summary_stats": {"h_index": 1, "2yr_mean_citedness": 0.1},+ }+++def _counting_partitions(orig, counter: dict):+ """Wrap ``iter_partitions`` so every record pulled is counted."""++ def wrapped(*args, **kwargs):+ for idx, total, records in orig(*args, **kwargs):+ yield idx, total, _counted(records, counter)++ return wrapped+++def _counted(rows, counter: dict):+ for row in rows:+ counter["rows"] += 1+ yield row+++def _counting_factory(factory, counter: dict):+ """Wrap a csv reader factory so every parsed row is counted."""++ def make(*args, **kwargs):+ return _counted(factory(*args, **kwargs), counter)++ return make+++class TestProductionCeilings:+ def test_production_ceiling_values(self):+ """The behavioural tests below monkeypatch small ceilings; pin+ the shipped values here so they cannot silently drift."""+ assert openalex._MAX_OPENALEX_SOURCES == 1_000_000+ assert inst_mod._MAX_INSTITUTIONS == 500_000+ assert inst_mod._MAX_INSTITUTION_INDEX_ENTRIES == 2_500_000+ assert doaj._MAX_DOAJ_JOURNALS == 200_000+ assert jabref._MAX_JABREF_ABBREVS == 500_000+ assert pred_mod._MAX_PREDATORY_PER_LIST == 50_000+++class TestOpenAlexSourcesCeiling:+ def test_refuses_past_the_record_ceiling(self, tmp_path, monkeypatch):+ """A hostile partition carrying more records than the ceiling is+ refused after at most ceiling+1 records are consumed.++ Every existing control passes for this payload: the s3://openalex+ allowlist, the self-declared content_length and md5, the schema+ fields, and the decompressed-char caps. Only the record-count+ ceiling stops the accumulation.+ """+ monkeypatch.setattr(openalex, "_MAX_OPENALEX_SOURCES", 100)+ counter = {"rows": 0}+ monkeypatch.setattr(+ openalex,+ "iter_partitions",+ _counting_partitions(openalex.iter_partitions, counter),+ )+ records = [_openalex_record(i) for i in range(500)]+ part = _gz_records(records)+ _patch_safe_get(+ monkeypatch,+ [_manifest_for(part, len(records)), _response(part)],+ )+ with pytest.raises(HostileSnapshotError, match="suspiciously many"):+ openalex.OpenAlexSource().fetch(tmp_path)+ assert counter["rows"] <= 101++ def test_fleet_sized_snapshot_still_passes(self, tmp_path, monkeypatch):+ """A realistic snapshot (above the 10K floor, far below the+ ceiling) is accepted unchanged."""+ records = [_openalex_record(i) for i in range(10_000)]+ part = _gz_records(records)+ _patch_safe_get(+ monkeypatch,+ [_manifest_for(part, len(records)), _response(part)],+ )+ count = openalex.OpenAlexSource().fetch(tmp_path)+ assert count == 10_000+ assert (tmp_path / "openalex_sources.json.gz").exists()+++class TestInstitutionsCeiling:+ @staticmethod+ def _serve(monkeypatch, records: list[dict]) -> None:+ part = _gz_records(records)+ _patch_safe_get(+ monkeypatch,+ [_manifest_for(part, len(records)), _response(part)],+ )++ def test_refuses_past_the_record_ceiling(self, tmp_path, monkeypatch):+ monkeypatch.setattr(inst_mod, "_MAX_INSTITUTIONS", 100)+ counter = {"rows": 0}+ monkeypatch.setattr(+ inst_mod,+ "iter_partitions",+ _counting_partitions(inst_mod.iter_partitions, counter),+ )+ self._serve(+ monkeypatch,+ [+ {+ "id": f"https://openalex.org/I{i}",+ "display_name": f"Inst {i}",+ }+ for i in range(500)+ ],+ )+ with pytest.raises(HostileSnapshotError, match="suspiciously many"):+ inst_mod.InstitutionSource().fetch(tmp_path)+ assert counter["rows"] <= 101++ def test_repeated_id_with_fresh_indexes_is_refused(+ self, tmp_path, monkeypatch+ ):+ """One id repeated with a fresh ror/display_name each time never+ grows ``institutions`` but grows both indexes; the combined+ index-entry ceiling refuses it."""+ monkeypatch.setattr(inst_mod, "_MAX_INSTITUTION_INDEX_ENTRIES", 100)+ counter = {"rows": 0}+ monkeypatch.setattr(+ inst_mod,+ "iter_partitions",+ _counting_partitions(inst_mod.iter_partitions, counter),+ )+ self._serve(+ monkeypatch,+ [+ {+ "id": "https://openalex.org/I1",+ "ror": f"https://ror.org/0r{i:07d}",+ "display_name": f"Inst {i}",+ }+ for i in range(1_000)+ ],+ )+ with pytest.raises(HostileSnapshotError, match="index entries"):+ inst_mod.InstitutionSource().fetch(tmp_path)+ # Two index entries per record: the ceiling trips after ~50.+ assert counter["rows"] <= 51++ def test_huge_alternatives_list_is_refused_mid_record(+ self, tmp_path, monkeypatch+ ):+ """A single record with a huge ``display_name_alternatives`` list+ is refused inside the alternatives loop, before the list is+ indexed in full."""+ monkeypatch.setattr(inst_mod, "_MAX_INSTITUTION_INDEX_ENTRIES", 100)+ calls = {"rows": 0}+ orig_normalize = inst_mod.normalize_name++ def counting_normalize(name):+ calls["rows"] += 1+ return orig_normalize(name)++ monkeypatch.setattr(inst_mod, "normalize_name", counting_normalize)+ self._serve(+ monkeypatch,+ [+ {+ "id": "https://openalex.org/I1",+ "display_name": "Inst",+ "display_name_alternatives": [+ f"Alt {i}" for i in range(10_000)+ ],+ }+ ],+ )+ with pytest.raises(HostileSnapshotError, match="index entries"):+ inst_mod.InstitutionSource().fetch(tmp_path)+ # primary name + at most ceiling alternative names normalised.+ assert calls["rows"] <= 102++ def test_fleet_sized_snapshot_still_passes(self, tmp_path, monkeypatch):+ records = [+ {+ "id": f"https://openalex.org/I{i}",+ "ror": f"https://ror.org/0r{i:07d}",+ "display_name": f"Inst {i}",+ "display_name_alternatives": [f"Alt A {i}", f"Alt B {i}"],+ }+ for i in range(50_000)+ ]+ self._serve(monkeypatch, records)+ count = inst_mod.InstitutionSource().fetch(tmp_path)+ assert count == 50_000+++class TestDOAJCeiling:+ @staticmethod+ def _csv(n: int) -> str:+ rows = ["Journal title,Journal ISSN (print version),Publisher"]+ # Unique 8-digit ISSN per row: journals are keyed by ISSN, so a+ # repeated ISSN would collapse rows and under-count.+ rows += [f"Journal {i},{i:08d},Pub {i}" for i in range(n)]+ return "\n".join(rows)++ def test_refuses_past_the_record_ceiling(self, tmp_path, monkeypatch):+ monkeypatch.setattr(doaj, "_MAX_DOAJ_JOURNALS", 100)+ counter = {"rows": 0}+ monkeypatch.setattr(+ doaj.csv,+ "DictReader",+ _counting_factory(doaj.csv.DictReader, counter),+ )+ _patch_safe_get(monkeypatch, [_text_response(self._csv(500))])+ with pytest.raises(HostileSnapshotError, match="suspiciously many"):+ doaj.DOAJSource().fetch(tmp_path)+ # Checked inside the loop: refused on row ceiling+1, not after+ # all 500 rows were accumulated.+ assert counter["rows"] <= 101++ def test_fleet_sized_csv_still_passes(self, tmp_path, monkeypatch):+ _patch_safe_get(monkeypatch, [_text_response(self._csv(5_000))])+ count = doaj.DOAJSource().fetch(tmp_path)+ assert count == 5_000+++class TestJabRefCeiling:+ @staticmethod+ def _csv(n: int, tag: str = "f0") -> str:+ rows = ["Full Name,Abbreviation"]+ rows += [f"Journal Full {i} {tag},J Full {i} {tag}" for i in range(n)]+ return "\n".join(rows)++ def test_refuses_past_the_record_ceiling(self, tmp_path, monkeypatch):+ monkeypatch.setattr(jabref, "_MAX_JABREF_ABBREVS", 100)+ counter = {"rows": 0}+ monkeypatch.setattr(+ jabref.csv, "reader", _counting_factory(jabref.csv.reader, counter)+ )+ # The fetcher loops over all 14 upstream CSVs; serve the hostile+ # payload for the first and empty-but-valid CSVs for the rest.+ hostile = _text_response(self._csv(500))+ rest = [_text_response("Full Name,Abbreviation") for _ in range(13)]+ _patch_safe_get(monkeypatch, [hostile] + rest)+ with pytest.raises(HostileSnapshotError, match="suspiciously many"):+ jabref.JabRefSource().fetch(tmp_path)+ # The header row also parses as a pair, so the ceiling trips on+ # row ceiling+1 counting the header — never after all 501 rows.+ assert counter["rows"] <= 101++ def test_fleet_sized_csv_still_passes(self, tmp_path, monkeypatch):+ responses = [+ _text_response(self._csv(500, tag=f"f{f}")) for f in range(14)+ ]+ _patch_safe_get(monkeypatch, responses)+ count = jabref.JabRefSource().fetch(tmp_path)+ # 14 files x 500 unique abbreviations; the shared header row+ # ("Full Name,Abbreviation") parses as one extra pair.+ assert count == 500 * 14 + 1+++class TestPredatoryCeiling:+ @staticmethod+ def _csv(n: int, name_col: str) -> str:+ rows = [f"{name_col},url"]+ rows += [+ f"Predatory {name_col} {i},https://evil.example/{i}"+ for i in range(n)+ ]+ return "\n".join(rows)++ def test_refuses_past_the_per_list_ceiling(self, tmp_path, monkeypatch):+ monkeypatch.setattr(pred_mod, "_MAX_PREDATORY_PER_LIST", 100)+ counter = {"rows": 0}+ monkeypatch.setattr(+ pred_mod.csv,+ "DictReader",+ _counting_factory(pred_mod.csv.DictReader, counter),+ )+ big_journals = self._csv(500, "name")+ ok_publishers = self._csv(10, "name")+ ok_hijacked = self._csv(10, "hijacked")+ _patch_safe_get(+ monkeypatch,+ [+ _text_response(ok_publishers),+ _text_response(big_journals),+ _text_response(ok_hijacked),+ ],+ )+ with pytest.raises(HostileSnapshotError, match="suspiciously many"):+ pred_mod.PredatorySource().fetch(tmp_path)+ # 10 publisher rows, then the journals list trips on row+ # ceiling+1: rows are parsed lazily and checked before storing,+ # so the remaining hostile rows are never materialised.+ assert counter["rows"] <= 10 + 101++ def test_fleet_sized_csvs_still_pass(self, tmp_path, monkeypatch):+ pubs = self._csv(400, "name")+ journals = self._csv(400, "name")+ hijacked = self._csv(400, "hijacked")+ _patch_safe_get(+ monkeypatch,+ [+ _text_response(pubs),+ _text_response(journals),+ _text_response(hijacked),+ ],+ )+ count = pred_mod.PredatorySource().fetch(tmp_path)+ assert count == 1_200diff --git a/tests/security/INDEX.md b/tests/security/INDEX.mdindex eee371434b..926b7cbd38 100644--- a/tests/security/INDEX.md+++ b/tests/security/INDEX.md@@ -3,5 +3,6 @@| Seam | Contract test | PR ||---|---|---|| `GET /benchmark/api/results` `grader_response` CWE-209 boundary (failure-prefixed raw exception detail genericized, including the historical 🔑-decorated prefix; normal/NULL pass through) | `tests/web/routers/test_benchmark_results_grader_response_boundary.py` | #7591 |+| journal-quality dataset fetch record-count ceilings (hostile-upstream bound on accumulated entry count; `HostileSnapshotError` raised inside the accumulation loop, before storing, for OpenAlex sources, institutions (ids and combined id/ROR/name-index entries, incl. per alternative name), DOAJ, JabRef, predatory lists (lazy CSV rows); fleet-sized payloads pass. Not covered: field lengths, whole-body buffering of DOAJ/JabRef/predatory responses, which only the transport size cap bounds) | `tests/journal_quality/test_snapshot_record_ceilings.py` | #7973 || Chat research-start boundary `is_safe_custom_llm_endpoint` pre-flight (`send_message` + `retry_attempt` 400 before any row/worker; router-wide structural fence flipped from recorded xfail) | `tests/chat/test_chat_custom_endpoint_gate.py` + `tests/llm/test_provider_adapter_contracts.py::TestCustomEndpointBoundaryGate` | #7992 || `POST /metrics/api/domain-classifications/classify` domain input bound (length capped at 255 — the `DomainClassification.domain` column's own declared length — and control characters rejected at the route boundary, ahead of prompt build/persistence/error echo; pass-through guards pin the 255 edge, ordinary domains, and batch mode) | `tests/web/routers/test_metrics_domain_input_bounds.py` | #7641 |