~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(hooks): use name/segment-based env-var exemptions (#3550)
LearningCircuit3bd578a54622
diff --git a/.pre-commit-hooks/check-env-vars.py b/.pre-commit-hooks/check-env-vars.pyindex 5798ead752..7677f542f8 100755--- a/.pre-commit-hooks/check-env-vars.py+++ b/.pre-commit-hooks/check-env-vars.py@@ -6,29 +6,50 @@ This is a lightweight check - comprehensive validation happens in CI.import astimport sys+from pathlib import Path+++# Allowlist entries, partitioned by matching strategy.+#+# Previously this was a single ALLOWED_PATTERNS set checked with+# `pattern in self.filename` — a bare substring match. That incorrectly+# exempted production files whose path happened to contain an allowlist+# substring: e.g. "test_" matched protest_handler.py, "settings/" matched+# foo_settings_override.py, and so on. Partition the list instead so each+# entry matches at the right granularity.++# Directory subtrees where env-var access is allowed (settings / tests /+# scripts / examples / migrations / the hooks themselves).+ALLOWED_PATH_SEGMENTS = {+ "settings",+ "config",+ "tests",+ "scripts",+ "examples",+ "migrations",+ ".pre-commit-hooks",+}++# Filename prefixes for test files.+ALLOWED_NAME_PREFIXES = ("test_",)+# Filename suffixes for Go-style *_test.py convention.+ALLOWED_NAME_SUFFIXES = ("_test.py",)-# Files/patterns where direct os.environ access is allowed-ALLOWED_PATTERNS = {- # Settings infrastructure (reads env vars to bootstrap the system)- "settings/",- "config/",- # Tests, scripts, examples (expected to use env vars freely)- "test_",- "_test.py",- "tests/",- "scripts/",- ".pre-commit-hooks/",- "examples/",- # Database migrations (run outside normal app context)- "migrations/",- # Bootstrap modules (run before SettingsManager is initialized)+# Exact basenames for bootstrap / infrastructure modules that run before+# SettingsManager is initialized.+ALLOWED_NAMES = {"log_utils.py", # Logger init before DB/SettingsManager"server_config.py", # Fail-closed security validation for LDR_APP_ALLOW_REGISTRATIONS- "security/rate_limiter.py", # Module-level RATE_LIMIT_FAIL_CLOSED at decorator time"sqlcipher_utils.py", # Encryption init needs LDR_TEST_MODE before SettingsManager}+# Path-anchored entries where the basename alone is too generic to match+# reliably.+ALLOWED_PATH_ENDINGS = (+ "security/rate_limiter.py", # Module-level RATE_LIMIT_FAIL_CLOSED at decorator time+)+# System environment variables that are always allowedSYSTEM_VARS = {"PATH",@@ -229,8 +250,17 @@ class EnvVarChecker(ast.NodeVisitor):def _is_file_allowed(self) -> bool:"""Check if this file is allowed to use os.environ directly."""- for pattern in ALLOWED_PATTERNS:- if pattern in self.filename:+ p = Path(self.filename)+ if p.name in ALLOWED_NAMES:+ return True+ if p.name.startswith(ALLOWED_NAME_PREFIXES):+ return True+ if p.name.endswith(ALLOWED_NAME_SUFFIXES):+ return True+ if ALLOWED_PATH_SEGMENTS.intersection(p.parts):+ return True+ for ending in ALLOWED_PATH_ENDINGS:+ if self.filename.endswith(ending):return Truereturn Falsediff --git a/tests/hooks/test_check_env_vars.py b/tests/hooks/test_check_env_vars.pynew file mode 100644index 0000000000..fd77d9c30b--- /dev/null+++ b/tests/hooks/test_check_env_vars.py@@ -0,0 +1,129 @@+"""+Tests for the check-env-vars pre-commit hook.++Covers regressions for the substring-based filename exemption:+- `"test_" in filepath` matched `protest_handler.py` (contains 'test_')+- `"settings/" in filepath` matched `foo_settings_override.py`+- Segment / basename / prefix / suffix matching now used instead.+"""++import subprocess+import sys+import tempfile+from pathlib import Path+++HOOK_SCRIPT = (+ Path(__file__).parent.parent.parent+ / ".pre-commit-hooks"+ / "check-env-vars.py"+)+++def _run_hook(+ content: str, filename: str = "service.py"+) -> subprocess.CompletedProcess:+ with tempfile.TemporaryDirectory() as d:+ path = Path(d) / filename+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(content)+ return subprocess.run(+ [sys.executable, str(HOOK_SCRIPT), str(path)],+ capture_output=True,+ text=True,+ )+++VIOLATION = 'import os\nx = os.environ.get("LDR_FOO")\n'+++class TestSubstringExemptionBugFixed:+ """Production files whose paths merely contain an allowlist substring+ must no longer be silently exempted."""++ def test_protest_handler_scanned(self):+ """'protest_handler.py' contains substring 'test_'."""+ result = _run_hook(VIOLATION, "protest_handler.py")+ assert result.returncode == 1+ assert "LDR_FOO" in result.stdout++ def test_foo_settings_override_scanned(self):+ """'foo_settings_override.py' contains substring 'settings/' is+ false, but 'foo_settings.py' would have matched 'settings' as a+ bare string if we weren't segment-anchored. Use a path where+ 'settings' is part of the basename, not a directory segment."""+ result = _run_hook(VIOLATION, "foo_settings.py")+ assert result.returncode == 1++ def test_scriptlike_basename_scanned(self):+ """A basename containing 'scripts' is not a scripts/ directory."""+ result = _run_hook(VIOLATION, "typescripts_loader.py")+ assert result.returncode == 1+++class TestRealExemptionsStillApply:+ """All the genuine exemption cases must still work."""++ def test_settings_directory_exempt(self):+ result = _run_hook(VIOLATION, "src/settings/foo.py")+ assert result.returncode == 0++ def test_tests_directory_exempt(self):+ result = _run_hook(VIOLATION, "tests/helpers.py")+ assert result.returncode == 0++ def test_test_prefix_exempt(self):+ result = _run_hook(VIOLATION, "test_foo.py")+ assert result.returncode == 0++ def test_underscore_test_suffix_exempt(self):+ """Go-style *_test.py — previously this was matched as a bare+ substring which happened to work, but now is handled explicitly."""+ result = _run_hook(VIOLATION, "foo_test.py")+ assert result.returncode == 0++ def test_migrations_directory_exempt(self):+ result = _run_hook(VIOLATION, "migrations/0001_init.py")+ assert result.returncode == 0++ def test_scripts_directory_exempt(self):+ result = _run_hook(VIOLATION, "scripts/bootstrap.py")+ assert result.returncode == 0++ def test_examples_directory_exempt(self):+ result = _run_hook(VIOLATION, "examples/demo.py")+ assert result.returncode == 0++ def test_log_utils_exempt(self):+ result = _run_hook(VIOLATION, "log_utils.py")+ assert result.returncode == 0++ def test_sqlcipher_utils_exempt(self):+ result = _run_hook(VIOLATION, "sqlcipher_utils.py")+ assert result.returncode == 0++ def test_server_config_exempt(self):+ result = _run_hook(VIOLATION, "server_config.py")+ assert result.returncode == 0++ def test_security_rate_limiter_exempt(self):+ """Path-anchored entry: 'security/rate_limiter.py'."""+ result = _run_hook(VIOLATION, "security/rate_limiter.py")+ assert result.returncode == 0+++class TestBareRateLimiterStillFlagged:+ """A file literally named rate_limiter.py at a different path must+ NOT be exempt (only the security/ one is)."""++ def test_rate_limiter_outside_security_flagged(self):+ result = _run_hook(VIOLATION, "other/rate_limiter.py")+ assert result.returncode == 1+++class TestRealViolation:+ """Sanity check — normal production files are still flagged."""++ def test_production_module_flagged(self):+ result = _run_hook(VIOLATION, "service.py")+ assert result.returncode == 1