~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(journal-quality): bound how far the build's gzipped snapshots may decompress (#6784)
Lukasa1052e009fa6
diff --git a/changelog.d/6770.security.md b/changelog.d/6770.security.mdnew file mode 100644index 0000000000..a1c9d88a45--- /dev/null+++ b/changelog.d/6770.security.md@@ -0,0 +1 @@+The journal-quality database build now bounds how far its gzipped snapshots (`openalex_sources.json.gz`, `openalex_institutions.json.gz`, `jabref_abbreviations.json.gz`) may decompress: a file whose text runs past 32 characters per compressed byte plus 1,048,576 characters (and never past 4,294,967,296 characters in all) is refused with a clear error before it is read further, instead of being expanded without limit into one string. A snapshot whose top level is not a JSON object is refused the same way. These files are the pipeline's own output, so this only matters for a replaced or corrupted file; real snapshots compress well under that ratio.diff --git a/src/local_deep_research/journal_quality/db.py b/src/local_deep_research/journal_quality/db.pyindex 92883f9bd5..e2654c36ef 100644--- a/src/local_deep_research/journal_quality/db.py+++ b/src/local_deep_research/journal_quality/db.py@@ -1252,13 +1252,39 @@ def _sweep_stale_tmp_files(directory: Path, base_name: str) -> None:# Source-data loaders (used by build_db only)# ---------------------------------------------------------------------------+# The gzipped snapshots are this pipeline's own output, but a replaced or+# corrupted file must not expand without limit into one string. The bound is+# derived from the compressed size: compact JSON of these records compresses+# well under 32:1, so a file past the bound is refused rather than loaded.+_GZIP_SNAPSHOT_RATIO = 32+_GZIP_SNAPSHOT_SLACK_CHARS = 1024 * 1024+_GZIP_SNAPSHOT_MAX_CHARS = 4 * 1024**3+++def _load_gzip_json(path: Path) -> dict:+ """Parse a gzipped JSON snapshot, refusing one that decompresses too far."""+ cap = min(+ path.stat().st_size * _GZIP_SNAPSHOT_RATIO + _GZIP_SNAPSHOT_SLACK_CHARS,+ _GZIP_SNAPSHOT_MAX_CHARS,+ )+ with gzip.open(path, "rt", encoding="utf-8") as f:+ text = f.read(cap + 1)+ if len(text) > cap:+ raise ValueError(+ f"{path.name} decompresses past {cap:,} characters, "+ f"{_GZIP_SNAPSHOT_RATIO}x its compressed size; refusing to load it"+ )+ data = json.loads(text)+ if not isinstance(data, dict):+ raise ValueError(f"{path.name} is not a JSON object")+ return data+def _load_openalex(data_dir: Path) -> dict:path = data_dir / "openalex_sources.json.gz"if not path.exists():raise FileNotFoundError(f"OpenAlex source file not found: {path}")- with gzip.open(path, "rt", encoding="utf-8") as f:- data = json.load(f)+ data = _load_gzip_json(path)sources = data.get("s", data.get("sources", {}))logger.info(f"Loaded {len(sources)} OpenAlex sources")return dict(sources)@@ -1329,8 +1355,7 @@ def _load_institutions(data_dir: Path) -> dict:if not path.exists():logger.warning(f"{path} not found — institution tier will be empty")return {}- with gzip.open(path, "rt", encoding="utf-8") as f:- data = json.load(f)+ data = _load_gzip_json(path)institutions = data.get("i", {})logger.info(f"Loaded {len(institutions)} institutions")return dict(institutions)@@ -1343,8 +1368,7 @@ def _load_abbreviations(data_dir: Path) -> dict:f"{path} not found — abbreviation expansion will be empty")return {}- with gzip.open(path, "rt", encoding="utf-8") as f:- data = json.load(f)+ data = _load_gzip_json(path)mappings = data.get("abbrev_to_full", {})logger.info(f"Loaded {len(mappings)} abbreviation mappings")return dict(mappings)diff --git a/tests/journal_quality/test_db_offline_build.py b/tests/journal_quality/test_db_offline_build.pyindex 7d0e84fad2..fdc881d645 100644--- a/tests/journal_quality/test_db_offline_build.py+++ b/tests/journal_quality/test_db_offline_build.py@@ -268,6 +268,121 @@ def loguru_sink() -> Iterator[list]:loguru_logger.remove(handler_id)+ ("filename", "loader"),+ [+ ("openalex_sources.json.gz", _load_openalex),+ ("openalex_institutions.json.gz", _load_institutions),+ ("jabref_abbreviations.json.gz", _load_abbreviations),+ ],+)+def test_loaders_refuse_a_snapshot_that_expands_past_its_bound(+ tmp_path: Path, filename: str, loader+) -> None:+ # An empty object followed by 64 MiB of whitespace is valid JSON and+ # gzips to about 64 KiB, far past 32 times its compressed size.+ with gzip.open(tmp_path / filename, "wt", encoding="utf-8") as stream:+ stream.write("{}")+ for _ in range(64):+ stream.write(" " * 1024 * 1024)++ with pytest.raises(ValueError, match="decompresses past"):+ loader(tmp_path)+++ ("filename", "loader"),+ [+ ("openalex_sources.json.gz", _load_openalex),+ ("openalex_institutions.json.gz", _load_institutions),+ ("jabref_abbreviations.json.gz", _load_abbreviations),+ ],+)+def test_loaders_refuse_a_snapshot_that_is_not_a_json_object(+ tmp_path: Path, filename: str, loader+) -> None:+ with gzip.open(tmp_path / filename, "wt", encoding="utf-8") as stream:+ stream.write('["not", "an", "object"]')++ with pytest.raises(ValueError, match="is not a JSON object"):+ loader(tmp_path)+++ ("ratio", "slack", "ceiling"),+ [+ (0, 20, db_module._GZIP_SNAPSHOT_MAX_CHARS),+ (10**6, 0, 20),+ ],+ ids=["size-derived-bound", "fixed-ceiling"],+)+def test_snapshot_bound_admits_exactly_its_cap(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ ratio: int,+ slack: int,+ ceiling: int,+) -> None:+ monkeypatch.setattr(db_module, "_GZIP_SNAPSHOT_RATIO", ratio)+ monkeypatch.setattr(db_module, "_GZIP_SNAPSHOT_SLACK_CHARS", slack)+ monkeypatch.setattr(db_module, "_GZIP_SNAPSHOT_MAX_CHARS", ceiling)+ path = tmp_path / "openalex_sources.json.gz"+ payload = '{"s": {"S1": {}}} '+ assert len(payload) == 20++ with gzip.open(path, "wt", encoding="utf-8") as stream:+ stream.write(payload)+ assert _load_openalex(tmp_path) == {"S1": {}}++ with gzip.open(path, "wt", encoding="utf-8") as stream:+ stream.write(payload + " ")+ with pytest.raises(ValueError, match="decompresses past 20 characters"):+ _load_openalex(tmp_path)+++class _ReadRecorder:+ """A gzip text handle that records the sizes it is asked to read."""++ def __init__(self, handle) -> None:+ self.handle = handle+ self.sizes: list[int] = []++ def __enter__(self) -> "_ReadRecorder":+ return self++ def __exit__(self, *exc_info) -> None:+ self.handle.close()++ def read(self, size: int = -1) -> str:+ self.sizes.append(size)+ return self.handle.read(size)+++def test_snapshot_read_stops_one_character_past_the_cap(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ # The refusal alone would still decompress the whole file first; the+ # read itself has to stop.+ monkeypatch.setattr(db_module, "_GZIP_SNAPSHOT_RATIO", 0)+ monkeypatch.setattr(db_module, "_GZIP_SNAPSHOT_SLACK_CHARS", 20)+ with gzip.open(+ tmp_path / "openalex_sources.json.gz", "wt", encoding="utf-8"+ ) as stream:+ stream.write("{}" + " " * 10_000)+ recorders: list[_ReadRecorder] = []+ real_open = gzip.open++ def recording_open(*args, **kwargs) -> _ReadRecorder:+ recorders.append(_ReadRecorder(real_open(*args, **kwargs)))+ return recorders[-1]++ monkeypatch.setattr(db_module.gzip, "open", recording_open)++ with pytest.raises(ValueError, match="decompresses past"):+ _load_openalex(tmp_path)+ assert [recorder.sizes for recorder in recorders] == [[21]]++def test_malformed_version_metadata_is_ignored(tmp_path: Path, loguru_sink: list) -> None: