~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: enforce snapshot schema and binary content (#6079)
LearningCircuit23ef9c5761e6
diff --git a/.github/scripts/file-whitelist-check.sh b/.github/scripts/file-whitelist-check.shindex 05982fe686..b30f145341 100755--- a/.github/scripts/file-whitelist-check.sh+++ b/.github/scripts/file-whitelist-check.sh@@ -5,8 +5,240 @@set -euo pipefail-# Load allowed file patterns from shared whitelist (single source of truth)REPO_ROOT="$(git rev-parse --show-toplevel 2>/dev/null || echo ".")"++# Content check shared by this Actions gate and the local pre-commit hook.+# A pathname allowlist is not a content allowlist: without this check a PNG,+# executable, or archive renamed to an allowed .py/.json path would pass.+#+# The six binary assets already tracked by the project are exact-path+# exceptions to the "must be reviewable text" rule below, and their content is+# pinned by SHA-256 digest (see PINNED_BINARY_ASSET_DIGESTS / the loader for+# .github/security/binary-asset-hashes.txt) rather than by parsing PNG/MP3+# container structure. A container-format allowlist (accepted chunk/frame+# *types*, well-formed framing) was tried first and does not actually work+# for this: PNG's IDAT chunk type is both unavoidable (every real PNG needs+# one) and unrestricted in length/content, so a complete ZIP fits inside a+# well-formed, correctly-CRC'd IDAT chunk placed before a legitimate IEND --+# `zipfile.ZipFile` opens it while the chunk-framing/chunk-type check accepts+# it, exit 0. MP3 has the same shape of hole: an ID3v2 header's declared+# `tag_size` is trusted and that many bytes are skipped unvalidated, so a+# payload can be sized into the tag region ahead of genuine trailing frames.+# Closing either hole for real means decoding IDAT as zlib/deflate or+# otherwise fully parsing chunk/tag *content*, i.e. reimplementing a PNG/MP3+# decoder here. These six files are exact, known, rarely-changing assets, so+# pinning their exact bytes by hash is simpler and strictly stronger: ANY+# byte change is rejected, not just the subset a container parser happens to+# flag as structurally invalid.+#+# Every other allowed path must be UTF-8 text without binary control bytes or+# a known binary magic signature.+check_file_contents() {+python3 - "$@" <<'PY'+from __future__ import annotations++import hashlib+import pathlib+import re+import sys+++repo_root = pathlib.Path(sys.argv[1]).resolve()+raw_paths = sys.argv[2:]++# Path allowlist: only these six exact paths may carry binary content at all.+# This is the PATH gate, not the CONTENT gate -- it does not validate bytes.+# Keeping it as its own hardcoded set (rather than just "whatever has an+# entry in the digests file") means a missing/mistyped digest can only ever+# make validation stricter -- a path in this set with no matching digest+# fails closed -- never accidentally widen which paths are allowed to be+# binary just because someone appended a line to the digest file.+ALLOWED_BINARY_ASSET_PATHS = frozenset(+ {+ "docs/images/Local Search.png",+ "docs/images/local_search_embedding_model_type.png",+ "docs/images/local_search_paths.png",+ "src/local_deep_research/web/static/favicon.png",+ "src/local_deep_research/web/static/sounds/error.mp3",+ "src/local_deep_research/web/static/sounds/success.mp3",+ }+)++# Standard `sha256sum` output line: 64 hex chars, a space, a mode indicator+# (' ' text / '*' binary), then the path -- so the file doubles as something+# `sha256sum -c` can verify directly from the repo root.+_DIGEST_LINE_RE = re.compile(r"^([0-9a-fA-F]{64}) [ *](.+)$")+++def load_pinned_digests(root: pathlib.Path) -> dict[str, str]:+ digests_path = root / ".github" / "security" / "binary-asset-hashes.txt"+ digests: dict[str, str] = {}+ if not digests_path.is_file():+ return digests+ for line in digests_path.read_text(encoding="utf-8").splitlines():+ if not line.strip() or line.lstrip().startswith("#"):+ continue+ match = _DIGEST_LINE_RE.match(line)+ if not match:+ continue+ digest, path = match.groups()+ digests[path] = digest.lower()+ return digests+++PINNED_BINARY_ASSET_DIGESTS = load_pinned_digests(repo_root)++REGENERATE_DIGESTS_COMMAND = (+ 'sha256sum "docs/images/Local Search.png" '+ '"docs/images/local_search_embedding_model_type.png" '+ '"docs/images/local_search_paths.png" '+ '"src/local_deep_research/web/static/favicon.png" '+ '"src/local_deep_research/web/static/sounds/error.mp3" '+ '"src/local_deep_research/web/static/sounds/success.mp3" '+ "> .github/security/binary-asset-hashes.txt"+)++magic_signatures = (+ (b"\x7fELF", "ELF executable/object"),+ (b"MZ", "PE executable"),+ (b"\xca\xfe\xba\xbe", "Java class/Mach-O binary"),+ (b"\xfe\xed\xfa\xce", "Mach-O binary"),+ (b"\xfe\xed\xfa\xcf", "Mach-O binary"),+ (b"\xce\xfa\xed\xfe", "Mach-O binary"),+ (b"\xcf\xfa\xed\xfe", "Mach-O binary"),+ (b"\x89PNG\r\n\x1a\n", "PNG image"),+ (b"\xff\xd8\xff", "JPEG image"),+ (b"GIF87a", "GIF image"),+ (b"GIF89a", "GIF image"),+ (b"%PDF-", "PDF document"),+ (b"PK\x03\x04", "ZIP/container"),+ (b"PK\x05\x06", "empty ZIP/container"),+ (b"\x1f\x8b", "gzip data"),+ (b"BZh", "bzip2 data"),+ (b"\xfd7zXZ\x00", "xz data"),+ (b"7z\xbc\xaf\x27\x1c", "7z archive"),+ (b"Rar!\x1a\x07", "RAR archive"),+ (b"SQLite format 3\x00", "SQLite database"),+ (b"\x00asm", "WebAssembly"),+ (b"\x00\x01\x00\x00", "TrueType font"),+ (b"OTTO", "OpenType font"),+ (b"wOFF", "WOFF font"),+ (b"wOF2", "WOFF2 font"),+ (b"ID3", "MP3 audio"),+ (b"OggS", "Ogg media"),+ (b"fLaC", "FLAC audio"),+)+++def relative_path(path: pathlib.Path) -> str | None:+ try:+ return path.resolve().relative_to(repo_root).as_posix()+ except ValueError:+ return None+++def pinned_digest_mismatch_reason(repository_path: str, data: bytes) -> str | None:+ """Return a human-readable rejection reason for one of the+ ALLOWED_BINARY_ASSET_PATHS whose content doesn't match its pinned+ SHA-256 digest, or None if the content matches (or there is nothing to+ compare -- callers only invoke this for paths already known to be in+ the allowlist).++ This is a content-equality check, not a "is this well-formed PNG/MP3"+ check -- see the comment above check_file_contents() for why container+ parsing was replaced with hash pinning. A mismatch here does not mean+ the file is corrupt; it means these exact bytes were never reviewed.+ """+ expected = PINNED_BINARY_ASSET_DIGESTS.get(repository_path)+ actual = hashlib.sha256(data).hexdigest()+ if expected is not None and actual == expected:+ return None+ pinned_state = (+ f"pinned digest is {expected}"+ if expected is not None+ else "no pinned digest is on file for this path"+ )+ return (+ f"content (sha256 {actual}) does not match its pinned digest in "+ f".github/security/binary-asset-hashes.txt ({pinned_state}) -- this "+ "does NOT mean the file is corrupt, it means these exact bytes were "+ "never reviewed. If this is an intentional asset update (e.g. "+ "re-exporting an icon or replacing a sound), regenerate ALL SIX "+ "digests in the SAME PR as the byte change so the change is "+ f"reviewed: {REGENERATE_DIGESTS_COMMAND}"+ )+++def binary_reason(data: bytes) -> str | None:+ for signature, description in magic_signatures:+ if data.startswith(signature):+ return description+ if data.startswith(b"RIFF") and data[8:12] in {b"AVI ", b"WAVE", b"WEBP"}:+ return f"RIFF/{data[8:12].decode('ascii', 'replace').strip()} binary"+ if len(data) >= 12 and data[4:8] == b"ftyp":+ return "ISO media container"+ if b"\x00" in data:+ return "NUL byte"+ try:+ data.decode("utf-8")+ except UnicodeDecodeError:+ return "non-UTF-8 content"+ controls = [+ byte+ for byte in data+ if (byte < 32 and byte not in {9, 10, 12, 13}) or byte == 127+ ]+ # Isolated controls can be intentional text fixtures (for example a JS+ # regression test that embeds SOH before ``javascript:``). Dense controls+ # are binary-like; require both a useful minimum count and density so those+ # source fixtures stay reviewable while opaque control-byte payloads fail.+ if len(controls) >= 8 and len(controls) / max(len(data), 1) >= 0.01:+ rendered = ", ".join(f"0x{byte:02x}" for byte in sorted(set(controls)))+ return f"dense binary control byte(s): {rendered}"+ return None+++failed = False+for raw_path in raw_paths:+ candidate = pathlib.Path(raw_path)+ if not candidate.is_absolute():+ candidate = repo_root / candidate+ if not candidate.is_file():+ continue+ try:+ data = candidate.read_bytes()+ except OSError as error:+ print(f"{raw_path}\tunable to inspect content: {error}")+ failed = True+ continue++ repository_path = relative_path(candidate)+ if repository_path in ALLOWED_BINARY_ASSET_PATHS:+ mismatch = pinned_digest_mismatch_reason(repository_path, data)+ if mismatch is not None:+ print(f"{raw_path}\t{mismatch}")+ failed = True+ continue++ reason = binary_reason(data)+ if reason is not None:+ print(f"{raw_path}\t{reason}")+ failed = True++raise SystemExit(1 if failed else 0)+PY+}++# Narrow entry point used by .pre-commit-hooks/file-whitelist-check.sh. Keeping+# the classifier here means the CI-enforced, maintainer-owned script remains the+# single source of truth instead of two binary detectors drifting apart.+if [ "${1:-}" = "--content-only" ]; then+shift+check_file_contents "$REPO_ROOT" "$@"+exit $?+fi++# Load allowed file patterns from shared whitelist (single source of truth)WHITELIST_FILE="$REPO_ROOT/.file-whitelist.txt"if [ ! -f "$WHITELIST_FILE" ]; then@@ -80,6 +312,7 @@ FILES_CHECKED=0WHITELIST_VIOLATIONS=()LARGE_FILES=()BINARY_FILES=()+CONTENT_CHECK_FILES=()SUSPICIOUS_FILES=()RESEARCH_DATA_VIOLATIONS=()FLASK_SECRET_VIOLATIONS=()@@ -99,6 +332,7 @@ continuefiFILES_CHECKED=$((FILES_CHECKED + 1))+CONTENT_CHECK_FILES+=("$file")if [ $((FILES_CHECKED % 10)) -eq 0 ]; thenprintf "."fi@@ -124,11 +358,6 @@ LARGE_FILES+=("$file ($(echo "$FILE_SIZE" | awk '{printf "%.1fMB", $1/1024/1024}fifi-# 3. Binary file check-if file "$file" | grep -q "binary"; then-BINARY_FILES+=("$file")-fi-# 4. Secret pattern check - REMOVED: gitleaks workflow handles this more accurately# 5. Suspicious filename patterns - whitelist approach@@ -274,6 +503,23 @@ fifidone <<< "$CHANGED_FILES"+# Content classification is batched into one Python process so release-mode+# scans over every tracked file stay fast. It fails closed if the classifier+# itself cannot run or produces an unexpected binary finding.+if [ ${#CONTENT_CHECK_FILES[@]} -gt 0 ]; then+CONTENT_SCAN_OUTPUT=""+if ! CONTENT_SCAN_OUTPUT=$(check_file_contents "$REPO_ROOT" "${CONTENT_CHECK_FILES[@]}"); then+if [ -z "$CONTENT_SCAN_OUTPUT" ]; then+BINARY_FILES+=("<content scanner> (failed without diagnostics)")+else+while IFS=$'\t' read -r binary_path reason; do+[ -z "$binary_path" ] && continue+BINARY_FILES+=("$binary_path ($reason)")+done <<< "$CONTENT_SCAN_OUTPUT"+fi+fi+fi+echo ""echo "✓ Checked $FILES_CHECKED files"echo ""@@ -342,15 +588,16 @@ fiif [ ${#BINARY_FILES[@]} -gt 0 ]; thenecho ""-echo "⚠️ BINARY FILES DETECTED - Review these carefully:"-echo " Binary files may contain sensitive data and can't be easily reviewed."+echo "❌ UNEXPECTED BINARY CONTENT - Files must be reviewable UTF-8 text:"+echo " Only the six exact, pre-existing PNG/MP3 assets are content exceptions."echo ""for violation in "${BINARY_FILES[@]}"; doecho " 🔒 $violation"-echo " → Issue: Binary file detected (contents not reviewable)"-echo " → Action: Verify this file doesn't contain sensitive data"+echo " → Issue: Binary content appeared outside an approved binary asset path"+echo " → Fix: Remove it; renaming a binary to an allowed extension is not permitted"echo ""done+TOTAL_VIOLATIONS=$((TOTAL_VIOLATIONS + ${#BINARY_FILES[@]}))fiif [ ${#SUSPICIOUS_FILES[@]} -gt 0 ]; thendiff --git a/.github/security/binary-asset-hashes.txt b/.github/security/binary-asset-hashes.txtnew file mode 100644index 0000000000..b4d7433bd6--- /dev/null+++ b/.github/security/binary-asset-hashes.txt@@ -0,0 +1,41 @@+# SHA-256 digests pinning the exact byte content of the six binary assets+# that .github/scripts/file-whitelist-check.sh allows at fixed paths.+#+# Why a hash instead of parsing PNG/MP3 structure: this checker used to+# validate PNG chunk framing and MP3 frame framing in bash/Python and reject+# anything that didn't parse as a "clean" file of that type. That caught+# trailing-data polyglots, but a container-format allowlist restricts framing+# and chunk/tag *types*, not chunk/tag *length or content* — a well-formed,+# already-allowlisted chunk type (e.g. PNG IDAT, which every real PNG needs)+# can still carry an arbitrary payload, and an ID3v2 tag's declared size is+# trusted rather than validated, so a payload can be smuggled inside either+# without ever producing a byte the parser calls invalid. Fully closing that+# would mean reimplementing a PNG/MP3 decoder. These are six exact, known,+# rarely-changing files, so pinning their content by hash is both simpler and+# strictly stronger: any byte change at all is rejected, not just changes the+# parser happens to notice.+#+# Format: standard `sha256sum` output (verifiable with `sha256sum -c` from+# the repo root). Lines starting with '#' and blank lines are ignored.+#+# To regenerate after an INTENTIONAL change to one of these assets (e.g.+# re-exporting an icon, replacing a sound), regenerate all six digests in the+# SAME PR as the byte change, so the diff is reviewed together:+#+# sha256sum \+# "docs/images/Local Search.png" \+# "docs/images/local_search_embedding_model_type.png" \+# "docs/images/local_search_paths.png" \+# "src/local_deep_research/web/static/favicon.png" \+# "src/local_deep_research/web/static/sounds/error.mp3" \+# "src/local_deep_research/web/static/sounds/success.mp3" \+# > .github/security/binary-asset-hashes.txt+#+# then restore this header comment (sha256sum only writes the hash lines).++f51f8ab8d3c99e56ef860e55c42bb69c71405493d0b62d9301263698b36856a5 docs/images/Local Search.png+9360435732e9b0d10c8f9257fbba9b7444336058b1b4ae65dbc3725a71d35d23 docs/images/local_search_embedding_model_type.png+24cfcb48c8c7ebe33969f70a1831b223d7b34fa6ddb42ff7632d323385585a21 docs/images/local_search_paths.png+c66941129d69656011f5d42c3e0e53a2cc16c1f1b7a468275ae9f9a2430e4e3e src/local_deep_research/web/static/favicon.png+38cdcafa90f190f0c2729b6a6fb7386c8c241d341aedc2d112ce3175800e0cfb src/local_deep_research/web/static/sounds/error.mp3+f04251c56111f9db7abc6e97e860cadc335bf33a0d6bfd5e0f3bac60955c58b2 src/local_deep_research/web/static/sounds/success.mp3diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yamlindex 09bb71535a..ccb9ba5cb0 100644--- a/.pre-commit-config.yaml+++ b/.pre-commit-config.yaml@@ -4,6 +4,7 @@ repos:hooks:- id: check-yamlexclude: cookiecutter-docker/.*+ - id: check-json- id: end-of-file-fixer- id: trailing-whitespace- id: check-added-large-filesdiff --git a/.pre-commit-hooks/file-whitelist-check.sh b/.pre-commit-hooks/file-whitelist-check.shindex 508a02b8b7..033afc8fa3 100755--- a/.pre-commit-hooks/file-whitelist-check.sh+++ b/.pre-commit-hooks/file-whitelist-check.sh@@ -19,6 +19,7 @@ done < "$WHITELIST_FILE"WHITELIST_VIOLATIONS=()LARGE_FILES=()+BINARY_FILES=()echo "🔍 Running file whitelist security checks..."@@ -49,6 +50,27 @@ for file in "$@"; dofidone+# Use the same content classifier as CI. Whitelisting a .py/.json pathname+# must not allow a binary merely renamed to that suffix. The classifier also+# verifies that the six explicit PNG/MP3 exceptions retain their expected+# signatures.+CONTENT_CHECKER="$REPO_ROOT/.github/scripts/file-whitelist-check.sh"+CONTENT_SCAN_OUTPUT=""+if [ ! -f "$CONTENT_CHECKER" ]; then+ BINARY_FILES+=("<content scanner> (missing $CONTENT_CHECKER)")+elif ! CONTENT_SCAN_OUTPUT=$(+ "$CONTENT_CHECKER" --content-only "$@"+); then+ if [ -z "$CONTENT_SCAN_OUTPUT" ]; then+ BINARY_FILES+=("<content scanner> (failed without diagnostics)")+ else+ while IFS=$'\t' read -r binary_path reason; do+ [ -z "$binary_path" ] && continue+ BINARY_FILES+=("$binary_path ($reason)")+ done <<< "$CONTENT_SCAN_OUTPUT"+ fi+fi+# Report violationsTOTAL_VIOLATIONS=0@@ -72,6 +94,16 @@ if [ ${#LARGE_FILES[@]} -gt 0 ]; thenTOTAL_VIOLATIONS=$((TOTAL_VIOLATIONS + ${#LARGE_FILES[@]}))fi+if [ ${#BINARY_FILES[@]} -gt 0 ]; then+ echo ""+ echo "❌ UNEXPECTED BINARY CONTENT - Files must be reviewable UTF-8 text:"+ echo " Only the six exact, pre-existing PNG/MP3 assets are content exceptions."+ for violation in "${BINARY_FILES[@]}"; do+ echo " 🔒 $violation"+ done+ TOTAL_VIOLATIONS=$((TOTAL_VIOLATIONS + ${#BINARY_FILES[@]}))+fi+if [ $TOTAL_VIOLATIONS -eq 0 ]; thenecho "✅ All file whitelist checks passed!"exit 0@@ -79,7 +111,7 @@ elseecho ""echo "💡 To fix these issues:"echo " - For text/config files: add pattern to .file-whitelist.txt (requires maintainer approval)"- echo " - For binary files: do NOT add to the repo — they permanently bloat git history"+ echo " - For binary files: do NOT rename or add them — they permanently bloat git history"echo " - For large files: use external storage"echo ""exit 1diff --git a/tests/security/test_file_whitelist_content.py b/tests/security/test_file_whitelist_content.pynew file mode 100644index 0000000000..eeea346799--- /dev/null+++ b/tests/security/test_file_whitelist_content.py@@ -0,0 +1,294 @@+# allow: no-sut-import -- guardian for repository-level shell gates+"""Regression tests for content enforcement behind the pathname whitelist.++The six binary assets allowlisted by .github/scripts/file-whitelist-check.sh+used to be validated by parsing PNG chunk / MP3 frame structure and rejecting+anything that didn't parse "cleanly". That approach was abandoned: a+container-format allowlist restricts chunk/frame *types*, not chunk/frame+*length or content*. PNG's IDAT chunk type is both unavoidable (every real+PNG needs one) and unrestricted in what it may contain, so a complete ZIP+fits inside a well-formed, correctly-CRC'd IDAT chunk placed before a+legitimate IEND -- the old structural check accepted that file outright.+MP3 has the equivalent hole: an ID3v2 header's declared tag size is trusted+and skipped without validation, so a payload can be sized into the tag+region ahead of genuine trailing audio frames. These are six exact, known,+rarely-changing files, so the fix pins their content by SHA-256 digest+instead: any byte difference at all is rejected, which is what the tests+below exercise directly.+"""++from __future__ import annotations++import struct+import subprocess+import zipfile+import zlib+from io import BytesIO+from pathlib import Path+++REPO_ROOT = Path(__file__).resolve().parents[2]+CI_CHECKER = REPO_ROOT / ".github" / "scripts" / "file-whitelist-check.sh"+PRECOMMIT_CHECKER = REPO_ROOT / ".pre-commit-hooks" / "file-whitelist-check.sh"+KNOWN_BINARY_ASSETS = (+ "docs/images/Local Search.png",+ "docs/images/local_search_embedding_model_type.png",+ "docs/images/local_search_paths.png",+ "src/local_deep_research/web/static/favicon.png",+ "src/local_deep_research/web/static/sounds/error.mp3",+ "src/local_deep_research/web/static/sounds/success.mp3",+)+++def _content_check(*paths: Path | str) -> subprocess.CompletedProcess[str]:+ return subprocess.run(+ ["bash", str(CI_CHECKER), "--content-only", *map(str, paths)],+ cwd=REPO_ROOT,+ check=False,+ capture_output=True,+ text=True,+ timeout=30,+ )+++def test_utf8_text_and_the_route_snapshot_pass_content_validation(tmp_path):+ text_file = tmp_path / "ordinary.py"+ text_file.write_text(+ "message = 'reviewable UTF-8: café'\n", encoding="utf-8"+ )++ result = _content_check(+ text_file,+ "tests/web/flask_route_table_snapshot.json",+ )++ assert result.returncode == 0, result.stdout + result.stderr+ assert result.stdout == ""+++def test_the_six_exact_binary_assets_match_their_pinned_digests():+ result = _content_check(*KNOWN_BINARY_ASSETS)++ assert result.returncode == 0, result.stdout + result.stderr+ assert result.stdout == ""+++def test_binary_magic_cannot_hide_behind_an_allowed_source_suffix(tmp_path):+ disguised = tmp_path / "looks_reviewable.py"+ disguised.write_bytes(b"\x89PNG\r\n\x1a\nnot-really-python")++ result = _content_check(disguised)++ assert result.returncode == 1+ assert str(disguised) in result.stdout+ assert "PNG image" in result.stdout+++def test_non_utf8_and_binary_control_bytes_fail_closed(tmp_path):+ non_utf8 = tmp_path / "opaque.json"+ non_utf8.write_bytes(b"reviewable-prefix\xff\xfe")+ controlled = tmp_path / "controlled.md"+ controlled.write_bytes(b"ordinary text" + (b"\x1b" * 16))++ result = _content_check(non_utf8, controlled)++ assert result.returncode == 1+ assert f"{non_utf8}\tnon-UTF-8 content" in result.stdout+ assert f"{controlled}\tdense binary control byte(s): 0x1b" in result.stdout+++def _init_repo_with_asset(+ tmp_path: Path, repo_relative_path: str, data: bytes+) -> None:+ # The checker's pinned-digest lookup keys off a path resolved relative to+ # its own `git rev-parse --show-toplevel`, so a polyglot has to live at+ # that exact relative path inside a real (if otherwise empty) git+ # repository to exercise the ALLOWED_BINARY_ASSET_PATHS / pinned-digest+ # branch instead of the generic binary-magic branch. A fresh repo like+ # this has no .github/security/binary-asset-hashes.txt of its own, so+ # every asset path in it is "no pinned digest on file" -- still a+ # rejection, which is exactly the property under test.+ subprocess.run(["git", "init", "-q"], cwd=tmp_path, check=True)+ target = tmp_path / repo_relative_path+ target.parent.mkdir(parents=True, exist_ok=True)+ target.write_bytes(data)+++def _run_content_check_in(+ tmp_path: Path, asset_path: str+) -> subprocess.CompletedProcess[str]:+ return subprocess.run(+ ["bash", str(CI_CHECKER), "--content-only", asset_path],+ cwd=tmp_path,+ check=False,+ capture_output=True,+ text=True,+ timeout=30,+ )+++def test_a_png_polyglot_with_an_appended_zip_payload_is_rejected(tmp_path):+ # Classic PNG/ZIP polyglot: a legitimate PNG followed by an appended ZIP+ # local file header. Trivially a different SHA-256 than the pinned one.+ real_png = (+ REPO_ROOT / "src/local_deep_research/web/static/favicon.png"+ ).read_bytes()+ polyglot = (+ real_png + b"PK\x03\x04\x14\x00\x00\x00\x08\x00hidden-zip-payload"+ )+ asset_path = "src/local_deep_research/web/static/favicon.png"+ _init_repo_with_asset(tmp_path, asset_path, polyglot)++ result = _run_content_check_in(tmp_path, asset_path)++ assert result.returncode == 1, result.stdout + result.stderr+ assert "does not match its pinned digest" in result.stdout+ assert "binary-asset-hashes.txt" in result.stdout+++def test_a_png_polyglot_payload_inside_an_already_allowlisted_idat_chunk_is_rejected(+ tmp_path,+):+ # This is the bypass that broke the previous (container-structure)+ # approach: unlike an unrecognized/private chunk type, IDAT is a real,+ # unavoidable, legitimately-repeatable PNG chunk type. A complete ZIP+ # fits inside a well-formed, correctly-CRC'd *IDAT* chunk placed before+ # a legitimate terminal IEND -- chunk-type allowlisting alone accepted+ # this file, while `zipfile.ZipFile()` (which scans backward for an+ # End-Of-Central-Directory signature and tolerates a trailing IEND+ # chunk like a ZIP comment) still opened it. Hash pinning has no notion+ # of "recognized chunk type" to fool -- it just compares bytes.+ real_png = (+ REPO_ROOT / "src/local_deep_research/web/static/favicon.png"+ ).read_bytes()++ offset = 8+ while True:+ chunk_length = int.from_bytes(real_png[offset : offset + 4], "big")+ chunk_type = real_png[offset + 4 : offset + 8]+ chunk_end = offset + 8 + chunk_length + 4+ if chunk_type == b"IEND":+ iend_start = offset+ break+ offset = chunk_end++ buf = BytesIO()+ with zipfile.ZipFile(buf, "w") as zf:+ zf.writestr("payload.txt", "malicious embedded payload")+ zip_bytes = buf.getvalue()+ idat_chunk_type = b"IDAT" # not a private/unrecognized type -- real PNG+ crc = zlib.crc32(idat_chunk_type + zip_bytes) & 0xFFFFFFFF+ idat_chunk = (+ struct.pack(">I", len(zip_bytes))+ + idat_chunk_type+ + zip_bytes+ + struct.pack(">I", crc)+ )+ polyglot = real_png[:iend_start] + idat_chunk + real_png[iend_start:]+ # The embedded ZIP must actually be openable -- otherwise this isn't+ # exercising the real bypass, just an inert extra IDAT chunk.+ assert zipfile.ZipFile(BytesIO(polyglot)).namelist() == ["payload.txt"]++ asset_path = "src/local_deep_research/web/static/favicon.png"+ _init_repo_with_asset(tmp_path, asset_path, polyglot)++ result = _run_content_check_in(tmp_path, asset_path)++ assert result.returncode == 1, result.stdout + result.stderr+ assert "does not match its pinned digest" in result.stdout+++def test_an_mp3_polyglot_with_an_appended_zip_payload_is_rejected(tmp_path):+ real_mp3 = (+ REPO_ROOT / "src/local_deep_research/web/static/sounds/success.mp3"+ ).read_bytes()+ polyglot = (+ real_mp3 + b"PK\x03\x04\x14\x00\x00\x00\x08\x00hidden-zip-payload"+ )+ asset_path = "src/local_deep_research/web/static/sounds/success.mp3"+ _init_repo_with_asset(tmp_path, asset_path, polyglot)++ result = _run_content_check_in(tmp_path, asset_path)++ assert result.returncode == 1, result.stdout + result.stderr+ assert "does not match its pinned digest" in result.stdout+++def test_an_mp3_polyglot_with_a_payload_sized_into_the_id3_tag_region_is_rejected(+ tmp_path,+):+ # The second bypass this rewrite is aimed at: the previous MP3 check+ # trusted the ID3v2 header's declared `tag_size` and skipped that many+ # bytes WITHOUT validating them, then only walked genuine MPEG frames+ # from there to EOF. An attacker can prepend an ID3v2 header declaring a+ # large tag, fill that declared region with an arbitrary payload, and+ # append genuine audio frames afterward -- the old check walked straight+ # past the payload to the real frames and accepted the file.+ real_mp3 = (+ REPO_ROOT / "src/local_deep_research/web/static/sounds/error.mp3"+ ).read_bytes()+ payload = b"payload-smuggled-inside-the-declared-id3-tag-region--" * 10+ tag_size = len(payload)+ size_bytes = bytes(+ [+ (tag_size >> 21) & 0x7F,+ (tag_size >> 14) & 0x7F,+ (tag_size >> 7) & 0x7F,+ tag_size & 0x7F,+ ]+ )+ id3_header = b"ID3" + bytes([0x03, 0x00, 0x00]) + size_bytes+ polyglot = id3_header + payload + real_mp3++ asset_path = "src/local_deep_research/web/static/sounds/error.mp3"+ _init_repo_with_asset(tmp_path, asset_path, polyglot)++ result = _run_content_check_in(tmp_path, asset_path)++ assert result.returncode == 1, result.stdout + result.stderr+ assert "does not match its pinned digest" in result.stdout+++def test_a_single_flipped_byte_in_a_pinned_asset_is_rejected(tmp_path):+ # The point of hash pinning: it does not matter whether a modification+ # is "structurally valid" by any container format's rules. One flipped+ # byte anywhere -- here, inside the final chunk's CRC -- is rejected.+ real_png = bytearray(+ (+ REPO_ROOT / "src/local_deep_research/web/static/favicon.png"+ ).read_bytes()+ )+ real_png[-1] ^= 0xFF+ asset_path = "src/local_deep_research/web/static/favicon.png"+ _init_repo_with_asset(tmp_path, asset_path, bytes(real_png))++ result = _run_content_check_in(tmp_path, asset_path)++ assert result.returncode == 1, result.stdout + result.stderr+ assert "does not match its pinned digest" in result.stdout+++def test_local_precommit_hook_treats_binary_content_as_fatal(tmp_path):+ # .py is intentionally a broad *pathname* allowance. This proves content+ # still decides the result after that filename stage has passed.+ disguised = tmp_path / "allowlisted_name.py"+ disguised.write_bytes(b"PK\x03\x04pretend-zip")++ result = subprocess.run(+ ["bash", str(PRECOMMIT_CHECKER), str(disguised)],+ cwd=REPO_ROOT,+ check=False,+ capture_output=True,+ text=True,+ timeout=30,+ )++ assert result.returncode == 1+ assert "UNEXPECTED BINARY CONTENT" in result.stdout+ assert "ZIP/container" in result.stdout+ assert "WHITELIST VIOLATIONS" not in result.stdout+++def test_json_syntax_is_a_precommit_invariant():+ config = (REPO_ROOT / ".pre-commit-config.yaml").read_text(encoding="utf-8")+ assert "- id: check-json\n" in configdiff --git a/tests/web/test_route_table_parity.py b/tests/web/test_route_table_parity.pyindex 7df407b7cd..3df57b01ed 100644--- a/tests/web/test_route_table_parity.py+++ b/tests/web/test_route_table_parity.py@@ -88,6 +88,25 @@ ROUTERS_DIR = REPO_ROOT / "src" / "local_deep_research" / "web" / "routers"FASTAPI_APP_FILE = (REPO_ROOT / "src" / "local_deep_research" / "web" / "fastapi_app.py")+_SNAPSHOT_KEYS = {"routes", "views"}+_SNAPSHOT_VIEW_KEYS = {+ "methods",+ "path",+ "func",+ "file",+ "auth",+ "status_codes",+ "body_keys",+}+_SNAPSHOT_HTTP_METHODS = {+ "DELETE",+ "GET",+ "HEAD",+ "OPTIONS",+ "PATCH",+ "POST",+ "PUT",+}# ---------------------------------------------------------------------------# Reviewed, intentional diff between the Flask table and the FastAPI table.@@ -1076,6 +1095,141 @@ def write_snapshot(merge_base: str) -> int:return len(views)+def _snapshot_schema_error(location: str, message: str) -> Never:+ raise ValueError(f"invalid Flask route snapshot at {location}: {message}")+++def _validate_snapshot(snapshot: object) -> dict:+ """Reject data hidden beside, or malformed inside, the route contract.++ The snapshot is an allowlisted JSON path in a public repository. Merely+ indexing ``routes`` and ``views`` would let an unrelated top-level payload+ ride along without affecting the parity assertions. Validate the complete+ shape before any consumer sees it so the file remains only the narrow,+ reviewable compatibility contract it claims to be.+ """+ if type(snapshot) is not dict:+ _snapshot_schema_error("$", "expected an object")+ if set(snapshot) != _SNAPSHOT_KEYS:+ missing = sorted(_SNAPSHOT_KEYS - set(snapshot))+ extra = sorted(set(snapshot) - _SNAPSHOT_KEYS)+ _snapshot_schema_error(+ "$", f"top-level keys differ; missing={missing}, extra={extra}"+ )++ routes = snapshot["routes"]+ if type(routes) is not list or not routes:+ _snapshot_schema_error("$.routes", "expected a non-empty list")++ route_pairs: set[tuple[str, str]] = set()+ for index, route in enumerate(routes):+ location = f"$.routes[{index}]"+ if (+ type(route) is not list+ or len(route) != 2+ or not all(type(value) is str for value in route)+ ):+ _snapshot_schema_error(+ location, "expected exactly [HTTP_METHOD, /path]"+ )+ method, path = route+ if method not in _SNAPSHOT_HTTP_METHODS:+ _snapshot_schema_error(location, f"unsupported method {method!r}")+ if not path.startswith("/"):+ _snapshot_schema_error(location, f"path is not rooted: {path!r}")+ pair = (method, path)+ if pair in route_pairs:+ _snapshot_schema_error(location, f"duplicate route {pair!r}")+ route_pairs.add(pair)++ views = snapshot["views"]+ if type(views) is not list or not views:+ _snapshot_schema_error("$.views", "expected a non-empty list")++ view_fingerprints: set[str] = set()+ for index, view in enumerate(views):+ location = f"$.views[{index}]"+ if type(view) is not dict:+ _snapshot_schema_error(location, "expected an object")+ if set(view) != _SNAPSHOT_VIEW_KEYS:+ missing = sorted(_SNAPSHOT_VIEW_KEYS - set(view))+ extra = sorted(set(view) - _SNAPSHOT_VIEW_KEYS)+ _snapshot_schema_error(+ location, f"view keys differ; missing={missing}, extra={extra}"+ )++ methods = view["methods"]+ path = view["path"]+ func = view["func"]+ source_file = view["file"]+ auth = view["auth"]+ status_codes = view["status_codes"]+ body_keys = view["body_keys"]++ if (+ type(methods) is not list+ or not methods+ or not all(+ type(method) is str and method in _SNAPSHOT_HTTP_METHODS+ for method in methods+ )+ or len(methods) != len(set(methods))+ ):+ _snapshot_schema_error(+ f"{location}.methods", "expected unique supported HTTP methods"+ )+ if type(path) is not str or not path.startswith("/"):+ _snapshot_schema_error(+ f"{location}.path", "expected a rooted route path"+ )+ if type(func) is not str or not func.isidentifier():+ _snapshot_schema_error(+ f"{location}.func", "expected a Python identifier"+ )+ if (+ type(source_file) is not str+ or not source_file.startswith("src/")+ or "\\" in source_file+ or ".." in Path(source_file).parts+ ):+ _snapshot_schema_error(+ f"{location}.file", "expected a repository-relative src/ path"+ )+ if type(auth) is not bool:+ _snapshot_schema_error(f"{location}.auth", "expected a boolean")+ if type(status_codes) is not list or not all(+ type(code) is int and 100 <= code <= 599 for code in status_codes+ ):+ _snapshot_schema_error(+ f"{location}.status_codes",+ "expected HTTP status integers from 100 through 599",+ )+ if type(body_keys) is not list or not all(+ type(key) is str for key in body_keys+ ):+ _snapshot_schema_error(+ f"{location}.body_keys", "expected a list of strings"+ )++ missing_pairs = sorted(+ (method, path)+ for method in methods+ if (method, path) not in route_pairs+ )+ if missing_pairs:+ _snapshot_schema_error(+ location,+ f"view method/path pairs missing from routes: {missing_pairs}",+ )++ fingerprint = json.dumps(view, sort_keys=True, separators=(",", ":"))+ if fingerprint in view_fingerprints:+ _snapshot_schema_error(location, "duplicate view record")+ view_fingerprints.add(fingerprint)++ return snapshot++def _read_snapshot() -> dict:"""The committed snapshot, as a mapping with `routes` and `views`.@@ -1085,7 +1239,72 @@ def _read_snapshot() -> dict:one freshness check keeps them consistent: two files could drift apartand only one of them be noticed."""- return json.loads(SNAPSHOT_FILE.read_text(encoding="utf-8"))+ return _validate_snapshot(+ json.loads(SNAPSHOT_FILE.read_text(encoding="utf-8"))+ )+++def _minimal_valid_snapshot() -> dict:+ return {+ "routes": [["GET", "/health"]],+ "views": [+ {+ "methods": ["GET"],+ "path": "/health",+ "func": "health",+ "file": "src/example.py",+ "auth": False,+ "status_codes": [200],+ "body_keys": ["status"],+ }+ ],+ }+++class TestFlaskSnapshotSchema:+ def test_committed_snapshot_has_only_the_validated_contract(self):+ snapshot = _read_snapshot()+ assert set(snapshot) == _SNAPSHOT_KEYS++ def test_rejects_an_unrelated_top_level_payload(self):+ snapshot = _minimal_valid_snapshot()+ snapshot["notes"] = {"unexpected": "unreviewed payload"}++ with pytest.raises(ValueError, match="top-level keys differ"):+ _validate_snapshot(snapshot)++ def test_rejects_extra_fields_hidden_in_a_view(self):+ snapshot = _minimal_valid_snapshot()+ snapshot["views"][0]["comment"] = "unreviewed payload"++ with pytest.raises(ValueError, match="view keys differ"):+ _validate_snapshot(snapshot)++ @pytest.mark.parametrize(+ ("field", "value", "message"),+ [+ ("methods", ["TRACE"], "supported HTTP methods"),+ ("path", "health", "rooted route path"),+ ("func", "not-a-function", "Python identifier"),+ ("file", "../outside/routes.py", "repository-relative"),+ ("auth", "false", "expected a boolean"),+ ("status_codes", [True], "HTTP status integers"),+ ("body_keys", ["status", 7], "list of strings"),+ ],+ )+ def test_rejects_malformed_view_fields(self, field, value, message):+ snapshot = _minimal_valid_snapshot()+ snapshot["views"][0][field] = value++ with pytest.raises(ValueError, match=message):+ _validate_snapshot(snapshot)++ def test_rejects_duplicate_route_records(self):+ snapshot = _minimal_valid_snapshot()+ snapshot["routes"].append(["GET", "/health"])++ with pytest.raises(ValueError, match="duplicate route"):+ _validate_snapshot(snapshot)def _load_snapshot() -> set[tuple[str, str]]: