Skip to content

~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.

fix(loaders): restore TOML and Evernote extraction (#7059)

LearningCircuit49bf08b970a1
diff --git a/.semgrep/rules/README.md b/.semgrep/rules/README.md
index ea95bd77d3..8206a7608f 100644
--- a/.semgrep/rules/README.md
+++ b/.semgrep/rules/README.md
@@ -193,7 +193,7 @@ Keep the rule enabled elsewhere; do not exclude a file or weaken the release
threshold to clear an alert. Re-review the annotation when the expression or
its input boundary changes.
-The October 2026 review identified these cases:
+Reviews in October 2026 identified these cases:
| Finding | Why the annotated use is safe | Existing verification |
| --- | --- | --- |
@@ -204,6 +204,8 @@ The October 2026 review identified these cases:
| Two apparent secrets | One is an empty API-key default; the other is the existing placeholder only used for unencrypted databases. | Configuration and authentication tests retain the surrounding behavior. |
| Two pickle calls | They raise `UnpicklingError` on rejected globals/extensions rather than loading data. | `tests/vector_stores/test_faiss_safe_load_security.py` exercises hostile payloads, extension caches, persistent IDs and legitimate docstores. |
| XML import | It imports `xml.sax.saxutils.escape` to encode text, not an XML parser. | Note-AI prompt rendering tests. |
+| Evernote `TreeBuilder` import | ElementTree's `TreeBuilder` only assembles elements. The Evernote loader's XML is read by defusedxml's parser, which refuses entity declarations, external references and any DOCTYPE with an internal subset. | `tests/document_loaders/test_evernote_extraction.py`. |
+| TOML loader's `Path(source)` | The app builds the loader only in `load_from_bytes`, from the temporary file it has just written; an upload supplies that file's bytes, not its path. No route passes a request value to `get_loader_for_path` or to the loader. | Review the callers of `load_from_bytes` and `get_loader_for_path`. `tests/document_loaders/test_toml_loader.py` loads uploads through `load_from_bytes`. |
The separate DevSkim annotation in `services/ui.js` covers its fragment-based
anchor renderer, which already adds both `noopener` and `noreferrer`.
diff --git a/changelog.d/+document-format-parsers.bugfix.md b/changelog.d/+document-format-parsers.bugfix.md
new file mode 100644
index 0000000000..bf87f26f5b
--- /dev/null
+++ b/changelog.d/+document-format-parsers.bugfix.md
@@ -0,0 +1,6 @@
+Fix advertised TOML and Evernote uploads using Python's bundled TOML parser and
+existing XML/HTML parsers. To bound the parser's time and memory, TOML files
+larger than 512 KiB, or with a key or table header of more than 32 dotted parts,
+are refused before they are parsed. An Evernote file is refused if its DOCTYPE
+has an internal subset, where entities or attribute defaults could be declared;
+the standard Evernote DOCTYPE is accepted without fetching its DTD.
diff --git a/changelog.d/+raw-config-toml-limits.security.md b/changelog.d/+raw-config-toml-limits.security.md
new file mode 100644
index 0000000000..5059aec31c
--- /dev/null
+++ b/changelog.d/+raw-config-toml-limits.security.md
@@ -0,0 +1,15 @@
+`POST /api/save_raw_config` now refuses a configuration larger than 512 KiB, or
+with a key or table header of more than 32 dotted parts, with a 400 error before
+it is parsed. One long dotted key costs Python's TOML parser time, and on a
+key/value line memory, that grows with the square of its number of parts, and
+the endpoint accepts bodies of up to 16 MB from any signed-in user, even where
+configuration writes are disabled. The check for protected keys that follows
+the parse now also runs off the event loop and builds a path only for a
+protected key: it built the path of every key and kept every protected one, so
+the keys under one long table name each repeated that name, and a configuration
+within the parsing limits could make it build over a gigabyte of paths on the
+event loop. Its 403 response lists at most 100 protected keys, each path cut to
+at most 200 characters, and sets `blocked_keys_truncated` to true when there
+are more; the configuration is refused either way. A configuration nested
+deeper than Python's recursion limit is now checked too, instead of failing
+with a 500 error.
diff --git a/src/local_deep_research/document_loaders/evernote_loader.py b/src/local_deep_research/document_loaders/evernote_loader.py
new file mode 100644
index 0000000000..e7554a0a2e
--- /dev/null
+++ b/src/local_deep_research/document_loaders/evernote_loader.py
@@ -0,0 +1,110 @@
+"""Read Evernote exports using the project's existing XML and HTML parsers."""
+
+from pathlib import Path
+from time import strptime
+from typing import Any, Iterator
+
+# nosemgrep: python.lang.security.use-defused-xml.use-defused-xml, reason: TreeBuilder only assembles elements; defusedxml's parser reads the XML
+from xml.etree.ElementTree import TreeBuilder
+
+from bs4 import BeautifulSoup
+from defusedxml.common import DTDForbidden
+from defusedxml.ElementTree import DefusedXMLParser, iterparse
+from langchain_core.document_loaders import BaseLoader
+from langchain_core.documents import Document
+
+
+class _EvernoteXMLParser(DefusedXMLParser):
+ """defusedxml's parser, refusing any DOCTYPE with an internal subset.
+
+ Evernote exports declare ``<!DOCTYPE en-export SYSTEM "...">``, and
+ defusedxml's ``forbid_dtd`` refuses every DOCTYPE, that one included.
+ This parser keeps ``forbid_dtd`` on but refuses only a DOCTYPE with an
+ internal subset (``[...]``), where a file could declare entities or
+ attribute defaults that expat adds to every matching element. Expat
+ reports the subset when it reaches the ``[``, so it is refused before
+ any of its declarations are read.
+ """
+
+ def __init__(self) -> None:
+ super().__init__(
+ target=TreeBuilder(),
+ forbid_dtd=True,
+ forbid_entities=True,
+ forbid_external=True,
+ )
+
+ def defused_start_doctype_decl(
+ self, name, sysid, pubid, has_internal_subset
+ ):
+ if has_internal_subset:
+ raise DTDForbidden(name, sysid, pubid)
+
+
+class EverNoteLoader(BaseLoader):
+ """Extract notes from an ENEX file without an undeclared parser dependency."""
+
+ def __init__(
+ self, file_path: str | Path, load_single_document: bool = True
+ ) -> None:
+ self.file_path = str(file_path)
+ self.load_single_document = load_single_document
+
+ def lazy_load(self) -> Iterator[Document]:
+ notes = self._iter_notes()
+ if self.load_single_document:
+ yield Document(
+ page_content="".join(note.page_content for note in notes),
+ metadata={"source": self.file_path},
+ )
+ else:
+ yield from notes
+
+ def _iter_notes(self) -> Iterator[Document]:
+ # Standard exports declare Evernote's doctype by its external
+ # identifier only, and ElementTree does not fetch that DTD. Any
+ # internal subset is refused (see _EvernoteXMLParser), and entity
+ # declarations and external references stay forbidden. Clearing the
+ # root after each note avoids retaining earlier notes and attachments.
+ with open(self.file_path, "rb") as stream:
+ context = iterparse(
+ stream,
+ events=("start", "end"),
+ parser=_EvernoteXMLParser(),
+ )
+ root = None
+ for event, element in context:
+ if root is None:
+ root = element
+ if event != "end" or element.tag != "note":
+ continue
+
+ content = element.findtext("content")
+ if content is not None:
+ metadata: dict[str, Any] = {"source": self.file_path}
+ for child in element:
+ if child.tag in {"content", "resource"}:
+ continue
+ if child.tag == "note-attributes":
+ for attribute in child:
+ metadata[f"note-attributes.{attribute.tag}"] = (
+ attribute.text
+ )
+ elif child.tag in {"created", "updated"}:
+ metadata[child.tag] = (
+ strptime(child.text, "%Y%m%dT%H%M%SZ")
+ if child.text
+ else None
+ )
+ else:
+ metadata[child.tag] = child.text
+
+ html = BeautifulSoup(content, "html.parser")
+ for ignored in html(["script", "style"]):
+ ignored.decompose()
+ yield Document(
+ page_content=html.get_text(" ", strip=True),
+ metadata=metadata,
+ )
+ element.clear()
+ root.clear()
diff --git a/src/local_deep_research/document_loaders/loader_registry.py b/src/local_deep_research/document_loaders/loader_registry.py
index e9cc61b4c2..d31fc23ba6 100644
--- a/src/local_deep_research/document_loaders/loader_registry.py
+++ b/src/local_deep_research/document_loaders/loader_registry.py
@@ -11,11 +11,9 @@ from pathlib import Path
from typing import Optional
from langchain_community.document_loaders import (
- EverNoteLoader,
MHTMLLoader,
NotebookLoader,
PyPDFLoader,
- TomlLoader,
UnstructuredEmailLoader,
UnstructuredExcelLoader,
UnstructuredHTMLLoader,
@@ -84,6 +82,8 @@ except ImportError:
# Import our custom loaders
from .json_loader import SimpleJSONLoader
from .text_encoding import EncodingAwareCSVLoader, EncodingAwareTextLoader
+from .evernote_loader import EverNoteLoader
+from .toml_loader import TOMLLoader
from .xls_loader import XLSLoader
from .yaml_loader import YAMLLoader
@@ -323,7 +323,7 @@ LOADER_REGISTRY[".enex"] = {
# TOML config files
LOADER_REGISTRY[".toml"] = {
- "loader_class": TomlLoader,
+ "loader_class": TOMLLoader,
"loader_kwargs": {},
}
diff --git a/src/local_deep_research/document_loaders/toml_loader.py b/src/local_deep_research/document_loaders/toml_loader.py
new file mode 100644
index 0000000000..e4aa42eaf3
--- /dev/null
+++ b/src/local_deep_research/document_loaders/toml_loader.py
@@ -0,0 +1,50 @@
+"""Load TOML with Python's bundled parser, within the shared TOML limits."""
+
+import json
+from pathlib import Path
+from typing import Iterator
+
+from langchain_core.document_loaders import BaseLoader
+from langchain_core.documents import Document
+
+from ..security import toml_limits
+
+
+def _read_limited_text(path: Path) -> str:
+ """Return *path*'s text without reading past the TOML size limit."""
+ with path.open("rb") as stream:
+ content = stream.read(toml_limits.MAX_TOML_BYTES + 1)
+ # Checked before decoding, so a read cut off inside a multi-byte
+ # character is reported as too large rather than as invalid UTF-8.
+ toml_limits.check_toml_size(len(content))
+ return content.decode()
+
+
+class TOMLLoader(BaseLoader):
+ """Load a TOML file or directory without requiring the tomli backport.
+
+ Each file is refused with TOMLLimitError, before tomllib parses it, when
+ it is larger than MAX_TOML_BYTES or has a key or table header of more
+ than MAX_TOML_KEY_PARTS dotted parts (see security.toml_limits).
+ """
+
+ def __init__(self, source: str | Path):
+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: load_from_bytes passes the temp file it wrote; no route passes a request path
+ self.source = Path(source)
+
+ def lazy_load(self) -> Iterator[Document]:
+ if self.source.is_file() and self.source.suffix.lower() == ".toml":
+ files = [self.source]
+ elif self.source.is_dir():
+ files = sorted(self.source.rglob("*.toml"))
+ else:
+ raise ValueError("Invalid source path or file type")
+
+ for file_path in files:
+ data = toml_limits.loads_toml_within_limits(
+ _read_limited_text(file_path)
+ )
+ yield Document(
+ page_content=json.dumps(data, ensure_ascii=False, default=str),
+ metadata={"source": str(file_path)},
+ )
diff --git a/src/local_deep_research/security/toml_limits.py b/src/local_deep_research/security/toml_limits.py
new file mode 100644
index 0000000000..eb5fbe7cc4
--- /dev/null
+++ b/src/local_deep_research/security/toml_limits.py
@@ -0,0 +1,113 @@
+"""Limits checked before tomllib parses TOML that a user supplied.
+
+tomllib is pure Python. It rebuilds a key's tuple for every part and, on a
+dotted key/value line, also builds and keeps every prefix of the key, so
+one long key costs time (and, on a key/value line, memory) that grows with
+the square of its length. Uploaded TOML documents and the raw configuration
+endpoint both parse through ``loads_toml_within_limits``.
+"""
+
+import re
+import tomllib
+from itertools import islice
+from typing import Any
+
+# Largest TOML document parsed, in UTF-8 bytes. TOML files are mostly
+# configuration: a full pyproject.toml is about 30 KB, and gitleaks' rule
+# set, one of the larger common ones, about 100 KB, so this leaves fivefold
+# headroom. tomllib is pure Python, and hostile but valid documents were
+# measured holding several hundred bytes of parser memory per input byte;
+# neither the general upload limit (3 GB by default) nor the default 16 MB
+# JSON body limit bounds that.
+MAX_TOML_BYTES = 512 * 1024
+
+# Most dotted parts allowed in one key or table header ("a.b.c" has three).
+# The deepest key in 252 sampled TOML files had five parts. Under this cap
+# the total work stays proportional to the document size. A number such as
+# 1.5 also scans as a two-part run, so keep this at least 2.
+MAX_TOML_KEY_PARTS = 32
+
+# One key part: bare, or a one-line basic or literal string that ends
+# where tomllib ends it.
+_KEY_PART = (
+ r"(?:[A-Za-z0-9_-]++"
+ r"|\x22(?:[^\x22\\\n]++|\\[^\n])*+\x22"
+ r"|\x27[^\x27\n]*+\x27)"
+)
+_KEY_PART_RE = re.compile(_KEY_PART)
+
+# Some alternative matches at every position, so the tokens cover the text
+# in order and, up to where tomllib would reject the document, string and
+# comment contents are skipped exactly where tomllib skips them. A "key"
+# token is a run of dot-separated key parts.
+_TOKEN_RE = re.compile(
+ rf"""
+ (?P<string>
+ \x22{{3}} (?: [^\x22\\]++ | \\[\s\S] | \x22(?!\x22{{2}}) )*+ \x22{{3,5}}
+ | \x27{{3}} (?: [^\x27]++ | \x27(?!\x27{{2}}) )*+ \x27{{3,5}}
+ )
+ | (?P<key>
+ (?!\x22{{3}}|\x27{{3}})
+ {_KEY_PART} (?: [ \t]*+ \. [ \t]*+ {_KEY_PART} )*+
+ )
+ | (?P<comment> \# [^\n]*+ )
+ | (?P<other> [^A-Za-z0-9_\-\x22\x27\#]++ )
+ | (?P<unterminated> [\x22\x27] )
+ """,
+ re.VERBOSE,
+)
+
+
+class TOMLLimitError(ValueError):
+ """TOML input exceeds a limit that is checked before tomllib runs."""
+
+
+def _has_overlong_key(text: str, max_parts: int) -> bool:
+ """Return whether a key or table header has more than *max_parts* parts.
+
+ The scan stops at an unterminated string, where tomllib rejects the
+ document, so it stays linear in the length of *text*.
+ """
+ for token in _TOKEN_RE.finditer(text):
+ kind = token.lastgroup
+ if kind == "unterminated":
+ return False
+ start, end = token.span()
+ if kind == "key" and text.find(".", start, end) != -1:
+ parts = _KEY_PART_RE.finditer(text, start, end)
+ if sum(1 for _ in islice(parts, max_parts + 1)) > max_parts:
+ return True
+ return False
+
+
+def check_toml_size(size: int) -> None:
+ """Raise TOMLLimitError when a *size*-byte document is over the limit."""
+ if size > MAX_TOML_BYTES:
+ raise TOMLLimitError(
+ f"TOML document is larger than {MAX_TOML_BYTES} bytes"
+ )
+
+
+def loads_toml_within_limits(text: str) -> dict[str, Any]:
+ """Parse *text* with tomllib unless it exceeds the limits.
+
+ Raises TOMLLimitError, before tomllib runs, when the UTF-8 form of
+ *text* is larger than MAX_TOML_BYTES or a key or table header has more
+ than MAX_TOML_KEY_PARTS dotted parts, and TypeError when *text* is not
+ a string. Otherwise it returns or raises what
+ tomllib.loads does, such as TOMLDecodeError for invalid TOML.
+ """
+ if not isinstance(text, str):
+ raise TypeError(f"Expected str object, not '{type(text).__qualname__}'")
+ # A character takes at least one UTF-8 byte, so the length check refuses
+ # most oversized text before its encoded size is measured.
+ check_toml_size(len(text))
+ check_toml_size(len(text.encode("utf-8", "surrogatepass")))
+ # tomllib.loads folds CRLF before it parses; scan that same text.
+ text = text.replace("\r\n", "\n")
+ if _has_overlong_key(text, MAX_TOML_KEY_PARTS):
+ raise TOMLLimitError(
+ "TOML key or table header has more than "
+ f"{MAX_TOML_KEY_PARTS} dotted parts"
+ )
+ return tomllib.loads(text)
diff --git a/src/local_deep_research/web/routers/research.py b/src/local_deep_research/web/routers/research.py
index 2d561d4a0c..c8d6a6fd29 100644
--- a/src/local_deep_research/web/routers/research.py
+++ b/src/local_deep_research/web/routers/research.py
@@ -2542,6 +2542,93 @@ def open_file_location(
)
+# save_raw_config refuses a configuration with any key whose lowercased name
+# contains one of these: such keys name a Python module or class to import.
+_BLOCKED_KEY_PATTERNS = ("module_path", "class_name", "module", "class")
+
+# Its refusal lists at most this many protected keys, each path cut to at
+# most this many characters, so the response and its log line stay small
+# however many protected keys a configuration has and however long the names
+# above them are. One protected key is enough to refuse the save, so a cut
+# list changes only what is listed.
+_MAX_REPORTED_BLOCKED_KEYS = 100
+_MAX_BLOCKED_KEY_PATH_CHARS = 200
+
+
+def _blocked_key_path(parts: list[str | int]) -> str:
+ """Render *parts* as ``a.b[0].c``, cut to _MAX_BLOCKED_KEY_PATH_CHARS.
+
+ Names join with dots and array indexes go in brackets, as
+ save_raw_config has always reported them. Rendering stops once the
+ path passes the limit, so a long name is never copied whole, and a cut
+ path ends with an ellipsis.
+ """
+ limit = _MAX_BLOCKED_KEY_PATH_CHARS
+ pieces: list[str] = []
+ size = 0
+ for part in parts:
+ if isinstance(part, int):
+ # Not f"[{part}]": Semgrep's sql-string-concatenation rule
+ # reports that assignment as SQL built from input.
+ piece = "".join(("[", str(part), "]"))
+ elif size:
+ piece = "." + part[: limit + 1]
+ else:
+ piece = part[: limit + 1]
+ pieces.append(piece)
+ size += len(piece)
+ if size > limit:
+ break
+ path = "".join(pieces)
+ if len(path) > limit:
+ path = path[: limit - 1] + "\N{HORIZONTAL ELLIPSIS}"
+ return path
+
+
+def _find_blocked_keys(config: dict) -> tuple[list[str], bool]:
+ """Return the paths of the protected keys in a parsed configuration.
+
+ Every table, inline table and array is searched, depth first in the
+ parsed configuration's key order, for a key whose lowercased name
+ contains one of _BLOCKED_KEY_PATTERNS. The second value is True when
+ there are more than _MAX_REPORTED_BLOCKED_KEYS of them: the walk stops
+ at the first one past that limit, so the list holds the first
+ _MAX_REPORTED_BLOCKED_KEYS it found.
+
+ A path is rendered only for a protected key, by _blocked_key_path, so
+ the walk's work does not grow with the length of the names above one.
+ The walk keeps an explicit stack instead of recursing: a dotted key in
+ an inline table nests up to 32 tables for a few frames of tomllib's own
+ recursion, so a configuration within the parsing limits can nest deeper
+ than Python's recursion limit.
+ """
+ found: list[str] = []
+ parts: list[str | int] = []
+ stack = [iter(config.items())]
+ while stack:
+ entry = next(stack[-1], None)
+ if entry is None:
+ stack.pop()
+ if stack:
+ parts.pop()
+ continue
+ name, value = entry
+ parts.append(name)
+ if isinstance(name, str):
+ lowered = name.lower()
+ if any(pattern in lowered for pattern in _BLOCKED_KEY_PATTERNS):
+ if len(found) == _MAX_REPORTED_BLOCKED_KEYS:
+ return found, True
+ found.append(_blocked_key_path(parts))
+ if isinstance(value, dict):
+ stack.append(iter(value.items()))
+ elif isinstance(value, list):
+ stack.append(enumerate(value))
+ else:
+ parts.pop()
+ return found, False
+
+
@router.post("/api/save_raw_config")
async def save_raw_config(
request: Request, username: Annotated[str, Depends(require_auth)]
@@ -2559,30 +2646,46 @@ async def save_raw_config(
)
# Security: Parse and validate the TOML to block dangerous keys
- try:
- import tomllib
- except ImportError:
- import tomli as tomllib # type: ignore[no-redef]
+ from ...security import toml_limits
try:
- # Offloaded: tomllib is PURE PYTHON, and this body is capped at 16 MB
- # (fastapi_app.py's body-size limit, whose own note budgets "roughly
- # 60 ms" — a figure calibrated for C-speed json.loads). Measured here,
- # adversarial-but-valid TOML parses at roughly 100 ms/MB, so a 16 MB
- # document is ~5.5 s of straight-line CPU. On the event loop, with the
- # single-worker deployment this ships as, that stalls EVERY request for
- # the duration, repeatably, for any authenticated user.
+ # Bounded: the body may be 16 MB (fastapi_app.py's default JSON body
+ # limit), and tomllib's cost for one long dotted key grows with the
+ # square of its parts. loads_toml_within_limits refuses text over
+ # 512 KiB, or with a key or table header of more than 32 dotted parts,
+ # before tomllib runs (security/toml_limits.py).
#
- # asyncio.to_thread rather than run_db_sync: this opens no DB session,
- # and run_db_sync's docstring says to prefer to_thread for purely
- # CPU-bound work. The GIL is released periodically during the parse, so
- # the loop interleaves instead of stopping dead.
+ # Offloaded: within those limits the scan and the parse are still
+ # pure-Python CPU work. On the event loop, with the single-worker
+ # deployment this ships as, that would stall EVERY request for the
+ # duration, for any authenticated user. asyncio.to_thread rather than
+ # run_db_sync: this opens no DB session, and run_db_sync's docstring
+ # says to prefer to_thread for purely CPU-bound work. The GIL is
+ # released periodically during the parse, so the loop interleaves
+ # instead of stopping dead.
#
- # Note this runs BEFORE the system.allow_config_write gate (enforced
- # inside write_file_verified below), so it is reachable even on
- # deployments that have config writing turned off. Offloading is what
- # makes that ordering safe; it is not an argument for keeping it.
- parsed_config = await asyncio.to_thread(tomllib.loads, raw_config)
+ # Note this, and the protected-key walk below, run BEFORE the
+ # system.allow_config_write gate (enforced inside write_file_verified
+ # below), so they are reachable even on deployments that have config
+ # writing turned off. Offloading and the limits are what make that
+ # ordering safe; they are not an argument for keeping it.
+ parsed_config = await asyncio.to_thread(
+ toml_limits.loads_toml_within_limits, raw_config
+ )
+ except toml_limits.TOMLLimitError:
+ logger.warning("Refused TOML configuration over the parsing limits")
+ return JSONResponse(
+ {
+ "success": False,
+ "error": (
+ "Configuration exceeds the parsing limits: at most "
+ f"{toml_limits.MAX_TOML_BYTES // 1024} KiB, and at most "
+ f"{toml_limits.MAX_TOML_KEY_PARTS} dotted parts in any "
+ "key or table header."
+ ),
+ },
+ status_code=400,
+ )
except Exception:
logger.warning("Invalid TOML configuration")
# Don't expose internal exception details to users (CWE-209)
@@ -2594,39 +2697,26 @@ async def save_raw_config(
status_code=400,
)
- # Security: Check for dangerous keys that could enable code execution
- # These patterns match keys used for dynamic module imports
- BLOCKED_KEY_PATTERNS = ["module_path", "class_name", "module", "class"]
-
- def find_blocked_keys(obj, path=""):
- """Recursively find any blocked keys in the config."""
- blocked = []
- if isinstance(obj, dict):
- for key, value in obj.items():
- current_path = f"{path}.{key}" if path else key
- key_lower = key.lower()
- for pattern in BLOCKED_KEY_PATTERNS:
- if pattern in key_lower:
- blocked.append(current_path)
- break
- # Recurse into nested dicts
- blocked.extend(find_blocked_keys(value, current_path))
- elif isinstance(obj, list):
- for i, item in enumerate(obj):
- blocked.extend(find_blocked_keys(item, f"{path}[{i}]"))
- return blocked
-
- blocked_keys = find_blocked_keys(parsed_config)
- if blocked_keys:
+ # Security: Check for dangerous keys that could enable code execution.
+ # Offloaded like the parse: the walk is pure-Python work that grows with
+ # the size of the parsed configuration.
+ blocked_keys, more_blocked_keys = await asyncio.to_thread(
+ _find_blocked_keys, parsed_config
+ )
+ if blocked_keys or more_blocked_keys:
logger.warning(
"Security: Blocked attempt to write config with dangerous keys: {}",
_log_value_preview(blocked_keys),
)
+ error = "Configuration contains protected keys that cannot be modified"
+ if more_blocked_keys:
+ error += f"; only the first {len(blocked_keys)} are listed"
return JSONResponse(
{
"success": False,
- "error": "Configuration contains protected keys that cannot be modified",
+ "error": error,
"blocked_keys": blocked_keys,
+ "blocked_keys_truncated": more_blocked_keys,
},
status_code=403,
)
diff --git a/tests/document_loaders/test_evernote_extraction.py b/tests/document_loaders/test_evernote_extraction.py
new file mode 100644
index 0000000000..e02f83152e
--- /dev/null
+++ b/tests/document_loaders/test_evernote_extraction.py
@@ -0,0 +1,152 @@
+"""Evernote exports work with the declared application dependencies."""
+
+import pytest
+from defusedxml.common import DTDForbidden
+
+from local_deep_research.document_loaders import load_from_bytes
+
+
+def test_upload_extracts_each_note_and_preserves_metadata():
+ export = """<?xml version="1.0" encoding="UTF-8"?>
+<en-export>
+ <note>
+ <title>First note</title>
+ <content><![CDATA[<en-note><p>Hello <strong>世界</strong></p></en-note>]]></content>
+ <created>20240305T134500Z</created>
+ </note>
+ <note>
+ <title>Second note</title>
+ <content><![CDATA[<en-note><p>Another note</p></en-note>]]></content>
+ <created>20240306T134500Z</created>
+ </note>
+</en-export>"""
+ documents = load_from_bytes(export.encode(), ".enex", "notes.enex")
+ assert len(documents) == 2
+ assert [doc.metadata["title"] for doc in documents] == [
+ "First note",
+ "Second note",
+ ]
+ assert "世界" in documents[0].page_content
+ assert "<strong>" not in documents[0].page_content
+ assert "Another note" in documents[1].page_content
+ assert all(doc.metadata["created"] for doc in documents)
+ assert all(
+ doc.metadata["original_filename"] == "notes.enex" for doc in documents
+ )
+
+
+ "export",
+ [
+ pytest.param(
+ b"""<?xml version="1.0"?>
+<!DOCTYPE en-export [<!ATTLIST note added CDATA "x">]>
+<en-export><note><content>t</content></note></en-export>""",
+ id="attribute-default",
+ ),
+ pytest.param(
+ b"""<?xml version="1.0"?>
+<!DOCTYPE en-export SYSTEM "http://xml.evernote.com/pub/evernote-export3.dtd"
+ [<!ATTLIST note added CDATA "x">]>
+<en-export><note><content>t</content></note></en-export>""",
+ id="standard-identifier-with-subset",
+ ),
+ pytest.param(
+ b"""<?xml version="1.0"?>
+<!DOCTYPE en-export []>
+<en-export><note><content>t</content></note></en-export>""",
+ id="empty-subset",
+ ),
+ pytest.param(
+ b"""<?xml version="1.0"?>
+<!DOCTYPE en-export [<!ENTITY secret SYSTEM "file:///etc/passwd">]>
+<en-export><note><content>&secret;</content></note></en-export>""",
+ id="external-entity",
+ ),
+ pytest.param(
+ b"""<?xml version="1.0"?>
+<!DOCTYPE en-export [<!ENTITY repeated "untrusted expansion">]>
+<en-export><note><content>&repeated;</content></note></en-export>""",
+ id="internal-entity",
+ ),
+ ],
+)
+def test_evernote_refuses_any_internal_dtd_subset(export):
+ # An internal subset can declare entities, or attribute defaults that
+ # expat would add to every matching element, so none is accepted.
+ with pytest.raises(DTDForbidden):
+ load_from_bytes(export, ".enex", "untrusted.enex")
+
+
+def test_evernote_loads_a_standard_export_with_exact_note_text(monkeypatch):
+ def unexpected_network(*args, **kwargs):
+ raise AssertionError("ENEX parsing must not fetch its doctype")
+
+ monkeypatch.setattr("socket.create_connection", unexpected_network)
+ monkeypatch.setattr("urllib.request.urlopen", unexpected_network)
+ # The header lines follow Evernote's published sample export, and each
+ # note's ENML carries its own declarations inside the CDATA section.
+ export = """<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE en-export SYSTEM "http://xml.evernote.com/pub/evernote-export3.dtd">
+<en-export export-date="20130730T205637Z" application="Evernote" version="Evernote Mac">
+<note><title>First note</title><content><![CDATA[<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">
+<en-note><div>Hello <b>world</b></div></en-note>]]></content>
+<created>20130730T205204Z</created></note>
+<note><title>Second note</title><content><![CDATA[<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">
+<en-note><div>Second body</div></en-note>]]></content>
+<created>20130730T205300Z</created></note>
+</en-export>"""
+ documents = load_from_bytes(export.encode(), ".enex", "standard.enex")
+ assert [doc.page_content for doc in documents] == [
+ "Hello world",
+ "Second body",
+ ]
+ assert [doc.metadata["title"] for doc in documents] == [
+ "First note",
+ "Second note",
+ ]
+
+
+ "doctype_url",
+ [
+ "http://xml.evernote.com/pub/evernote-export3.dtd",
+ "https://xml.evernote.com/pub/evernote-export3.dtd",
+ "http://xml.evernote.com/pub/evernote-export4.dtd",
+ "https://xml.evernote.com/pub/evernote-export4.dtd",
+ ],
+)
+def test_evernote_accepts_standard_doctype_without_fetching_it(
+ doctype_url, monkeypatch
+):
+ def unexpected_network(*args, **kwargs):
+ raise AssertionError("ENEX parsing must not fetch its doctype")
+
+ monkeypatch.setattr("socket.create_connection", unexpected_network)
+ monkeypatch.setattr("urllib.request.urlopen", unexpected_network)
+ export = f'''<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE en-export SYSTEM "{doctype_url}">
+<en-export><note><title>Standard export</title>
+<content><![CDATA[<en-note><p>Exported note text</p></en-note>]]></content>
+</note></en-export>'''
+ documents = load_from_bytes(export.encode(), ".enex", "standard.enex")
+ assert len(documents) == 1
+ assert documents[0].page_content == "Exported note text"
+ assert documents[0].metadata["title"] == "Standard export"
+
+
+def test_evernote_keeps_note_attributes_without_script_text():
+ export = b"""<en-export><note>
+<title>A note</title>
+<note-attributes><source-url>https://example.org/item</source-url></note-attributes>
+<content><![CDATA[<en-note><p>Visible text</p><script>hidden()</script>
+<style>secret { display: none }</style></en-note>]]></content>
+</note></en-export>"""
+ documents = load_from_bytes(export, ".enex", "safe.enex")
+ assert len(documents) == 1
+ assert documents[0].page_content == "Visible text"
+ assert documents[0].metadata["note-attributes.source-url"] == (
+ "https://example.org/item"
+ )
diff --git a/tests/document_loaders/test_loader_hostile_input.py b/tests/document_loaders/test_loader_hostile_input.py
index 6cee9a8108..03d5412172 100644
--- a/tests/document_loaders/test_loader_hostile_input.py
+++ b/tests/document_loaders/test_loader_hostile_input.py
@@ -1019,8 +1019,7 @@ class TestAdvertisedFormatsHaveTheirParser:
@pytest.mark.parametrize(
("extension", "content"),
- # .toml and .enex are absent from VALID_BY_EXTENSION on purpose:
- # both are broken today and are pinned by the strict xfails below.
+ # TOML and ENEX have dedicated extraction controls below.
sorted(VALID_BY_EXTENSION.items()),
)
def test_no_advertised_format_fails_on_a_missing_parser_dependency(
@@ -1054,39 +1053,12 @@ class TestAdvertisedFormatsHaveTheirParser:
assert documents
assert "hello" in documents[0].page_content.lower()
- @pytest.mark.xfail(
- strict=True,
- reason=(
- "DEFECT: '.toml' is registered unconditionally in "
- "LOADER_REGISTRY, but langchain's TomlLoader does "
- "'import tomli' inside lazy_load(). 'tomli' is not a project "
- "dependency (pyproject pins 'toml~=0.10'; tomli appears in "
- "pdm.lock only as a python_version<'3.11' marker, and "
- "requires-python is '>=3.12,<3.15'), so every .toml upload "
- "fails with ModuleNotFoundError while the UI is told .toml is "
- "supported. Fix: gate the entry on "
- "_module_available('tomli') like the other formats, or use "
- "stdlib tomllib."
- ),
- )
def test_advertised_toml_can_actually_be_parsed(self):
assert ".toml" in get_supported_extensions()
documents = load_from_bytes(b'a = "hello toml"\n', ".toml", "g.toml")
assert documents
assert "hello toml" in documents[0].page_content
- @pytest.mark.xfail(
- strict=True,
- reason=(
- "DEFECT: '.enex' is registered unconditionally in "
- "LOADER_REGISTRY, but EverNoteLoader imports 'html2text' at "
- "load() time and html2text is neither in pyproject nor in "
- "pdm.lock. Every .enex upload fails with ImportError while the "
- "UI is told .enex is supported -- same class as the ODT bug "
- "(#4414) the capability flags were added for. Fix: gate the "
- "entry on _module_available('html2text')."
- ),
- )
def test_advertised_enex_can_actually_be_parsed(self):
assert ".enex" in get_supported_extensions()
enex = (
diff --git a/tests/document_loaders/test_loader_registry_coverage.py b/tests/document_loaders/test_loader_registry_coverage.py
index 7399bf765f..b335b51248 100644
--- a/tests/document_loaders/test_loader_registry_coverage.py
+++ b/tests/document_loaders/test_loader_registry_coverage.py
@@ -77,7 +77,7 @@ class TestRegistrySpecificLoaderClasses:
(".yml", "YAMLLoader"),
(".ipynb", "NotebookLoader"),
(".enex", "EverNoteLoader"),
- (".toml", "TomlLoader"),
+ (".toml", "TOMLLoader"),
(".mhtml", "MHTMLLoader"),
(".mht", "MHTMLLoader"),
],
diff --git a/tests/document_loaders/test_toml_loader.py b/tests/document_loaders/test_toml_loader.py
new file mode 100644
index 0000000000..ce14aa92bd
--- /dev/null
+++ b/tests/document_loaders/test_toml_loader.py
@@ -0,0 +1,238 @@
+"""Real extraction controls for the bundled TOML parser."""
+
+import builtins
+import json
+import tomllib
+from pathlib import Path
+
+import pytest
+
+from local_deep_research.document_loaders import (
+ extract_text_from_bytes,
+ load_from_bytes,
+)
+from local_deep_research.document_loaders.loader_registry import (
+ get_loader_for_path,
+)
+from local_deep_research.document_loaders.toml_loader import TOMLLoader
+from local_deep_research.security import toml_limits
+
+# One part more than MAX_TOML_KEY_PARTS (32).
+_OVERLONG_KEY = ".".join(["k"] * 33)
+
+
+def _forbid_parsing(monkeypatch):
+ """Fail if tomllib runs, so a refusal must happen before parsing."""
+
+ def parse_attempted(*args, **kwargs):
+ raise AssertionError("tomllib ran on input the loader must refuse")
+
+ monkeypatch.setattr(tomllib, "load", parse_attempted)
+ monkeypatch.setattr(tomllib, "loads", parse_attempted)
+
+
+def test_upload_reads_nested_values_and_unicode_without_tomli(monkeypatch):
+ original_import = builtins.__import__
+
+ def without_backport(name, *args, **kwargs):
+ if name == "tomli":
+ raise ModuleNotFoundError("tomli is intentionally unavailable")
+ return original_import(name, *args, **kwargs)
+
+ monkeypatch.setattr(builtins, "__import__", without_backport)
+ documents = load_from_bytes(
+ '[project]\nname = "研究"\nactive = true\nports = [80, 443]\n'.encode(),
+ ".toml",
+ "project.toml",
+ )
+ assert len(documents) == 1
+ assert json.loads(documents[0].page_content) == {
+ "project": {"name": "研究", "active": True, "ports": [80, 443]}
+ }
+ assert documents[0].metadata["original_filename"] == "project.toml"
+
+
+def test_local_file_reads_toml_dates(tmp_path):
+ path = tmp_path / "dates.toml"
+ path.write_text("day = 2026-10-02\nclock = 12:34:56\n", encoding="utf-8")
+ documents = get_loader_for_path(path).load()
+ assert json.loads(documents[0].page_content) == {
+ "day": "2026-10-02",
+ "clock": "12:34:56",
+ }
+ assert documents[0].metadata["source"] == str(path)
+
+
+def test_directory_loads_each_nested_toml_file(tmp_path):
+ (tmp_path / "a.toml").write_text('name = "first"\n')
+ nested = tmp_path / "nested"
+ nested.mkdir()
+ (nested / "b.toml").write_text('name = "second"\n')
+ (nested / "ignored.txt").write_text("not TOML")
+ documents = TOMLLoader(tmp_path).load()
+ assert [json.loads(doc.page_content)["name"] for doc in documents] == [
+ "first",
+ "second",
+ ]
+
+
+def test_malformed_toml_does_not_produce_a_document(tmp_path):
+ path = tmp_path / "invalid.toml"
+ path.write_text("name = [\n")
+ with pytest.raises(tomllib.TOMLDecodeError):
+ TOMLLoader(path).load()
+
+
[email protected]("filename", ["missing.toml", "wrong.txt"])
+def test_invalid_source_is_rejected(tmp_path, filename):
+ path = tmp_path / filename
+ if path.suffix == ".txt":
+ path.write_text("not TOML")
+ with pytest.raises(ValueError, match="Invalid source path or file type"):
+ TOMLLoader(path).load()
+
+
+def test_default_limits_accept_this_repository_pyproject():
+ path = Path(__file__).resolve().parents[2] / "pyproject.toml"
+ documents = TOMLLoader(path).load()
+ data = json.loads(documents[0].page_content)
+ assert data["project"]["name"] == "local-deep-research"
+
+
+def test_size_limit_admits_its_own_size_and_refuses_one_byte_more(
+ tmp_path, monkeypatch
+):
+ monkeypatch.setattr(toml_limits, "MAX_TOML_BYTES", 32)
+ at_limit = tmp_path / "at_limit.toml"
+ at_limit.write_bytes(b'name = "' + b"x" * 22 + b'"\n')
+ assert at_limit.stat().st_size == 32
+ documents = TOMLLoader(at_limit).load()
+ assert json.loads(documents[0].page_content) == {"name": "x" * 22}
+
+ over_limit = tmp_path / "over_limit.toml"
+ over_limit.write_bytes(b'name = "' + b"x" * 23 + b'"\n')
+ _forbid_parsing(monkeypatch)
+ with pytest.raises(toml_limits.TOMLLimitError, match="larger than 32"):
+ TOMLLoader(over_limit).load()
+
+
+ "document",
+ [
+ pytest.param(f"[{_OVERLONG_KEY}]\n", id="table-header"),
+ pytest.param(f"[[{_OVERLONG_KEY}]]\n", id="array-of-tables-header"),
+ pytest.param(f"{_OVERLONG_KEY} = 1\n", id="dotted-key"),
+ pytest.param(f"x = {{ {_OVERLONG_KEY} = 1 }}\n", id="inline-table"),
+ pytest.param(" . ".join(["k"] * 33) + " = 1\n", id="spaced-dots"),
+ pytest.param(
+ ".".join(['"k k"', "'k.k'", "k"] * 11) + " = 1\n",
+ id="quoted-parts",
+ ),
+ pytest.param(
+ f'x = ["""\n""", {{ {_OVERLONG_KEY} = 1 }}]\n',
+ id="after-a-multiline-string-closes",
+ ),
+ pytest.param(
+ f"x = [\n # 'quote\n {{ {_OVERLONG_KEY} = 1 }},\n]\n",
+ id="inside-a-multiline-array",
+ ),
+ pytest.param(f"x = 1\r\n{_OVERLONG_KEY} = 1\r\n", id="crlf"),
+ # Each case below is skipped by a scanner that takes the quotes or
+ # backslashes before the key as an unterminated string.
+ pytest.param(
+ f'# """\n{_OVERLONG_KEY} = 1\n', id="after-quotes-in-a-comment"
+ ),
+ pytest.param(
+ f'x = "a\\"b"\n{_OVERLONG_KEY} = 1\n', id="after-an-escaped-quote"
+ ),
+ pytest.param(
+ f'x = "a\\\\"\n{_OVERLONG_KEY} = 1\n',
+ id="after-an-escaped-backslash",
+ ),
+ pytest.param(
+ f'x = """a\\"""b"""\n{_OVERLONG_KEY} = 1\n',
+ id="after-a-multiline-escaped-quote",
+ ),
+ pytest.param(
+ f'x = """a\\\\"""\n{_OVERLONG_KEY} = 1\n',
+ id="after-a-multiline-escaped-backslash",
+ ),
+ pytest.param(
+ f"x = 'a\\'\n{_OVERLONG_KEY} = 1\n", id="after-a-literal-backslash"
+ ),
+ ],
+)
+def test_overlong_key_is_refused_before_parsing(
+ tmp_path, monkeypatch, document
+):
+ path = tmp_path / "deep.toml"
+ path.write_bytes(document.encode())
+ _forbid_parsing(monkeypatch)
+ with pytest.raises(
+ toml_limits.TOMLLimitError, match="more than 32 dotted parts"
+ ):
+ TOMLLoader(path).load()
+
+
[email protected]("opening", ['"', '"""', "'", "'''"])
+def test_scan_stops_where_tomllib_rejects_an_unterminated_string(
+ tmp_path, opening
+):
+ path = tmp_path / "unterminated.toml"
+ path.write_bytes(f"x = {opening}open\n{_OVERLONG_KEY} = 1\n".encode())
+ with pytest.raises(tomllib.TOMLDecodeError):
+ TOMLLoader(path).load()
+
+
+def _nested(parts, leaf):
+ for part in reversed(parts):
+ leaf = {part: leaf}
+ return leaf
+
+
+ ("document", "expected"),
+ [
+ pytest.param(
+ ".".join(["k"] * 32) + " = 1\n",
+ _nested(["k"] * 32, 1),
+ id="key-at-the-limit",
+ ),
+ pytest.param(
+ "[" + ".".join(['"k.k"'] * 32) + "]\n",
+ _nested(["k.k"] * 32, {}),
+ id="dots-inside-quoted-parts",
+ ),
+ pytest.param(
+ f'text = "{_OVERLONG_KEY}"\n', {"text": _OVERLONG_KEY}, id="string"
+ ),
+ pytest.param(
+ f"text = '''\n[{_OVERLONG_KEY}]\n'''\n",
+ {"text": f"[{_OVERLONG_KEY}]\n"},
+ id="multiline-string",
+ ),
+ pytest.param(
+ f'# [{_OVERLONG_KEY}] """ \'\nx = 1\n', {"x": 1}, id="comment"
+ ),
+ pytest.param(
+ "values = [" + ", ".join(["1.5"] * 40) + "]\n",
+ {"values": [1.5] * 40},
+ id="float-array",
+ ),
+ ],
+)
+def test_dotted_text_outside_overlong_keys_still_loads(
+ tmp_path, document, expected
+):
+ path = tmp_path / "ordinary.toml"
+ path.write_bytes(document.encode())
+ documents = TOMLLoader(path).load()
+ assert json.loads(documents[0].page_content) == expected
+
+
+def test_upload_refusal_reports_no_text_instead_of_parsing(monkeypatch):
+ content = f"{_OVERLONG_KEY} = 1\n".encode()
+ _forbid_parsing(monkeypatch)
+ with pytest.raises(toml_limits.TOMLLimitError):
+ load_from_bytes(content, ".toml", "deep.toml")
+ assert extract_text_from_bytes(content, ".toml", "deep.toml") is None
diff --git a/tests/document_loaders/test_upload_integration.py b/tests/document_loaders/test_upload_integration.py
index 21ad19a67f..51fccb9833 100644
--- a/tests/document_loaders/test_upload_integration.py
+++ b/tests/document_loaders/test_upload_integration.py
@@ -297,15 +297,10 @@ log_level = "INFO"
# Read as bytes
file_bytes = file_path.read_bytes()
- # Extract text - may return None if tomli is not installed
extracted = extract_text_from_bytes(file_bytes, ".toml", "config.toml")
- # TOML extraction requires optional 'tomli' dependency
- # Skip assertion if it returns None (dependency not installed)
- if extracted is not None:
- assert "local-deep-research" in extracted or "project" in extracted
- else:
- pytest.skip("TOML extraction requires 'tomli' package")
+ assert extracted is not None
+ assert "local-deep-research" in extracted or "project" in extracted
class TestUnicodeFileExtraction:
diff --git a/tests/security/test_save_raw_config_blocked_keys_fastapi.py b/tests/security/test_save_raw_config_blocked_keys_fastapi.py
index fc1a30b190..f36aaec3f7 100644
--- a/tests/security/test_save_raw_config_blocked_keys_fastapi.py
+++ b/tests/security/test_save_raw_config_blocked_keys_fastapi.py
@@ -4,10 +4,10 @@ WHY THIS FILE EXISTS
--------------------
``/api/save_raw_config`` takes a user-supplied TOML blob and writes it to
``<data_dir>/config/config.toml``. Before writing, the handler parses the
-blob and refuses it if any key matches ``BLOCKED_KEY_PATTERNS``
+blob and refuses it if any key matches ``_BLOCKED_KEY_PATTERNS``
(``src/local_deep_research/web/routers/research.py``)::
- BLOCKED_KEY_PATTERNS = ["module_path", "class_name", "module", "class"]
+ _BLOCKED_KEY_PATTERNS = ("module_path", "class_name", "module", "class")
Those key names are how this codebase points config at a Python module or
class to import, so letting a user write them into the config file is a
@@ -21,11 +21,13 @@ migration deleted all three and wrote no replacement: before this file,
``grep -rn save_raw_config tests/`` matched nothing at all. This restores
the coverage against the FastAPI route and extends it, because the
original suite only ever tried three of the four patterns and only two
-nesting shapes.
+nesting shapes. Section 8 also covers the parsing limits the handler
+applies before tomllib runs (``security/toml_limits.py``), and section 9
+the bounds on the walk that follows the parse.
HOW THE SCANNER ACTUALLY WORKS (read off the handler, not assumed)
------------------------------------------------------------------
-``find_blocked_keys`` walks the parsed TOML recursively — into nested
+``_find_blocked_keys`` walks the parsed TOML at every depth — into nested
dicts AND into lists — and for every dict key tests
``pattern in key.lower()``. So the match is:
@@ -71,9 +73,14 @@ HARNESS
produce a 429 that has nothing to do with the guard under test.
"""
+import asyncio
import itertools
+import json
+import sys
+import threading
import uuid
from pathlib import Path
+from unittest.mock import AsyncMock, MagicMock
import pytest
from fastapi.testclient import TestClient
@@ -319,7 +326,7 @@ _EACH_PATTERN = [
def test_each_blocked_pattern_is_rejected(
app, allow_config_write, config_file, raw_config, expected_paths
):
- """Each entry of ``BLOCKED_KEY_PATTERNS`` is refused with 403 and
+ """Each entry of ``_BLOCKED_KEY_PATTERNS`` is refused with 403 and
nothing is written.
The write gate is OPEN for this test (``allow_config_write``), so the
@@ -846,3 +853,291 @@ def test_pinned_write_gate_default_denies_with_a_500(app, config_file):
"error": "Failed to process request",
}
_assert_not_saved(config_file, "the write gate was closed")
+
+
+# ---------------------------------------------------------------------------
+# 8. Parsing limits.
+#
+# The body may be 16 MB, and tomllib's cost for one long dotted key grows
+# with the square of its parts, so the handler refuses text over
+# MAX_TOML_BYTES, or with a key or table header of more than
+# MAX_TOML_KEY_PARTS dotted parts, before tomllib parses it
+# (security/toml_limits.py). Each refusal is checked against tomllib's own
+# entry point: no tomllib.loads call may receive the submitted text.
+# ---------------------------------------------------------------------------
+
+
+def _record_parses_of(monkeypatch, raw_config: str) -> list[str]:
+ """Record every ``tomllib.loads`` call that receives *raw_config*.
+
+ Other parses in the request (theme front matter on the pages the
+ harness loads for CSRF) pass through unrecorded.
+ """
+ import tomllib
+
+ parses: list[str] = []
+ real_loads = tomllib.loads
+ submitted = raw_config.replace("\r\n", "\n")
+
+ def recording_loads(text, *args, **kwargs):
+ if text in (raw_config, submitted):
+ parses.append(text)
+ return real_loads(text, *args, **kwargs)
+
+ monkeypatch.setattr(tomllib, "loads", recording_loads)
+ return parses
+
+
+def test_overlong_dotted_key_is_refused_before_tomllib_parses_it(
+ app, allow_config_write, config_file, monkeypatch
+):
+ client = _authenticated_client(app)
+ raw_config = "[search]\n" + ".".join(["k"] * 33) + " = 1\n"
+ parses = _record_parses_of(monkeypatch, raw_config)
+
+ resp = _save(client, raw_config)
+
+ assert resp.status_code == 400, f"{resp.status_code} {resp.text[:300]}"
+ body = resp.json()
+ assert body["success"] is False
+ assert body["error"].startswith("Configuration exceeds the parsing limits")
+ assert parses == [], "tomllib parsed a key over the dotted-part limit"
+ _assert_not_saved(config_file, "a key had more than 32 dotted parts")
+
+
+def test_dotted_key_at_the_part_limit_is_accepted_and_written(
+ app, allow_config_write, config_file
+):
+ client = _authenticated_client(app)
+ raw_config = "[search]\n" + ".".join(["k"] * 32) + " = 1\n"
+
+ resp = _save(client, raw_config)
+
+ assert resp.status_code == 200, f"{resp.status_code} {resp.text[:300]}"
+ assert resp.json() == {"success": True}
+ assert config_file.read_text() == raw_config
+
+
+def test_config_over_the_size_limit_is_refused_before_tomllib_parses_it(
+ app, allow_config_write, config_file, monkeypatch
+):
+ from local_deep_research.security import toml_limits
+
+ monkeypatch.setattr(
+ toml_limits, "MAX_TOML_BYTES", len(CLEAN_CONFIG.encode())
+ )
+ client = _authenticated_client(app)
+
+ resp = _save(client, CLEAN_CONFIG)
+ assert resp.status_code == 200, f"{resp.status_code} {resp.text[:300]}"
+ assert config_file.read_text() == CLEAN_CONFIG
+
+ over_limit = CLEAN_CONFIG + "#"
+ parses = _record_parses_of(monkeypatch, over_limit)
+ resp = _save(client, over_limit)
+
+ assert resp.status_code == 400, f"{resp.status_code} {resp.text[:300]}"
+ body = resp.json()
+ assert body["success"] is False
+ assert body["error"].startswith("Configuration exceeds the parsing limits")
+ assert parses == [], "tomllib parsed a config over the size limit"
+ _assert_not_saved(
+ config_file, "the config was one byte over the limit", CLEAN_CONFIG
+ )
+
+
+# ---------------------------------------------------------------------------
+# 9. The protected-key walk.
+#
+# The walk runs on what the parse returned. It is offloaded like the parse,
+# and its report is bounded: at most _MAX_REPORTED_BLOCKED_KEYS paths, each
+# cut to _MAX_BLOCKED_KEY_PATH_CHARS characters. It used to build the full
+# path of every key on the event loop and keep the path of every protected
+# one, so each key under one long table name repeated that name. These tests
+# lower those limits, so their inputs stay small. The ones that need no app
+# call the handler directly, as
+# tests/web/routers/test_research_model_log_preview_bound.py does: its 403
+# returns before any DB or file access.
+# ---------------------------------------------------------------------------
+
+_ELLIPSIS = "\N{HORIZONTAL ELLIPSIS}"
+
+
+def _call_save_raw_config(raw_config: str):
+ """Run the handler on an event loop on this thread, without the app."""
+ from local_deep_research.web.routers import research
+
+ request = MagicMock()
+ request.json = AsyncMock(return_value={"raw_config": raw_config})
+ response = asyncio.run(research.save_raw_config(request, "testuser"))
+ return response.status_code, json.loads(response.body)
+
+
+def test_the_protected_key_walk_runs_off_the_event_loop(monkeypatch):
+ """The parse is replaced by one returning tables that record the thread
+ each walk of them runs on. ``asyncio.run`` runs the event loop on this
+ thread, so no table may be walked here."""
+ from local_deep_research.security import toml_limits
+
+ walked_on: list[int] = []
+
+ class RecordingTable(dict):
+ def items(self):
+ walked_on.append(threading.get_ident())
+ return super().items()
+
+ monkeypatch.setattr(
+ toml_limits,
+ "loads_toml_within_limits",
+ lambda text: RecordingTable(custom=RecordingTable(module_path="x")),
+ )
+
+ status, body = _call_save_raw_config('[custom]\nmodule_path = "x"\n')
+
+ assert status == 403, body
+ assert body["blocked_keys"] == ["custom.module_path"]
+ assert len(walked_on) == 2, walked_on
+ assert threading.get_ident() not in walked_on, (
+ "the protected-key walk ran on the event loop"
+ )
+
+
+def test_the_walk_stops_at_the_first_protected_key_past_the_limit(
+ monkeypatch,
+):
+ from local_deep_research.security import toml_limits
+ from local_deep_research.web.routers import research
+
+ later_walked: list[bool] = []
+
+ class LaterTable(dict):
+ def items(self):
+ later_walked.append(True)
+ return super().items()
+
+ monkeypatch.setattr(research, "_MAX_REPORTED_BLOCKED_KEYS", 1)
+ monkeypatch.setattr(
+ toml_limits,
+ "loads_toml_within_limits",
+ lambda text: {"module": 1, "class": 2, "later": LaterTable(module=3)},
+ )
+
+ status, body = _call_save_raw_config(
+ "module = 1\nclass = 2\n[later]\nmodule = 3\n"
+ )
+
+ assert status == 403, body
+ assert body["blocked_keys"] == ["module"]
+ assert body["blocked_keys_truncated"] is True
+ assert later_walked == [], (
+ "the walk went on past the first protected key over the limit"
+ )
+
+
+ ("raw_config", "expected_path"),
+ [
+ pytest.param("[abcde]\nmodule = 1\n", "abcde.module", id="at-limit"),
+ pytest.param(
+ "[abcdef]\nmodule = 1\n",
+ "abcdef.modu" + _ELLIPSIS,
+ id="one-over",
+ ),
+ pytest.param(
+ "[[ab]]\nmodule_path = 1\n",
+ "ab[0].modul" + _ELLIPSIS,
+ id="after-an-array-index",
+ ),
+ pytest.param(
+ "[" + "t" * 40 + "]\nmodule = 1\n",
+ "t" * 11 + _ELLIPSIS,
+ id="long-table-name",
+ ),
+ pytest.param(
+ "module" + "x" * 40 + " = 1\n",
+ "module" + "x" * 5 + _ELLIPSIS,
+ id="long-protected-key",
+ ),
+ ],
+)
+def test_a_protected_key_path_is_cut_to_the_limit(
+ monkeypatch, raw_config, expected_path
+):
+ """With the limit lowered to 12 characters. A cut path ends with an
+ ellipsis, so it cannot pass for a whole one."""
+ from local_deep_research.web.routers import research
+
+ monkeypatch.setattr(research, "_MAX_BLOCKED_KEY_PATH_CHARS", 12)
+
+ status, body = _call_save_raw_config(raw_config)
+
+ assert status == 403, body
+ assert body["blocked_keys"] == [expected_path]
+ assert len(expected_path) <= 12
+
+
+def test_more_protected_keys_than_are_listed_still_refuses_the_save(
+ app, allow_config_write, config_file, monkeypatch
+):
+ """Fail closed: past the limit the list is cut, and the configuration is
+ refused all the same, with a response that says the list was cut."""
+ from local_deep_research.web.routers import research
+
+ monkeypatch.setattr(research, "_MAX_REPORTED_BLOCKED_KEYS", 3)
+ client = _authenticated_client(app)
+ three = '[a]\nmodule = 1\nname = "x"\nclass = 2\n[b]\nmodule_path = 3\n'
+ listed = ["a.module", "a.class", "b.module_path"]
+
+ resp = _save(client, three)
+
+ assert resp.status_code == 403, f"{resp.status_code} {resp.text[:300]}"
+ body = resp.json()
+ assert body["blocked_keys"] == listed
+ assert body["blocked_keys_truncated"] is False
+ assert body["error"] == (
+ "Configuration contains protected keys that cannot be modified"
+ )
+
+ resp = _save(client, three + "class_name = 4\n")
+
+ assert resp.status_code == 403, f"{resp.status_code} {resp.text[:300]}"
+ body = resp.json()
+ assert body["blocked_keys"] == listed
+ assert body["blocked_keys_truncated"] is True
+ assert body["error"] == (
+ "Configuration contains protected keys that cannot be modified; "
+ "only the first 3 are listed"
+ )
+ _assert_not_saved(
+ config_file, "the config had more protected keys than are listed"
+ )
+
+
+def test_a_configuration_nested_past_the_recursion_limit_is_walked(
+ app, allow_config_write, config_file
+):
+ """A dotted key in an inline table nests up to 32 tables for a few
+ frames of tomllib's own recursion, so this configuration of about 2 KB
+ parses within the limits yet nests deeper than Python's recursion
+ limit. The walk recursed once per level of nesting, so it raised
+ RecursionError, a 500; it keeps its own stack."""
+ from local_deep_research.web.routers import research
+
+ levels = sys.getrecursionlimit() // 32 + 1
+ key = ".".join(["k"] * 32)
+ raw_config = (
+ "x = "
+ + ("{" + key + " = ") * levels
+ + "{ module = 1 }"
+ + "}" * levels
+ + "\n"
+ )
+ client = _authenticated_client(app)
+
+ resp = _save(client, raw_config)
+
+ assert resp.status_code == 403, f"{resp.status_code} {resp.text[:300]}"
+ limit = research._MAX_BLOCKED_KEY_PATH_CHARS
+ path = "x" + ".k" * (32 * levels) + ".module"
+ assert resp.json()["blocked_keys"] == [path[: limit - 1] + _ELLIPSIS]
+ _assert_not_saved(config_file, "the config nested a protected key deep")
diff --git a/tests/security/test_toml_limits.py b/tests/security/test_toml_limits.py
new file mode 100644
index 0000000000..88ca76aeb2
--- /dev/null
+++ b/tests/security/test_toml_limits.py
@@ -0,0 +1,75 @@
+"""Limits on TOML text checked before tomllib parses it.
+
+The key scanner's edge cases (strings, comments, escapes, CRLF, inline
+tables) are exercised through files in
+``tests/document_loaders/test_toml_loader.py``; these tests cover the
+text entry point that ``POST /api/save_raw_config`` uses.
+"""
+
+import tomllib
+
+import pytest
+
+from local_deep_research.security import toml_limits
+
+# One part more than MAX_TOML_KEY_PARTS (32).
+_OVERLONG_KEY = ".".join(["k"] * 33)
+
+
+def _forbid_parsing(monkeypatch):
+ """Fail if tomllib runs, so a refusal must happen before parsing."""
+
+ def parse_attempted(*args, **kwargs):
+ raise AssertionError("tomllib ran on input that must be refused")
+
+ monkeypatch.setattr(tomllib, "loads", parse_attempted)
+
+
+def test_text_within_the_limits_parses():
+ assert toml_limits.loads_toml_within_limits(
+ '[search]\ntool = "searxng"\r\n'
+ ) == {"search": {"tool": "searxng"}}
+
+
+def test_text_over_the_size_limit_is_refused_before_parsing(monkeypatch):
+ monkeypatch.setattr(toml_limits, "MAX_TOML_BYTES", 8)
+ assert toml_limits.loads_toml_within_limits("x = 'ab'") == {"x": "ab"}
+
+ _forbid_parsing(monkeypatch)
+ with pytest.raises(toml_limits.TOMLLimitError, match="larger than 8"):
+ toml_limits.loads_toml_within_limits("x = 'abc'")
+
+
+def test_size_limit_counts_utf8_bytes_not_characters(monkeypatch):
+ monkeypatch.setattr(toml_limits, "MAX_TOML_BYTES", 8)
+ text = "x = 'éé'"
+ assert len(text) == 8
+ assert len(text.encode()) == 10
+
+ _forbid_parsing(monkeypatch)
+ with pytest.raises(toml_limits.TOMLLimitError, match="larger than 8"):
+ toml_limits.loads_toml_within_limits(text)
+
+
+ "text",
+ [
+ pytest.param(f"{_OVERLONG_KEY} = 1\n", id="dotted-key"),
+ pytest.param(f"[{_OVERLONG_KEY}]\r\n", id="crlf-table-header"),
+ ],
+)
+def test_overlong_key_text_is_refused_before_parsing(monkeypatch, text):
+ _forbid_parsing(monkeypatch)
+ with pytest.raises(
+ toml_limits.TOMLLimitError, match="more than 32 dotted parts"
+ ):
+ toml_limits.loads_toml_within_limits(text)
+
+
[email protected]("value", [b"x = 1", ["x = 1"], 1])
+def test_non_string_input_is_rejected_before_parsing(monkeypatch, value):
+ # Python 3.12's tomllib raises different errors for these inputs. Check
+ # our stable contract and prove that invalid types never reach parsing.
+ _forbid_parsing(monkeypatch)
+ with pytest.raises(TypeError, match="Expected str object"):
+ toml_limits.loads_toml_within_limits(value)
diff --git a/tests/web/routers/test_async_handler_blocking_guard.py b/tests/web/routers/test_async_handler_blocking_guard.py
index 8b6e1fc941..0d8505dc09 100644
--- a/tests/web/routers/test_async_handler_blocking_guard.py
+++ b/tests/web/routers/test_async_handler_blocking_guard.py
@@ -74,8 +74,12 @@ comments in ``run_db_sync``'s docstring, or on a string literal.
"""
import ast
+import functools
+import importlib.util
from pathlib import Path
+import pytest
+
import local_deep_research.web.routers as routers_pkg
ROUTERS_DIR = Path(routers_pkg.__file__).resolve().parent
@@ -259,6 +263,23 @@ _CPU_BOUND_PARSERS: dict[str, str] = {
),
}
+# This repo's own wrappers around a parser above. A wrapper hides the parse
+# from the direct scan, and the cross-module scan further down sees it only
+# while the parse stays in the wrapper's own frame, so the wrapper is named
+# here as well. Matched like _BARE_NAME_BLOCKLIST, on the last dotted
+# component: `loads_toml_within_limits(...)`,
+# `toml_limits.loads_toml_within_limits(...)` and a call through any alias
+# of the module all resolve.
+_CPU_BOUND_HELPERS: dict[str, str] = {
+ "loads_toml_within_limits": (
+ "security/toml_limits.py's loads_toml_within_limits() scans the text "
+ "for over-long dotted keys and then runs tomllib.loads() on it. Its "
+ "512 KiB cap bounds the cost but does not remove it: a document of "
+ "32-part table headers at the cap measured ~0.8 s per call. Offload "
+ "with asyncio.to_thread, as research.py's save_raw_config does."
+ ),
+}
+
_EXACT_DOTTED_BLOCKLIST: dict[str, str] = {
"time.sleep": (
@@ -391,6 +412,8 @@ def _classify_blocking_call(dotted: str) -> str | None:
last = dotted.rsplit(".", 1)[-1]
if last in _BARE_NAME_BLOCKLIST:
return _BARE_NAME_BLOCKLIST[last]
+ if last in _CPU_BOUND_HELPERS:
+ return _CPU_BOUND_HELPERS[last]
return None
@@ -790,10 +813,14 @@ def test_no_blocking_reachable_one_helper_deep_from_an_async_handler():
already found. The pre-merge readiness audit flagged this as its top
UNVERIFIABLE item.
- Resolved statically for same-file helpers: currently zero. Cross-module
- helpers remain out of reach for an AST scan and are still the residual gap
- -- ``PYTHONASYNCIODEBUG=1`` with a low ``slow_callback_duration``, driven by
- the Puppeteer suite, is the experiment that would cover those.
+ Resolved statically for same-file helpers: currently zero. A sync helper
+ imported from another module of this package is followed one level by
+ ``test_no_blocking_reachable_one_helper_deep_in_another_module`` below.
+ The residual gap is blocking that no list names and that is reached more
+ than one call deep, through an async helper or a method, or through a
+ callee bound other than by an import -- ``PYTHONASYNCIODEBUG=1`` with a
+ low ``slow_callback_duration``, driven by the Puppeteer suite, is the
+ experiment that would cover those.
"""
findings = []
for path in SCANNED_FILES:
@@ -847,6 +874,361 @@ def test_the_indirect_scan_does_not_flag_a_correctly_offloaded_helper():
assert _indirect_blocking_hits(tree, "synthetic.py") == []
+# ===========================================================================
+# One level of indirection across modules: handler -> sync helper imported
+# from another module of this package -> blocking call
+# ===========================================================================
+
+#: The directory that holds the package; dotted module names resolve to
+#: files under it.
+SRC_ROOT = ROUTERS_DIR.parents[2]
+_PACKAGE = "local_deep_research"
+
+#: The package that relative imports in a synthetic web/routers module
+#: resolve against.
+ROUTERS_PACKAGE = routers_pkg.__name__
+
+
+def _in_package(module: str) -> bool:
+ return module == _PACKAGE or module.startswith(_PACKAGE + ".")
+
+
+def _module_file(module: str) -> Path | None:
+ """The source file of the dotted *module* under SRC_ROOT, if any."""
+ base = SRC_ROOT.joinpath(*module.split("."))
+ for candidate in (base.with_suffix(".py"), base / "__init__.py"):
+ if candidate.is_file():
+ return candidate
+ return None
+
+
+def _package_of(path: Path) -> str:
+ """The package that relative imports in the file at *path* resolve
+ against."""
+ parts = path.resolve().relative_to(SRC_ROOT).with_suffix("").parts
+ return ".".join(parts[:-1])
+
+
+def _own_frame(node: ast.AST):
+ """Yield every node in *node*'s own frame: like
+ ``_collect_blocking_calls``, never descend into a nested def or lambda."""
+ for child in ast.iter_child_nodes(node):
+ if isinstance(
+ child, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda)
+ ):
+ continue
+ yield child
+ yield from _own_frame(child)
+
+
+def _import_bindings(node: ast.AST, package: str, out: dict) -> None:
+ """Record what each name imported in *node*'s own frame refers to.
+
+ ``out[name]`` becomes ``(module, None)`` for a module of this package,
+ ``(module, attr)`` for ``attr`` imported from one, and ``None`` for a
+ name imported from outside the package, so that importing a name again
+ replaces what it was bound to before.
+ """
+ for child in _own_frame(node):
+ if isinstance(child, ast.ImportFrom):
+ source = (
+ importlib.util.resolve_name(
+ "." * child.level + (child.module or ""), package
+ )
+ if child.level
+ else child.module
+ )
+ for alias in child.names:
+ bound = alias.asname or alias.name
+ submodule = f"{source}.{alias.name}"
+ if not _in_package(source):
+ out[bound] = None
+ elif _module_file(submodule) is not None:
+ out[bound] = (submodule, None)
+ else:
+ out[bound] = (source, alias.name)
+ elif isinstance(child, ast.Import):
+ for alias in child.names:
+ bound = alias.asname or alias.name.partition(".")[0]
+ module = alias.name if alias.asname else bound
+ out[bound] = (module, None) if _in_package(module) else None
+
+
+def _parsed_module(path: Path) -> ast.Module:
+ return _parse(path)
+
+
+def _module_level_def(module: str, name: str, reexport_hops: int = 1):
+ """``(module, node)`` for the top-level sync ``def name`` in *module*.
+
+ Follows up to *reexport_hops* re-exports, such as security/__init__.py's
+ ``from .safe_requests import safe_get, safe_post, SafeSession``.
+ """
+ path = _module_file(module)
+ if path is None:
+ return None
+ tree = _parsed_module(path)
+ for node in tree.body:
+ if isinstance(node, ast.FunctionDef) and node.name == name:
+ return module, node
+ if reexport_hops:
+ bindings: dict = {}
+ _import_bindings(tree, _package_of(path), bindings)
+ target = bindings.get(name)
+ if target is not None and target[1] is not None:
+ return _module_level_def(*target, reexport_hops - 1)
+ return None
+
+
+def _resolve_imported_function(dotted: str, bindings: dict):
+ """``(module, node)`` for a call to a sync function that an import binds
+ to a module of this package, else None."""
+ head, *rest = dotted.split(".")
+ binding = bindings.get(head)
+ if binding is None:
+ return None
+ module, attr = binding
+ if attr is not None:
+ # `from pkg.mod import f`: only a bare `f(...)` calls f itself.
+ return None if rest else _module_level_def(module, attr)
+ if not rest:
+ return None
+ *submodules, name = rest
+ return _module_level_def(".".join([module, *submodules]), name)
+
+
+def _cross_module_blocking_hits(tree, rel_path, package):
+ """(handler, imported helper, blocking call) for one level of
+ indirection into another module of this package."""
+ module_bindings: dict = {}
+ _import_bindings(tree, package, module_bindings)
+ depends_names = _depends_target_names(tree)
+ hits = []
+ for node in ast.walk(tree):
+ if not _is_async_router_handler(node, depends_names):
+ continue
+ bindings = dict(module_bindings)
+ _import_bindings(node, package, bindings)
+ for child in _own_frame(node):
+ if not isinstance(child, ast.Call):
+ continue
+ dotted = _dotted_call_name(child)
+ target = dotted and _resolve_imported_function(dotted, bindings)
+ if not target:
+ continue
+ helper_module, helper = target
+ inner: list = []
+ _collect_blocking_calls(helper, inner)
+ for inner_line, inner_dotted, reason in inner:
+ hits.append(
+ f" {rel_path}:{child.lineno}: {node.name}() calls "
+ f"{dotted}() in its own frame, and "
+ f"{helper_module}.{helper.name}() calls "
+ f"`{inner_dotted}` at line {inner_line} -- {reason}"
+ )
+ return hits
+
+
+def test_no_blocking_reachable_one_helper_deep_in_another_module():
+ """The check above, for a sync helper imported from another module.
+
+ save_raw_config is why the same-file scan is not enough on its own: its
+ TOML parse sits behind ``toml_limits.loads_toml_within_limits`` in
+ security/toml_limits.py, a module that scan never reads, so inlining the
+ handler's ``asyncio.to_thread`` offload went unreported.
+ _CPU_BOUND_HELPERS now names that helper for the direct scan; this scan
+ is for the next wrapper nobody has listed.
+
+ Followed: a call, in the own frame of an async route handler or async
+ ``Depends`` target, whose callee an import (at module level or in that
+ frame) binds to a top-level sync ``def`` in another module of this
+ package -- ``f(...)`` after ``from pkg.mod import f``, or ``mod.f(...)``
+ after an import of ``mod`` -- found directly or through one re-export,
+ such as a package ``__init__``'s.
+
+ Not followed: ``async def`` helpers, which the same-file scan skips too
+ (an async helper can make its own offload decision, as notes.py's
+ ``_parse_json_off_loop`` does when it parses a body under a size
+ threshold inline); methods; names bound other than by an import; and
+ anything more than one call deep.
+ """
+ findings = []
+ for path in SCANNED_FILES:
+ findings.extend(
+ _cross_module_blocking_hits(
+ _parse(path), _rel(path), _package_of(path)
+ )
+ )
+
+ assert not findings, (
+ "An `async def` route handler reaches an event-loop-blocking call "
+ "through a sync helper imported from another module:\n"
+ + "\n".join(findings)
+ + "\n\nFIX: offload the helper call -- hand the helper to "
+ "asyncio.to_thread or run_db_sync, as save_raw_config does with "
+ "toml_limits.loads_toml_within_limits."
+ )
+
+
+class _InlineToThread(ast.NodeTransformer):
+ """Rewrite ``await asyncio.to_thread(f, *args)`` as ``f(*args)``: the
+ de-offload these scans exist to catch. ``inlined`` lists each ``f``, in
+ source order."""
+
+ def __init__(self):
+ self.inlined: list[str] = []
+
+ def visit_Await(self, node):
+ self.generic_visit(node)
+ call = node.value
+ if (
+ isinstance(call, ast.Call)
+ and _dotted_call_name(call) == "asyncio.to_thread"
+ and call.args
+ ):
+ self.inlined.append(ast.unparse(call.args[0]))
+ inlined = ast.Call(
+ func=call.args[0], args=call.args[1:], keywords=call.keywords
+ )
+ return ast.copy_location(inlined, node)
+ return node
+
+
+def test_save_raw_config_with_its_toml_parse_inlined_is_reported():
+ """Mutation check on the real handler.
+
+ research.py's save_raw_config offloads two calls with
+ ``asyncio.to_thread``: ``toml_limits.loads_toml_within_limits``, then
+ ``_find_blocked_keys`` on the parsed configuration. With both made
+ directly instead, the direct scan must report the parse (via
+ _CPU_BOUND_HELPERS) and the cross-module scan must report the
+ tomllib.loads inside it. As written, the handler is clean for both.
+
+ Neither scan reports the inlined walk, which calls nothing on any list
+ in this file. Its offload is checked by running the handler, in
+ tests/security/test_save_raw_config_blocked_keys_fastapi.py.
+ """
+ path = ROUTERS_DIR / "research.py"
+ tree = _parse(path)
+ package = _package_of(path)
+
+ def direct():
+ return [
+ (v[0], v[2])
+ for v in find_blocking_calls_in_async_route_handlers(tree)
+ if v[1] == "save_raw_config"
+ ]
+
+ def cross():
+ return [
+ hit
+ for hit in _cross_module_blocking_hits(tree, _rel(path), package)
+ if " save_raw_config() " in hit
+ ]
+
+ assert direct() == []
+ assert cross() == []
+
+ [handler] = [
+ node
+ for node in ast.walk(tree)
+ if isinstance(node, ast.AsyncFunctionDef)
+ and node.name == "save_raw_config"
+ ]
+ inliner = _InlineToThread()
+ inliner.visit(handler)
+ assert inliner.inlined == [
+ "toml_limits.loads_toml_within_limits",
+ "_find_blocked_keys",
+ ], (
+ f"save_raw_config offloads {inliner.inlined} with asyncio.to_thread "
+ "-- update this test to the handler's new shape."
+ )
+
+ reported = direct()
+ assert [dotted for _line, dotted in reported] == [
+ "toml_limits.loads_toml_within_limits"
+ ], reported
+ inner = cross()
+ assert len(inner) == 1, inner
+ assert f"{path.name}:{reported[0][0]}:" in inner[0], inner
+ assert (
+ "local_deep_research.security.toml_limits.loads_toml_within_limits() "
+ "calls `tomllib.loads`" in inner[0]
+ ), inner
+
+
+_TOML_PARSE_SPELLINGS = {
+ "function-imported": (
+ "from local_deep_research.security.toml_limits import "
+ "loads_toml_within_limits\n",
+ "loads_toml_within_limits",
+ ),
+ "module-aliased-relative": (
+ "from ...security import toml_limits as limits\n",
+ "limits.loads_toml_within_limits",
+ ),
+ "module-dotted-absolute": (
+ "import local_deep_research.security.toml_limits\n",
+ "local_deep_research.security.toml_limits.loads_toml_within_limits",
+ ),
+}
+
+
+ ("imports", "callee"),
+ list(_TOML_PARSE_SPELLINGS.values()),
+ ids=list(_TOML_PARSE_SPELLINGS),
+)
+def test_each_import_spelling_of_the_toml_parse_is_reported(imports, callee):
+ """Each of these import spellings leaves the call visible to both scans."""
+ tree = ast.parse(
+ imports + "@router.post('/x')\n"
+ "async def handler(request):\n"
+ f" return {callee}(await request.body())\n"
+ )
+ direct = find_blocking_calls_in_async_route_handlers(tree)
+ assert [v[2] for v in direct] == [callee], direct
+ inner = _cross_module_blocking_hits(tree, "synthetic.py", ROUTERS_PACKAGE)
+ assert len(inner) == 1 and "calls `tomllib.loads`" in inner[0], inner
+
+
+def test_an_offloaded_toml_parse_is_not_reported():
+ """Negative control: the prescribed fix must not trip either scan."""
+ tree = ast.parse(
+ "from ...security import toml_limits\n"
+ "@router.post('/x')\n"
+ "async def handler(request):\n"
+ " body = await request.body()\n"
+ " return await asyncio.to_thread(\n"
+ " toml_limits.loads_toml_within_limits, body\n"
+ " )\n"
+ )
+ assert find_blocking_calls_in_async_route_handlers(tree) == []
+ hits = _cross_module_blocking_hits(tree, "synthetic.py", ROUTERS_PACKAGE)
+ assert hits == [], hits
+
+
+def test_the_cross_module_scan_follows_a_package_reexport():
+ """security/__init__.py re-exports ``safe_post`` from safe_requests.py,
+ whose own frame calls ``requests.post``. Importing it from the package
+ must not hide that. (No list in this file names ``safe_post``, so here
+ only the cross-module scan reports it.)"""
+ tree = ast.parse(
+ "from ...security import safe_post\n"
+ "@router.post('/x')\n"
+ "async def handler(request):\n"
+ " return safe_post('https://example.com')\n"
+ )
+ hits = _cross_module_blocking_hits(tree, "synthetic.py", ROUTERS_PACKAGE)
+ assert any(
+ "local_deep_research.security.safe_requests.safe_post() calls "
+ "`requests.post`" in hit
+ for hit in hits
+ ), hits
+
+
class TestScopeWideningSelfTest:
"""Prove the three scope fixes actually detect what they were added for.
diff --git a/tests/web/routers/test_research_model_log_preview_bound.py b/tests/web/routers/test_research_model_log_preview_bound.py
index 9f65d42eb0..a90956b364 100644
--- a/tests/web/routers/test_research_model_log_preview_bound.py
+++ b/tests/web/routers/test_research_model_log_preview_bound.py
@@ -757,12 +757,22 @@ class TestDeferredRequestValueLogSites:
"""Catches (W1)/(W2) at the blocked-keys warning, through the
real call.
- The raw TOML carries 50,000 blocked keys (every key matches the
- ``module`` pattern), so ``find_blocked_keys`` returns a 50,000
- path list and the warning line interpolates all of it. No DB or
- file access happens before the 403 return.
+ The raw TOML carries as many blocked keys as the 403 lists at
+ most (every key matches the ``module`` pattern), so
+ ``_find_blocked_keys`` returns its longest list and the warning
+ line interpolates all of it. No DB or file access happens before
+ the 403 return.
+
+ #7059 changed this test's premise (correct new behaviour, stale
+ test). It sent 50,000 keys, about 1 MB of TOML, which
+ save_raw_config now refuses with a 400 before parsing, since a
+ configuration may be at most 512 KiB; and the 403 now lists at
+ most ``_MAX_REPORTED_BLOCKED_KEYS`` keys. That many keys (100
+ today) take about 2 KB of TOML, and the repr of their list is
+ still far longer than the line bound asserted below.
"""
- raw_config = "\n".join(f"module_path_{i} = 1" for i in range(50_000))
+ count = research_module._MAX_REPORTED_BLOCKED_KEYS
+ raw_config = "\n".join(f"module_path_{i} = 1" for i in range(count))
request = _json_request({"raw_config": raw_config})
with loguru_caplog.at_level("WARNING"):
@@ -772,7 +782,11 @@ class TestDeferredRequestValueLogSites:
assert response.status_code == 403
body = json.loads(response.body)
- assert len(body["blocked_keys"]) == 50_000
+ assert len(body["blocked_keys"]) == count
+ assert body["blocked_keys_truncated"] is False
+ assert len(repr(body["blocked_keys"])) > 1000, (
+ "the list is too short for the line bound below to mean anything"
+ )
line = _bounded_line(
loguru_caplog.text,
"Security: Blocked attempt to write config",
diff --git a/tests/web/test_event_loop_stall_detection.py b/tests/web/test_event_loop_stall_detection.py
index 8edd8ecaf4..9327d9a19d 100644
--- a/tests/web/test_event_loop_stall_detection.py
+++ b/tests/web/test_event_loop_stall_detection.py
@@ -1,12 +1,15 @@
"""Runtime detection of event-loop stalls, at any call depth.
The AST guards in ``tests/web/routers/test_async_handler_blocking_guard.py``
-catch blocking calls written literally in an ``async def`` handler, and (since
-the pre-merge readiness audit) one level of indirection through a same-file
-helper. Both are static, so both share a ceiling: a handler that blocks through
-a helper in ANOTHER module is invisible to them. The audit named that as its
-top residual gap and proposed ``PYTHONASYNCIODEBUG=1`` with a lowered
-``slow_callback_duration`` as the experiment that would close it.
+catch blocking calls written literally in an ``async def`` handler, and one
+level of indirection through a sync helper: a same-file one (since the
+pre-merge readiness audit), or one imported from another module of this
+package. All are static, so all share a ceiling: blocking reached more than
+one call deep, through an async helper or a method, or through a callee the
+scanner cannot resolve is invisible to them unless one of their lists names a
+function on the way. The audit named blocking through a helper in ANOTHER
+module as its top residual gap and proposed ``PYTHONASYNCIODEBUG=1`` with a
+lowered ``slow_callback_duration`` as the experiment that would close it.
This is that experiment, as a test rather than a manual procedure.
@@ -100,9 +103,10 @@ async def test_no_request_stalls_the_event_loop(caplog):
f"{SLOW_CALLBACK_SECONDS}s while serving ordinary requests -- "
"something on the request path is blocking the event loop:\n "
+ "\n ".join(_slow_callback_messages(caplog))
- + "\n\nThis catches what the AST guards cannot: blocking reached "
- "through a helper in another module, or through an alias the scanner "
- "cannot resolve. Find the call and offload it "
+ + "\n\nThis catches what the AST guards miss: blocking reached more "
+ "than one call deep, through an async helper or a method, or "
+ "through a callee the scanner cannot resolve, when none of their "
+ "lists names a function on the way. Find the call and offload it "
"(asyncio.to_thread / run_db_sync), or make it async."
)