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: broaden absolute module path hook and add tests (#2177)

LearningCircuitd6eb202cc935
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 7b9a5a062a..980df9b132 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -174,12 +174,11 @@ repos:
files: \.py$
description: "Ensure DownloadService, LibraryRAGService, LocalEmbeddingManager use context managers"
- id: check-absolute-module-paths
- name: Check for absolute module paths in engine configs
+ name: Check for absolute module paths
entry: .pre-commit-hooks/check-absolute-module-paths.py
language: script
files: \.(py|json)$
- description: "Ensure search engine module_path values use relative imports, not
- absolute paths"
+ description: "Ensure module_path values use relative imports, not absolute paths"
- id: check-pdm-lock
name: Check pdm.lock sync
entry: .pre-commit-hooks/check-pdm-lock.sh
diff --git a/.pre-commit-hooks/check-absolute-module-paths.py b/.pre-commit-hooks/check-absolute-module-paths.py
index 95ef4e82b6..6aeadcc0c6 100755
--- a/.pre-commit-hooks/check-absolute-module-paths.py
+++ b/.pre-commit-hooks/check-absolute-module-paths.py
@@ -1,10 +1,11 @@
#!/usr/bin/env python3
"""
-Pre-commit hook to prevent absolute module paths for search engines.
+Pre-commit hook to prevent absolute module paths in the codebase.
-Search engine module_path values MUST use relative imports (starting with ".")
-instead of absolute paths (starting with "local_deep_research.web_search_engines.").
-The module whitelist security boundary requires relative paths.
+Module path configuration values MUST use relative imports (starting with ".")
+instead of absolute paths (starting with "local_deep_research.").
+The module whitelist security boundary requires relative paths for search engines,
+and absolute paths elsewhere are a packaging anti-pattern.
See: src/local_deep_research/security/module_whitelist.py
"""
@@ -16,24 +17,39 @@ from pathlib import Path
# The absolute base that must NOT appear as a module path prefix
-ABSOLUTE_BASE = "local_deep_research.web_search_engines"
-
-# Directory patterns where absolute paths are allowed
+ABSOLUTE_BASE = "local_deep_research"
+
+# Known legitimate uses of absolute package references that are NOT module_path
+# config values. These are used for importlib.resources, package= kwargs, and
+# normalization constants where the full package name is required by Python APIs.
+LEGITIMATE_ABSOLUTE_REFS = frozenset(
+ {
+ # importlib.resources.files() requires the full package name
+ "local_deep_research.defaults.settings",
+ # importlib.import_module() to avoid circular imports
+ "local_deep_research.utilities",
+ # package= kwarg for relative import resolution
+ "local_deep_research.llm.providers",
+ # Normalization prefix constant (used to strip, not as a module_path)
+ "local_deep_research.web_search_engines",
+ }
+)
+
+# Directory patterns where absolute paths are allowed (matched as path components)
ALLOWED_DIR_PATTERNS = {
- "tests/", # Tests may verify rejection of absolute paths
- ".pre-commit-hooks/", # Hook files themselves
+ "tests", # Tests may verify rejection of absolute paths
+ ".pre-commit-hooks", # Hook files themselves
}
-# Specific file paths where absolute paths are allowed
-ALLOWED_FILES = {
+# Specific file suffixes where absolute paths are allowed
+ALLOWED_FILE_SUFFIXES = {
+ # Use os.sep-independent matching via PurePosixPath
"security/module_whitelist.py", # Defines the security boundary itself
}
-# Basename prefixes/suffixes for test files
-ALLOWED_BASENAME_PATTERNS = {
- "test_", # test_*.py files
- "_test.", # *_test.py files
-}
+# Basename patterns for test files
+ALLOWED_BASENAME_PREFIXES = {"test_"} # test_*.py
+ALLOWED_BASENAME_SUFFIXES = {"_test.py"} # *_test.py
class AbsoluteModulePathChecker(ast.NodeVisitor):
@@ -45,15 +61,16 @@ class AbsoluteModulePathChecker(ast.NodeVisitor):
def visit_Constant(self, node):
"""Check string constants for absolute module paths."""
- if isinstance(node.value, str) and node.value.startswith(
- ABSOLUTE_BASE + "."
+ if (
+ isinstance(node.value, str)
+ and node.value.startswith(ABSOLUTE_BASE + ".")
+ and node.value not in LEGITIMATE_ABSOLUTE_REFS
):
- relative = node.value[len(ABSOLUTE_BASE) :]
self.errors.append(
(
node.lineno,
f'Absolute module path "{node.value}" found. '
- f'Use relative path "{relative}" instead.',
+ f"Use a relative path (starting with '.') instead.",
)
)
self.generic_visit(node)
@@ -61,16 +78,29 @@ class AbsoluteModulePathChecker(ast.NodeVisitor):
def _is_file_allowed(filename: str) -> bool:
"""Check if this file is allowed to contain absolute module paths."""
+ p = Path(filename)
+ normalized = p.as_posix()
+ parts = p.parts
+
+ # Check directory patterns as path components
for pattern in ALLOWED_DIR_PATTERNS:
- if pattern in filename:
+ if pattern in parts:
return True
- for pattern in ALLOWED_FILES:
- if pattern in filename:
+
+ # Check specific file suffixes
+ for suffix in ALLOWED_FILE_SUFFIXES:
+ if normalized.endswith(suffix):
return True
- basename = Path(filename).name
- for pattern in ALLOWED_BASENAME_PATTERNS:
- if basename.startswith(pattern) or pattern in basename:
+
+ # Check basename patterns
+ basename = p.name
+ for prefix in ALLOWED_BASENAME_PREFIXES:
+ if basename.startswith(prefix):
+ return True
+ for suffix in ALLOWED_BASENAME_SUFFIXES:
+ if basename.endswith(suffix):
return True
+
return False
@@ -108,7 +138,7 @@ def check_python_file(filename: str) -> bool:
def check_json_file(filename: str) -> bool:
- """Check a JSON config file for absolute module paths."""
+ """Check a JSON config file for absolute module paths in module_path keys."""
if _is_file_allowed(filename):
return True
@@ -125,22 +155,27 @@ def check_json_file(filename: str) -> bool:
if isinstance(obj, dict):
for key, value in obj.items():
current_path = f"{path}.{key}" if path else key
- _check_value(value, current_path)
+ # Only check values under module_path keys
+ if key == "module_path" and isinstance(value, str):
+ if (
+ value.startswith(ABSOLUTE_BASE + ".")
+ and value not in LEGITIMATE_ABSOLUTE_REFS
+ ):
+ errors.append((current_path, value))
+ elif isinstance(value, (dict, list)):
+ _check_value(value, current_path)
elif isinstance(obj, list):
for i, item in enumerate(obj):
_check_value(item, f"{path}[{i}]")
- elif isinstance(obj, str) and obj.startswith(ABSOLUTE_BASE + "."):
- relative = obj[len(ABSOLUTE_BASE) :]
- errors.append((path, obj, relative))
_check_value(data)
if errors:
print(f"\n{filename}:")
- for key_path, value, relative in errors:
+ for key_path, value in errors:
print(
f' Key "{key_path}": Absolute module path "{value}" found. '
- f'Use relative path "{relative}" instead.'
+ f"Use a relative path (starting with '.') instead."
)
return False
@@ -168,25 +203,14 @@ def main():
print("\n" + "=" * 70)
print("Module Path Security: Absolute module paths detected!")
print("=" * 70)
- print(
- "\nSearch engine module paths must use relative imports"
- " (starting with '.')"
- )
- print(
- "instead of absolute paths starting with"
- " 'local_deep_research.web_search_engines.'."
- )
+ print("\nModule paths must use relative imports (starting with '.')")
+ print("instead of absolute paths starting with 'local_deep_research.'.")
print("\nExamples:")
print(
' BAD: "local_deep_research.web_search_engines'
'.engines.search_engine_local"'
)
print(' GOOD: ".engines.search_engine_local"')
- print(
- "\nRelative paths are resolved against"
- " local_deep_research.web_search_engines"
- )
- print("and are required by the module whitelist security boundary.")
print("\nSee: src/local_deep_research/security/module_whitelist.py")
sys.exit(1)
else:
diff --git a/tests/security/test_absolute_module_paths_hook.py b/tests/security/test_absolute_module_paths_hook.py
new file mode 100644
index 0000000000..25c24fa103
--- /dev/null
+++ b/tests/security/test_absolute_module_paths_hook.py
@@ -0,0 +1,344 @@
+"""
+Tests for the check-absolute-module-paths pre-commit hook.
+
+Ensures the hook correctly detects absolute module paths (local_deep_research.*)
+that should be relative imports, while allowing legitimate uses.
+"""
+
+import ast
+import json
+import sys
+from importlib import import_module
+from pathlib import Path
+
+
+# Add the pre-commit hooks directory to path
+HOOKS_DIR = Path(__file__).parent.parent.parent / ".pre-commit-hooks"
+sys.path.insert(0, str(HOOKS_DIR))
+
+# Import the checker from the hook (must be after sys.path modification)
+hook_module = import_module("check-absolute-module-paths") # noqa: E402
+AbsoluteModulePathChecker = hook_module.AbsoluteModulePathChecker
+LEGITIMATE_ABSOLUTE_REFS = hook_module.LEGITIMATE_ABSOLUTE_REFS
+
+
+class TestAbsoluteModulePathChecker:
+ """Tests for the AbsoluteModulePathChecker AST visitor."""
+
+ def _check_code(self, code: str, filename: str = "src/module.py") -> list:
+ """Helper to check code and return errors."""
+ tree = ast.parse(code)
+ checker = AbsoluteModulePathChecker(filename)
+ checker.visit(tree)
+ return checker.errors
+
+ # --- Detection tests ---
+
+ def test_detects_web_search_engine_absolute_path(self):
+ """Should detect absolute paths in the web_search_engines subpackage."""
+ code = """
+module_path = "local_deep_research.web_search_engines.engines.search_engine_brave"
+"""
+ errors = self._check_code(code)
+ assert len(errors) == 1
+ assert "local_deep_research.web_search_engines" in errors[0][1]
+
+ def test_detects_llm_absolute_path(self):
+ """Should detect absolute paths in the llm subpackage."""
+ code = """
+path = "local_deep_research.llm.providers.implementations.openai_provider"
+"""
+ errors = self._check_code(code)
+ assert len(errors) == 1
+ assert "local_deep_research.llm" in errors[0][1]
+
+ def test_detects_arbitrary_subpackage_absolute_path(self):
+ """Should detect absolute paths in any subpackage."""
+ code = """
+x = "local_deep_research.some_new_package.foo.bar"
+"""
+ errors = self._check_code(code)
+ assert len(errors) == 1
+
+ def test_detects_multiple_violations(self):
+ """Should detect multiple violations in one file."""
+ code = """
+a = "local_deep_research.web_search_engines.engines.search_engine_local"
+b = "local_deep_research.web_search_engines.engines.search_engine_brave"
+c = "local_deep_research.llm.providers.implementations.openai_provider"
+"""
+ errors = self._check_code(code)
+ assert len(errors) == 3
+
+ def test_reports_correct_line_numbers(self):
+ """Should report the correct line number for violations."""
+ code = """
+# Some comment
+x = 1
+
+module_path = "local_deep_research.web_search_engines.engines.foo"
+"""
+ errors = self._check_code(code)
+ assert len(errors) == 1
+ assert errors[0][0] == 5 # Line 5
+
+ # --- Allowance tests ---
+
+ def test_allows_relative_paths(self):
+ """Should not flag relative module paths."""
+ code = """
+module_path = ".engines.search_engine_brave"
+"""
+ errors = self._check_code(code)
+ assert len(errors) == 0
+
+ def test_allows_legitimate_absolute_refs(self):
+ """Should not flag known legitimate absolute references."""
+ for ref in LEGITIMATE_ABSOLUTE_REFS:
+ code = f'''
+x = "{ref}"
+'''
+ errors = self._check_code(code)
+ assert len(errors) == 0, f"Legitimate ref '{ref}' was flagged"
+
+ def test_allows_unrelated_strings(self):
+ """Should not flag strings that don't start with local_deep_research."""
+ code = """
+name = "some_other_package.module"
+url = "https://example.com"
+msg = "This is a message"
+"""
+ errors = self._check_code(code)
+ assert len(errors) == 0
+
+ def test_allows_bare_package_name(self):
+ """Should not flag 'local_deep_research' without a dot-suffix."""
+ code = """
+name = "local_deep_research"
+"""
+ errors = self._check_code(code)
+ assert len(errors) == 0
+
+ def test_allows_non_string_constants(self):
+ """Should not flag integer or other non-string constants."""
+ code = """
+x = 42
+y = 3.14
+z = True
+"""
+ errors = self._check_code(code)
+ assert len(errors) == 0
+
+
+class TestIsFileAllowed:
+ """Tests for the _is_file_allowed() function."""
+
+ def test_allows_test_directory(self):
+ """Files under tests/ should be allowed."""
+ assert hook_module._is_file_allowed("tests/test_something.py") is True
+ assert (
+ hook_module._is_file_allowed("tests/security/test_whitelist.py")
+ is True
+ )
+
+ def test_allows_pre_commit_hooks_directory(self):
+ """Files under .pre-commit-hooks/ should be allowed."""
+ assert (
+ hook_module._is_file_allowed(
+ ".pre-commit-hooks/check-absolute-module-paths.py"
+ )
+ is True
+ )
+
+ def test_allows_module_whitelist(self):
+ """module_whitelist.py should be allowed."""
+ assert (
+ hook_module._is_file_allowed(
+ "src/local_deep_research/security/module_whitelist.py"
+ )
+ is True
+ )
+
+ def test_allows_test_prefix_basename(self):
+ """Files with test_ prefix should be allowed."""
+ assert hook_module._is_file_allowed("src/test_something.py") is True
+
+ def test_allows_test_suffix_basename(self):
+ """Files with _test.py suffix should be allowed."""
+ assert hook_module._is_file_allowed("src/something_test.py") is True
+
+ def test_rejects_normal_source_file(self):
+ """Normal source files should NOT be allowed."""
+ assert (
+ hook_module._is_file_allowed("src/local_deep_research/config.py")
+ is False
+ )
+
+ def test_no_false_positive_on_tests_in_filename(self):
+ """'tests' in a filename (not dir) should not allow the file."""
+ # 'my_tests_helper.py' has 'tests' in the name but isn't a test file
+ # and isn't in a tests/ directory
+ assert hook_module._is_file_allowed("src/my_tests_helper.py") is False
+
+ def test_no_false_positive_on_module_whitelist_substring(self):
+ """module_whitelist_extra.py should NOT match module_whitelist.py."""
+ assert (
+ hook_module._is_file_allowed(
+ "src/security/module_whitelist_extra.py"
+ )
+ is False
+ )
+
+ def test_no_false_positive_on_test_in_middle_of_name(self):
+ """'contest_results.py' should not match test_ prefix."""
+ assert hook_module._is_file_allowed("src/contest_results.py") is False
+
+
+class TestCheckPythonFile:
+ """Integration tests for check_python_file()."""
+
+ def test_clean_file_passes(self, tmp_path):
+ """A file with only relative paths should pass."""
+ clean = tmp_path / "clean_module.py"
+ clean.write_text("""
+config = {
+ "module_path": ".engines.search_engine_brave",
+ "class_name": "BraveSearchEngine",
+}
+""")
+ assert hook_module.check_python_file(str(clean)) is True
+
+ def test_violation_file_fails(self, tmp_path):
+ """A file with absolute paths should fail."""
+ bad = tmp_path / "bad_module.py"
+ bad.write_text("""
+config = {
+ "module_path": "local_deep_research.web_search_engines.engines.search_engine_brave",
+ "class_name": "BraveSearchEngine",
+}
+""")
+ assert hook_module.check_python_file(str(bad)) is False
+
+ def test_legitimate_ref_passes(self, tmp_path):
+ """A file using a legitimate absolute ref should pass."""
+ legit = tmp_path / "legit_module.py"
+ legit.write_text("""
+from importlib import resources
+data_dir = resources.files("local_deep_research.defaults.settings")
+""")
+ assert hook_module.check_python_file(str(legit)) is True
+
+ def test_syntax_error_passes(self, tmp_path):
+ """Files with syntax errors should pass (let other tools handle them)."""
+ broken = tmp_path / "broken.py"
+ broken.write_text("def bad(:\n pass")
+ assert hook_module.check_python_file(str(broken)) is True
+
+ def test_test_file_always_passes(self, tmp_path):
+ """Test files should always pass even with absolute paths."""
+ test_file = tmp_path / "test_whitelist.py"
+ test_file.write_text("""
+path = "local_deep_research.web_search_engines.engines.foo"
+""")
+ assert hook_module.check_python_file(str(test_file)) is True
+
+ def test_nonexistent_file_fails(self):
+ """A non-existent file should fail (returns False)."""
+ assert (
+ hook_module.check_python_file("/nonexistent/path/file.py") is False
+ )
+
+
+class TestCheckJsonFile:
+ """Integration tests for check_json_file()."""
+
+ def test_clean_json_passes(self, tmp_path):
+ """A JSON file with relative module_path should pass."""
+ clean = tmp_path / "engine.json"
+ clean.write_text(
+ json.dumps(
+ {
+ "module_path": ".engines.search_engine_brave",
+ "class_name": "BraveSearchEngine",
+ }
+ )
+ )
+ assert hook_module.check_json_file(str(clean)) is True
+
+ def test_absolute_module_path_in_json_fails(self, tmp_path):
+ """A JSON file with absolute module_path should fail."""
+ bad = tmp_path / "bad_engine.json"
+ bad.write_text(
+ json.dumps(
+ {
+ "module_path": "local_deep_research.web_search_engines.engines.search_engine_brave",
+ "class_name": "BraveSearchEngine",
+ }
+ )
+ )
+ assert hook_module.check_json_file(str(bad)) is False
+
+ def test_nested_module_path_in_json_fails(self, tmp_path):
+ """A nested JSON module_path with absolute path should fail."""
+ bad = tmp_path / "nested.json"
+ bad.write_text(
+ json.dumps(
+ {
+ "engines": {
+ "brave": {
+ "module_path": "local_deep_research.web_search_engines.engines.search_engine_brave",
+ "class_name": "BraveSearchEngine",
+ }
+ }
+ }
+ )
+ )
+ assert hook_module.check_json_file(str(bad)) is False
+
+ def test_absolute_path_in_non_module_path_key_passes(self, tmp_path):
+ """Absolute paths in non-module_path keys should NOT trigger (no false positive)."""
+ ok = tmp_path / "description.json"
+ ok.write_text(
+ json.dumps(
+ {
+ "description": "Uses local_deep_research.web_search_engines.engines.foo internally",
+ "module_path": ".engines.search_engine_brave",
+ }
+ )
+ )
+ assert hook_module.check_json_file(str(ok)) is True
+
+ def test_invalid_json_fails(self, tmp_path):
+ """Invalid JSON should fail gracefully (returns False)."""
+ bad = tmp_path / "broken.json"
+ bad.write_text("{invalid json}")
+ assert hook_module.check_json_file(str(bad)) is False
+
+ def test_legitimate_ref_in_module_path_passes(self, tmp_path):
+ """Legitimate absolute refs in module_path should pass."""
+ legit = tmp_path / "legit.json"
+ legit.write_text(
+ json.dumps(
+ {"module_path": "local_deep_research.web_search_engines"}
+ )
+ )
+ assert hook_module.check_json_file(str(legit)) is True
+
+ def test_module_path_in_list_of_dicts(self, tmp_path):
+ """Should detect absolute paths in lists of engine configs."""
+ bad = tmp_path / "engines_list.json"
+ bad.write_text(
+ json.dumps(
+ [
+ {
+ "module_path": ".engines.good",
+ "class_name": "Good",
+ },
+ {
+ "module_path": "local_deep_research.web_search_engines.engines.bad",
+ "class_name": "Bad",
+ },
+ ]
+ )
+ )
+ assert hook_module.check_json_file(str(bad)) is False