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.

test: add 250 high-value tests across 8 modules (round 10) (#2586)

LearningCircuitd84687f95381
diff --git a/tests/library/download_management/test_failure_classifier_high_value.py b/tests/library/download_management/test_failure_classifier_high_value.py
new file mode 100644
index 0000000000..7fe4a6ab38
--- /dev/null
+++ b/tests/library/download_management/test_failure_classifier_high_value.py
@@ -0,0 +1,277 @@
+"""High-value tests for library/download_management/failure_classifier.py."""
+
+from datetime import timedelta, datetime
+
+
+from local_deep_research.library.download_management.failure_classifier import (
+ PermanentFailure,
+ TemporaryFailure,
+ RateLimitFailure,
+ FailureClassifier,
+)
+
+
+# ---------------------------------------------------------------------------
+# BaseFailure / PermanentFailure
+# ---------------------------------------------------------------------------
+
+
+class TestPermanentFailure:
+ """PermanentFailure behavior."""
+
+ def test_is_permanent(self):
+ f = PermanentFailure("not_found", "Gone")
+ assert f.is_permanent() is True
+
+ def test_can_never_retry(self):
+ f = PermanentFailure("not_found", "Gone")
+ assert f.can_retry_now() is False
+
+ def test_cooldown_remaining_is_none(self):
+ f = PermanentFailure("forbidden", "No access")
+ assert f.get_cooldown_remaining() is None
+
+ def test_to_dict_fields(self):
+ f = PermanentFailure("not_found", "Resource not found")
+ d = f.to_dict()
+ assert d["error_type"] == "not_found"
+ assert d["message"] == "Resource not found"
+ assert d["is_permanent"] is True
+ assert d["retry_after_timestamp"] is None
+ assert isinstance(d["created_at"], datetime)
+
+ def test_error_type_stored(self):
+ f = PermanentFailure("gone", "Permanently removed")
+ assert f.error_type == "gone"
+
+ def test_message_stored(self):
+ f = PermanentFailure("gone", "Permanently removed")
+ assert f.message == "Permanently removed"
+
+
+# ---------------------------------------------------------------------------
+# TemporaryFailure
+# ---------------------------------------------------------------------------
+
+
+class TestTemporaryFailure:
+ """TemporaryFailure with cooldown."""
+
+ def test_not_permanent(self):
+ f = TemporaryFailure("timeout", "Timed out", timedelta(minutes=30))
+ assert f.is_permanent() is False
+
+ def test_cannot_retry_immediately(self):
+ f = TemporaryFailure("timeout", "Timed out", timedelta(hours=1))
+ assert f.can_retry_now() is False
+
+ def test_can_retry_after_cooldown(self):
+ f = TemporaryFailure("timeout", "Timed out", timedelta(seconds=0))
+ assert f.can_retry_now() is True
+
+ def test_cooldown_remaining_positive(self):
+ f = TemporaryFailure("error", "err", timedelta(hours=2))
+ remaining = f.get_cooldown_remaining()
+ assert remaining is not None
+ assert remaining > timedelta(0)
+
+ def test_cooldown_remaining_none_after_expiry(self):
+ f = TemporaryFailure("error", "err", timedelta(seconds=0))
+ assert f.get_cooldown_remaining() is None
+
+ def test_to_dict_has_retry_timestamp(self):
+ f = TemporaryFailure("timeout", "t", timedelta(hours=1))
+ d = f.to_dict()
+ assert d["is_permanent"] is False
+ assert d["retry_after_timestamp"] is not None
+ assert isinstance(d["retry_after_timestamp"], datetime)
+
+ def test_retry_after_stored(self):
+ cooldown = timedelta(minutes=30)
+ f = TemporaryFailure("timeout", "t", cooldown)
+ assert f.retry_after == cooldown
+
+
+# ---------------------------------------------------------------------------
+# RateLimitFailure
+# ---------------------------------------------------------------------------
+
+
+class TestRateLimitFailure:
+ """Domain-specific rate limit cooldowns."""
+
+ def test_arxiv_6h_cooldown(self):
+ f = RateLimitFailure("arxiv.org")
+ assert f.retry_after == timedelta(hours=6)
+
+ def test_pubmed_2h_cooldown(self):
+ f = RateLimitFailure("pubmed.ncbi.nlm.nih.gov")
+ assert f.retry_after == timedelta(hours=2)
+
+ def test_biorxiv_6h_cooldown(self):
+ f = RateLimitFailure("biorxiv.org")
+ assert f.retry_after == timedelta(hours=6)
+
+ def test_semantic_scholar_4h_cooldown(self):
+ f = RateLimitFailure("semanticscholar.org")
+ assert f.retry_after == timedelta(hours=4)
+
+ def test_researchgate_12h_cooldown(self):
+ f = RateLimitFailure("researchgate.net")
+ assert f.retry_after == timedelta(hours=12)
+
+ def test_unknown_domain_1h_default(self):
+ f = RateLimitFailure("random-site.com")
+ assert f.retry_after == timedelta(hours=1)
+
+ def test_error_type_is_rate_limited(self):
+ f = RateLimitFailure("arxiv.org")
+ assert f.error_type == "rate_limited"
+
+ def test_domain_stored(self):
+ f = RateLimitFailure("arxiv.org")
+ assert f.domain == "arxiv.org"
+
+ def test_details_in_message(self):
+ f = RateLimitFailure("arxiv.org", "Too many requests")
+ assert "Too many requests" in f.message
+
+ def test_is_not_permanent(self):
+ f = RateLimitFailure("arxiv.org")
+ assert f.is_permanent() is False
+
+
+# ---------------------------------------------------------------------------
+# FailureClassifier.classify_failure()
+# ---------------------------------------------------------------------------
+
+
+class TestClassifyFailureHTTPStatus:
+ """HTTP status code classification."""
+
+ def setup_method(self):
+ self.classifier = FailureClassifier()
+
+ def test_404_permanent(self):
+ f = self.classifier.classify_failure("http_error", status_code=404)
+ assert isinstance(f, PermanentFailure)
+ assert f.error_type == "not_found"
+
+ def test_403_permanent(self):
+ f = self.classifier.classify_failure("http_error", status_code=403)
+ assert isinstance(f, PermanentFailure)
+ assert f.error_type == "forbidden"
+
+ def test_410_permanent(self):
+ f = self.classifier.classify_failure("http_error", status_code=410)
+ assert isinstance(f, PermanentFailure)
+ assert f.error_type == "gone"
+
+ def test_429_rate_limit(self):
+ f = self.classifier.classify_failure(
+ "http_error", status_code=429, url="https://arxiv.org/pdf/1234"
+ )
+ assert isinstance(f, RateLimitFailure)
+ assert f.domain == "arxiv.org"
+
+ def test_503_temporary(self):
+ f = self.classifier.classify_failure("http_error", status_code=503)
+ assert isinstance(f, TemporaryFailure)
+ assert f.error_type == "server_error"
+
+
+class TestClassifyFailurePatterns:
+ """Error message pattern classification."""
+
+ def setup_method(self):
+ self.classifier = FailureClassifier()
+
+ def test_arxiv_recaptcha_3_day_cooldown(self):
+ f = self.classifier.classify_failure(
+ "arxiv_error", details="reCAPTCHA challenge detected"
+ )
+ assert isinstance(f, TemporaryFailure)
+ assert f.retry_after == timedelta(days=3)
+
+ def test_timeout_30_min_cooldown(self):
+ f = self.classifier.classify_failure("timeout")
+ assert isinstance(f, TemporaryFailure)
+ assert f.retry_after == timedelta(minutes=30)
+
+ def test_network_error_5_min_cooldown(self):
+ f = self.classifier.classify_failure("network_error")
+ assert isinstance(f, TemporaryFailure)
+ assert f.retry_after == timedelta(minutes=5)
+
+ def test_connection_error_5_min(self):
+ f = self.classifier.classify_failure("connection_error")
+ assert isinstance(f, TemporaryFailure)
+ assert f.retry_after == timedelta(minutes=5)
+
+ def test_unknown_defaults_to_1h_temporary(self):
+ f = self.classifier.classify_failure("something_weird")
+ assert isinstance(f, TemporaryFailure)
+ assert f.retry_after == timedelta(hours=1)
+
+ def test_arxiv_not_pdf_permanent(self):
+ f = self.classifier.classify_failure(
+ "arxiv_error", details="Not a PDF file"
+ )
+ assert isinstance(f, PermanentFailure)
+
+ def test_arxiv_html_instead_of_pdf_permanent(self):
+ f = self.classifier.classify_failure(
+ "arxiv_error", details="Received HTML content instead of PDF"
+ )
+ assert isinstance(f, PermanentFailure)
+ assert f.error_type == "incompatible_format"
+
+ def test_429_empty_url_unknown_domain(self):
+ f = self.classifier.classify_failure(
+ "http_error", status_code=429, url=""
+ )
+ assert isinstance(f, RateLimitFailure)
+ assert f.domain == "unknown"
+ assert f.retry_after == timedelta(hours=1)
+
+ def test_arxiv_html_with_pdf_content_type_not_permanent(self):
+ """The application/pdf guard prevents HTML detection from firing."""
+ f = self.classifier.classify_failure(
+ "arxiv_error", details="html content; application/pdf"
+ )
+ assert not isinstance(f, PermanentFailure)
+
+ def test_500_default_temporary(self):
+ f = self.classifier.classify_failure("http_error", status_code=500)
+ assert isinstance(f, TemporaryFailure)
+ assert f.retry_after == timedelta(hours=1)
+
+
+# ---------------------------------------------------------------------------
+# classify_from_exception()
+# ---------------------------------------------------------------------------
+
+
+class TestClassifyFromException:
+ """Exception-based classification."""
+
+ def setup_method(self):
+ self.classifier = FailureClassifier()
+
+ def test_timeout_exception(self):
+ exc = TimeoutError("Request timed out")
+ f = self.classifier.classify_from_exception(exc)
+ assert isinstance(f, TemporaryFailure)
+ assert f.retry_after == timedelta(minutes=30)
+
+ def test_connection_error(self):
+ exc = ConnectionError("Connection refused")
+ f = self.classifier.classify_from_exception(exc)
+ assert isinstance(f, TemporaryFailure)
+ assert f.retry_after == timedelta(minutes=5)
+
+ def test_generic_exception_unknown(self):
+ exc = RuntimeError("Something broke")
+ f = self.classifier.classify_from_exception(exc)
+ assert isinstance(f, TemporaryFailure)
+ assert f.retry_after == timedelta(hours=1)
diff --git a/tests/library/download_management/test_retry_manager_high_value.py b/tests/library/download_management/test_retry_manager_high_value.py
new file mode 100644
index 0000000000..13b9cb468f
--- /dev/null
+++ b/tests/library/download_management/test_retry_manager_high_value.py
@@ -0,0 +1,172 @@
+"""High-value tests for library/download_management/retry_manager.py - Pure logic."""
+
+from datetime import timedelta
+
+
+from local_deep_research.library.download_management.retry_manager import (
+ RetryDecision,
+ ResourceFilterResult,
+ FilterSummary,
+)
+
+
+# ---------------------------------------------------------------------------
+# RetryDecision dataclass
+# ---------------------------------------------------------------------------
+
+
+class TestRetryDecision:
+ """RetryDecision dataclass fields."""
+
+ def test_can_retry_true(self):
+ d = RetryDecision(can_retry=True)
+ assert d.can_retry is True
+ assert d.reason is None
+ assert d.estimated_wait_time is None
+
+ def test_can_retry_false_with_reason(self):
+ d = RetryDecision(can_retry=False, reason="permanently failed")
+ assert d.can_retry is False
+ assert d.reason == "permanently failed"
+
+ def test_with_estimated_wait(self):
+ wait = timedelta(hours=2)
+ d = RetryDecision(
+ can_retry=False, reason="cooldown", estimated_wait_time=wait
+ )
+ assert d.estimated_wait_time == wait
+
+
+# ---------------------------------------------------------------------------
+# ResourceFilterResult
+# ---------------------------------------------------------------------------
+
+
+class TestResourceFilterResult:
+ """ResourceFilterResult initialization and fields."""
+
+ def test_basic_fields(self):
+ r = ResourceFilterResult(
+ resource_id=42, can_retry=True, status="available"
+ )
+ assert r.resource_id == 42
+ assert r.can_retry is True
+ assert r.status == "available"
+ assert r.reason == ""
+ assert r.estimated_wait is None
+
+ def test_with_reason_and_wait(self):
+ wait = timedelta(minutes=30)
+ r = ResourceFilterResult(
+ resource_id=1,
+ can_retry=False,
+ status="temporarily_failed",
+ reason="cooldown active",
+ estimated_wait=wait,
+ )
+ assert r.reason == "cooldown active"
+ assert r.estimated_wait == wait
+
+
+# ---------------------------------------------------------------------------
+# FilterSummary
+# ---------------------------------------------------------------------------
+
+
+class TestFilterSummary:
+ """FilterSummary counting logic."""
+
+ def test_initial_counts_zero(self):
+ s = FilterSummary()
+ assert s.total_count == 0
+ assert s.downloadable_count == 0
+ assert s.permanently_failed_count == 0
+ assert s.temporarily_failed_count == 0
+ assert s.available_count == 0
+ assert s.failure_type_counts == {}
+
+ def test_add_downloadable(self):
+ s = FilterSummary()
+ r = ResourceFilterResult(1, can_retry=True, status="available")
+ s.add_result(r)
+ assert s.total_count == 1
+ assert s.downloadable_count == 1
+ assert s.permanently_failed_count == 0
+
+ def test_add_permanently_failed(self):
+ s = FilterSummary()
+ r = ResourceFilterResult(
+ 1, can_retry=False, status="permanently_failed"
+ )
+ s.add_result(r)
+ assert s.total_count == 1
+ assert s.permanently_failed_count == 1
+ assert s.downloadable_count == 0
+
+ def test_add_temporarily_failed(self):
+ s = FilterSummary()
+ r = ResourceFilterResult(
+ 1, can_retry=False, status="temporarily_failed"
+ )
+ s.add_result(r)
+ assert s.total_count == 1
+ assert s.temporarily_failed_count == 1
+
+ def test_add_unrecognized_status_falls_to_available_counter(self):
+ s = FilterSummary()
+ r = ResourceFilterResult(1, can_retry=False, status="unavailable")
+ s.add_result(r)
+ assert s.available_count == 1
+
+ def test_can_retry_true_with_temporarily_failed_status_counts_downloadable(
+ self,
+ ):
+ s = FilterSummary()
+ r = ResourceFilterResult(1, can_retry=True, status="temporarily_failed")
+ s.add_result(r)
+ assert s.downloadable_count == 1
+ assert s.temporarily_failed_count == 0
+
+ def test_multiple_results(self):
+ s = FilterSummary()
+ s.add_result(
+ ResourceFilterResult(1, can_retry=True, status="available")
+ )
+ s.add_result(
+ ResourceFilterResult(2, can_retry=True, status="available")
+ )
+ s.add_result(
+ ResourceFilterResult(
+ 3, can_retry=False, status="permanently_failed"
+ )
+ )
+ s.add_result(
+ ResourceFilterResult(
+ 4, can_retry=False, status="temporarily_failed"
+ )
+ )
+ s.add_result(
+ ResourceFilterResult(5, can_retry=False, status="unavailable")
+ )
+
+ assert s.total_count == 5
+ assert s.downloadable_count == 2
+ assert s.permanently_failed_count == 1
+ assert s.temporarily_failed_count == 1
+ assert s.available_count == 1
+
+ def test_to_dict(self):
+ s = FilterSummary()
+ s.add_result(
+ ResourceFilterResult(1, can_retry=True, status="available")
+ )
+ s.add_result(
+ ResourceFilterResult(2, can_retry=False, status="unavailable")
+ )
+ d = s.to_dict()
+ assert d["total_count"] == 2
+ assert d["downloadable_count"] == 1
+ assert d["permanently_failed_count"] == 0
+ assert d["temporarily_failed_count"] == 0
+ assert d["available_count"] == 1
+ assert d["failure_type_counts"] == {}
diff --git a/tests/security/test_data_sanitizer_high_value.py b/tests/security/test_data_sanitizer_high_value.py
new file mode 100644
index 0000000000..f1ff2d47a5
--- /dev/null
+++ b/tests/security/test_data_sanitizer_high_value.py
@@ -0,0 +1,294 @@
+"""High-value tests for security/data_sanitizer.py - Data Sanitization."""
+
+import json
+
+
+from local_deep_research.security.data_sanitizer import (
+ DataSanitizer,
+ sanitize_data,
+ redact_data,
+ filter_research_metadata,
+ strip_settings_snapshot,
+)
+
+
+# ---------------------------------------------------------------------------
+# DataSanitizer.sanitize()
+# ---------------------------------------------------------------------------
+
+
+class TestSanitizeBasic:
+ """Basic sanitize behavior."""
+
+ def test_removes_api_key(self):
+ result = DataSanitizer.sanitize(
+ {"username": "bob", "api_key": "secret"}
+ )
+ assert result == {"username": "bob"}
+
+ def test_removes_password(self):
+ result = DataSanitizer.sanitize({"password": "pass123", "name": "x"})
+ assert result == {"name": "x"}
+
+ def test_removes_multiple_sensitive_keys(self):
+ data = {"api_key": "k", "secret": "s", "safe": "v"}
+ result = DataSanitizer.sanitize(data)
+ assert result == {"safe": "v"}
+
+ def test_case_insensitive_removal(self):
+ data = {"API_KEY": "k", "Password": "p", "name": "n"}
+ result = DataSanitizer.sanitize(data)
+ assert result == {"name": "n"}
+
+ def test_primitive_passthrough_string(self):
+ assert DataSanitizer.sanitize("hello") == "hello"
+
+ def test_primitive_passthrough_int(self):
+ assert DataSanitizer.sanitize(42) == 42
+
+ def test_primitive_passthrough_none(self):
+ assert DataSanitizer.sanitize(None) is None
+
+ def test_empty_dict(self):
+ assert DataSanitizer.sanitize({}) == {}
+
+ def test_empty_list(self):
+ assert DataSanitizer.sanitize([]) == []
+
+
+class TestSanitizeRecursive:
+ """Recursive sanitization through nested structures."""
+
+ def test_nested_dict(self):
+ data = {"outer": {"api_key": "secret", "value": 1}}
+ result = DataSanitizer.sanitize(data)
+ assert result == {"outer": {"value": 1}}
+
+ def test_deeply_nested(self):
+ data = {"a": {"b": {"c": {"password": "p", "data": "d"}}}}
+ result = DataSanitizer.sanitize(data)
+ assert result == {"a": {"b": {"c": {"data": "d"}}}}
+
+ def test_list_of_dicts(self):
+ data = [{"api_key": "k1", "name": "a"}, {"api_key": "k2", "name": "b"}]
+ result = DataSanitizer.sanitize(data)
+ assert result == [{"name": "a"}, {"name": "b"}]
+
+ def test_dict_with_list_of_dicts(self):
+ data = {"items": [{"secret": "s", "id": 1}]}
+ result = DataSanitizer.sanitize(data)
+ assert result == {"items": [{"id": 1}]}
+
+ def test_list_of_primitives_unchanged(self):
+ assert DataSanitizer.sanitize([1, 2, 3]) == [1, 2, 3]
+
+
+class TestSanitizeCustomKeys:
+ """Custom sensitive_keys parameter."""
+
+ def test_custom_keys_only(self):
+ data = {"api_key": "keep", "custom_secret": "remove", "name": "n"}
+ result = DataSanitizer.sanitize(data, sensitive_keys={"custom_secret"})
+ assert result == {"api_key": "keep", "name": "n"}
+
+ def test_custom_keys_case_insensitive(self):
+ data = {"MY_TOKEN": "t", "name": "n"}
+ result = DataSanitizer.sanitize(data, sensitive_keys={"my_token"})
+ assert result == {"name": "n"}
+
+
+# ---------------------------------------------------------------------------
+# DataSanitizer.redact()
+# ---------------------------------------------------------------------------
+
+
+class TestRedactBasic:
+ """Basic redact behavior."""
+
+ def test_replaces_with_redacted(self):
+ data = {"api_key": "secret", "name": "bob"}
+ result = DataSanitizer.redact(data)
+ assert result == {"api_key": "[REDACTED]", "name": "bob"}
+
+ def test_case_insensitive(self):
+ result = DataSanitizer.redact({"PASSWORD": "p", "x": 1})
+ assert result == {"PASSWORD": "[REDACTED]", "x": 1}
+
+ def test_custom_redaction_text(self):
+ result = DataSanitizer.redact({"api_key": "k"}, redaction_text="***")
+ assert result == {"api_key": "***"}
+
+ def test_primitive_passthrough(self):
+ assert DataSanitizer.redact("hello") == "hello"
+ assert DataSanitizer.redact(42) == 42
+ assert DataSanitizer.redact(None) is None
+
+
+class TestRedactRecursive:
+ """Recursive redaction."""
+
+ def test_nested_dict_redaction(self):
+ data = {"outer": {"password": "secret", "value": 1}}
+ result = DataSanitizer.redact(data)
+ assert result == {"outer": {"password": "[REDACTED]", "value": 1}}
+
+ def test_list_of_dicts_redaction(self):
+ data = [{"secret": "s1", "id": 1}, {"secret": "s2", "id": 2}]
+ result = DataSanitizer.redact(data)
+ assert result == [
+ {"secret": "[REDACTED]", "id": 1},
+ {"secret": "[REDACTED]", "id": 2},
+ ]
+
+ def test_list_passthrough(self):
+ assert DataSanitizer.redact([1, "two", 3]) == [1, "two", 3]
+
+
+class TestRedactNonPrimitiveValue:
+ """Redact replaces the value wholesale, even if it's a nested structure."""
+
+ def test_nested_dict_value_replaced_not_recursed(self):
+ data = {"api_key": {"nested": "data"}}
+ result = DataSanitizer.redact(data)
+ assert result == {"api_key": "[REDACTED]"}
+
+
+class TestRedactCustomKeys:
+ """Custom sensitive_keys for redact."""
+
+ def test_custom_keys(self):
+ data = {"api_key": "keep", "my_field": "redact"}
+ result = DataSanitizer.redact(data, sensitive_keys={"my_field"})
+ assert result == {"api_key": "keep", "my_field": "[REDACTED]"}
+
+
+# ---------------------------------------------------------------------------
+# Convenience functions
+# ---------------------------------------------------------------------------
+
+
+class TestConvenienceFunctions:
+ def test_sanitize_data_delegates(self):
+ data = {"api_key": "k", "name": "n"}
+ assert sanitize_data(data) == {"name": "n"}
+
+ def test_redact_data_delegates(self):
+ data = {"password": "p", "name": "n"}
+ result = redact_data(data)
+ assert result == {"password": "[REDACTED]", "name": "n"}
+
+ def test_redact_data_custom_text(self):
+ result = redact_data({"api_key": "k"}, redaction_text="HIDDEN")
+ assert result == {"api_key": "HIDDEN"}
+
+
+# ---------------------------------------------------------------------------
+# filter_research_metadata()
+# ---------------------------------------------------------------------------
+
+
+class TestFilterResearchMetadata:
+ """filter_research_metadata extracts only safe fields."""
+
+ def test_dict_with_is_news_search_true(self):
+ result = filter_research_metadata(
+ {"is_news_search": True, "settings_snapshot": {"api_key": "x"}}
+ )
+ assert result == {"is_news_search": True}
+
+ def test_dict_with_is_news_search_false(self):
+ result = filter_research_metadata({"is_news_search": False})
+ assert result == {"is_news_search": False}
+
+ def test_dict_missing_is_news_search(self):
+ result = filter_research_metadata({"other": "stuff"})
+ assert result == {"is_news_search": False}
+
+ def test_json_string_input(self):
+ result = filter_research_metadata('{"is_news_search": true}')
+ assert result == {"is_news_search": True}
+
+ def test_none_input(self):
+ result = filter_research_metadata(None)
+ assert result == {"is_news_search": False}
+
+ def test_non_dict_input(self):
+ result = filter_research_metadata([1, 2, 3])
+ assert result == {"is_news_search": False}
+
+ def test_invalid_json_string(self):
+ result = filter_research_metadata("{bad json")
+ assert result == {"is_news_search": False}
+
+ def test_empty_dict(self):
+ result = filter_research_metadata({})
+ assert result == {"is_news_search": False}
+
+ def test_int_truthy_coerced_to_bool(self):
+ result = filter_research_metadata({"is_news_search": 1})
+ assert result == {"is_news_search": True}
+ assert type(result["is_news_search"]) is bool
+
+ def test_string_truthy_coerced_to_bool(self):
+ result = filter_research_metadata({"is_news_search": "yes"})
+ assert result == {"is_news_search": True}
+
+ def test_json_string_non_dict_returns_default(self):
+ """JSON string that parses to a list exercises the not-isinstance(meta, dict) branch."""
+ result = filter_research_metadata("[1, 2]")
+ assert result == {"is_news_search": False}
+
+
+# ---------------------------------------------------------------------------
+# strip_settings_snapshot()
+# ---------------------------------------------------------------------------
+
+
+class TestStripSettingsSnapshot:
+ """strip_settings_snapshot removes settings_snapshot key."""
+
+ def test_removes_settings_snapshot(self):
+ data = {
+ "phase": "done",
+ "settings_snapshot": {"api_key": "x"},
+ "duration": 5,
+ }
+ result = strip_settings_snapshot(data)
+ assert result == {"phase": "done", "duration": 5}
+
+ def test_preserves_other_keys(self):
+ data = {"phase": "done", "error_type": None, "mode": "quick"}
+ result = strip_settings_snapshot(data)
+ assert result == data
+
+ def test_json_string_input(self):
+ data = json.dumps({"settings_snapshot": {}, "phase": "done"})
+ result = strip_settings_snapshot(data)
+ assert result == {"phase": "done"}
+
+ def test_none_input(self):
+ assert strip_settings_snapshot(None) == {}
+
+ def test_non_dict_input(self):
+ assert strip_settings_snapshot(42) == {}
+
+ def test_invalid_json(self):
+ assert strip_settings_snapshot("{invalid") == {}
+
+ def test_nested_settings_snapshot_survives(self):
+ data = {
+ "results": {"settings_snapshot": {"key": "val"}},
+ "phase": "done",
+ }
+ result = strip_settings_snapshot(data)
+ assert result == {
+ "results": {"settings_snapshot": {"key": "val"}},
+ "phase": "done",
+ }
+
+ def test_json_string_non_dict_returns_empty(self):
+ """JSON string that parses to a list exercises the not-isinstance branch."""
+ assert strip_settings_snapshot("[1, 2]") == {}
+
+ def test_empty_dict(self):
+ assert strip_settings_snapshot({}) == {}
diff --git a/tests/security/test_module_whitelist_high_value.py b/tests/security/test_module_whitelist_high_value.py
new file mode 100644
index 0000000000..1a8cdd3bd7
--- /dev/null
+++ b/tests/security/test_module_whitelist_high_value.py
@@ -0,0 +1,236 @@
+"""High-value tests for security/module_whitelist.py - Module Import Security."""
+
+from unittest.mock import patch, MagicMock
+
+import pytest
+
+from local_deep_research.security.module_whitelist import (
+ validate_module_import,
+ get_safe_module_class,
+ ALLOWED_MODULE_PATHS,
+ ALLOWED_CLASS_NAMES,
+ ALLOWED_MODULES,
+ SecurityError,
+ ModuleNotAllowedError,
+)
+
+
+# ---------------------------------------------------------------------------
+# ALLOWED_MODULE_PATHS constraints
+# ---------------------------------------------------------------------------
+
+
+class TestAllowedModulePaths:
+ """Whitelist structure validation."""
+
+ def test_is_frozenset(self):
+ assert isinstance(ALLOWED_MODULE_PATHS, frozenset)
+
+ def test_all_start_with_dot(self):
+ for path in ALLOWED_MODULE_PATHS:
+ assert path.startswith("."), (
+ f"Module path {path!r} must start with '.'"
+ )
+
+ def test_legacy_alias_same_object(self):
+ assert ALLOWED_MODULES is ALLOWED_MODULE_PATHS
+
+ def test_known_engine_paths_present(self):
+ expected = [
+ ".engines.search_engine_brave",
+ ".engines.search_engine_ddg",
+ ".engines.search_engine_arxiv",
+ ".engines.search_engine_wikipedia",
+ ".engines.search_engine_tavily",
+ ]
+ for path in expected:
+ assert path in ALLOWED_MODULE_PATHS
+
+ def test_not_empty(self):
+ assert len(ALLOWED_MODULE_PATHS) > 0
+
+
+# ---------------------------------------------------------------------------
+# ALLOWED_CLASS_NAMES constraints
+# ---------------------------------------------------------------------------
+
+
+class TestAllowedClassNames:
+ """Class name whitelist validation."""
+
+ def test_is_frozenset(self):
+ assert isinstance(ALLOWED_CLASS_NAMES, frozenset)
+
+ def test_known_classes_present(self):
+ expected = [
+ "BraveSearchEngine",
+ "DuckDuckGoSearchEngine",
+ "ArXivSearchEngine",
+ "WikipediaSearchEngine",
+ "TavilySearchEngine",
+ "BaseSearchEngine",
+ ]
+ for cls_name in expected:
+ assert cls_name in ALLOWED_CLASS_NAMES
+
+ def test_not_empty(self):
+ assert len(ALLOWED_CLASS_NAMES) > 0
+
+
+# ---------------------------------------------------------------------------
+# SecurityError / ModuleNotAllowedError
+# ---------------------------------------------------------------------------
+
+
+class TestSecurityError:
+ def test_is_exception(self):
+ assert issubclass(SecurityError, Exception)
+
+ def test_alias_is_same_class(self):
+ assert ModuleNotAllowedError is SecurityError
+
+ def test_can_raise_and_catch(self):
+ with pytest.raises(SecurityError):
+ raise SecurityError("blocked")
+
+
+# ---------------------------------------------------------------------------
+# validate_module_import()
+# ---------------------------------------------------------------------------
+
+
+class TestValidateModuleImport:
+ """Module + class pair validation."""
+
+ def test_valid_pair_accepted(self):
+ assert (
+ validate_module_import(
+ ".engines.search_engine_brave", "BraveSearchEngine"
+ )
+ is True
+ )
+
+ def test_non_relative_path_rejected(self):
+ assert validate_module_import("os", "system") is False
+
+ def test_absolute_dotted_path_rejected(self):
+ assert (
+ validate_module_import(
+ "local_deep_research.web_search_engines.engines.search_engine_brave",
+ "BraveSearchEngine",
+ )
+ is False
+ )
+
+ def test_empty_module_rejected(self):
+ assert validate_module_import("", "BraveSearchEngine") is False
+
+ def test_empty_class_rejected(self):
+ assert (
+ validate_module_import(".engines.search_engine_brave", "") is False
+ )
+
+ def test_both_empty_rejected(self):
+ assert validate_module_import("", "") is False
+
+ def test_unlisted_module_rejected(self):
+ assert (
+ validate_module_import(
+ ".engines.search_engine_evil", "BraveSearchEngine"
+ )
+ is False
+ )
+
+ def test_unlisted_class_rejected(self):
+ assert (
+ validate_module_import(".engines.search_engine_brave", "EvilEngine")
+ is False
+ )
+
+ def test_both_unlisted_rejected(self):
+ assert validate_module_import(".evil_module", "EvilClass") is False
+
+
+# ---------------------------------------------------------------------------
+# get_safe_module_class()
+# ---------------------------------------------------------------------------
+
+
+class TestGetSafeModuleClass:
+ """Safe dynamic import."""
+
+ def test_invalid_module_raises_security_error(self):
+ with pytest.raises(
+ SecurityError, match="not in the security whitelist"
+ ):
+ get_safe_module_class("os", "system")
+
+ def test_invalid_class_raises_security_error(self):
+ with pytest.raises(
+ SecurityError, match="not in the security whitelist"
+ ):
+ get_safe_module_class(".engines.search_engine_brave", "EvilClass")
+
+ def test_whitelisted_class_non_whitelisted_module_rejected(self):
+ """Whitelisted class name with non-whitelisted module still raises."""
+ with pytest.raises(
+ SecurityError, match="not in the security whitelist"
+ ):
+ get_safe_module_class(
+ ".engines.search_engine_evil", "BraveSearchEngine"
+ )
+
+ @patch(
+ "local_deep_research.security.module_whitelist.importlib.import_module"
+ )
+ def test_valid_pair_imports_and_returns_class(self, mock_import):
+ mock_module = MagicMock()
+ mock_module.BraveSearchEngine = type("BraveSearchEngine", (), {})
+ mock_import.return_value = mock_module
+
+ cls = get_safe_module_class(
+ ".engines.search_engine_brave", "BraveSearchEngine"
+ )
+ assert cls is mock_module.BraveSearchEngine
+ mock_import.assert_called_once_with(
+ ".engines.search_engine_brave",
+ package="local_deep_research.web_search_engines",
+ )
+
+ @patch(
+ "local_deep_research.security.module_whitelist.importlib.import_module"
+ )
+ def test_custom_package_used(self, mock_import):
+ mock_module = MagicMock()
+ mock_module.BraveSearchEngine = type("BraveSearchEngine", (), {})
+ mock_import.return_value = mock_module
+
+ get_safe_module_class(
+ ".engines.search_engine_brave",
+ "BraveSearchEngine",
+ package="custom.package",
+ )
+ mock_import.assert_called_once_with(
+ ".engines.search_engine_brave", package="custom.package"
+ )
+
+ @patch(
+ "local_deep_research.security.module_whitelist.importlib.import_module"
+ )
+ def test_module_not_found_propagates(self, mock_import):
+ mock_import.side_effect = ModuleNotFoundError("No module")
+ with pytest.raises(ModuleNotFoundError):
+ get_safe_module_class(
+ ".engines.search_engine_brave", "BraveSearchEngine"
+ )
+
+ @patch(
+ "local_deep_research.security.module_whitelist.importlib.import_module"
+ )
+ def test_attribute_error_propagates(self, mock_import):
+ mock_module = MagicMock(spec=[]) # no attributes
+ mock_import.return_value = mock_module
+ with pytest.raises(AttributeError):
+ get_safe_module_class(
+ ".engines.search_engine_brave", "BraveSearchEngine"
+ )
diff --git a/tests/security/test_path_validator_high_value.py b/tests/security/test_path_validator_high_value.py
new file mode 100644
index 0000000000..7b1649a9a7
--- /dev/null
+++ b/tests/security/test_path_validator_high_value.py
@@ -0,0 +1,276 @@
+"""High-value tests for security/path_validator.py - Path Validation."""
+
+from pathlib import Path
+
+import pytest
+
+from local_deep_research.security.path_validator import PathValidator
+
+
+# ---------------------------------------------------------------------------
+# validate_safe_path()
+# ---------------------------------------------------------------------------
+
+
+class TestValidateSafePath:
+ """Safe path validation with base directory containment."""
+
+ def test_null_bytes_rejected(self, tmp_path):
+ with pytest.raises(ValueError, match="[Nn]ull"):
+ PathValidator.validate_safe_path("file\x00.txt", tmp_path)
+
+ def test_traversal_blocked(self, tmp_path):
+ with pytest.raises(ValueError, match="traversal"):
+ PathValidator.validate_safe_path("../../etc/passwd", tmp_path)
+
+ def test_valid_relative_path(self, tmp_path):
+ result = PathValidator.validate_safe_path("subdir/file.txt", tmp_path)
+ assert result is not None
+ assert str(tmp_path) in str(result)
+
+ def test_extension_filtering_valid(self, tmp_path):
+ result = PathValidator.validate_safe_path(
+ "config.json", tmp_path, required_extensions=(".json", ".yaml")
+ )
+ assert result is not None
+ assert result.suffix == ".json"
+
+ def test_extension_filtering_invalid(self, tmp_path):
+ with pytest.raises(ValueError, match="file type"):
+ PathValidator.validate_safe_path(
+ "script.py", tmp_path, required_extensions=(".json",)
+ )
+
+ def test_empty_input_rejected(self, tmp_path):
+ with pytest.raises(ValueError, match="Invalid path input"):
+ PathValidator.validate_safe_path("", tmp_path)
+
+ def test_none_input_rejected(self, tmp_path):
+ with pytest.raises(ValueError, match="Invalid path input"):
+ PathValidator.validate_safe_path(None, tmp_path)
+
+ def test_simple_filename(self, tmp_path):
+ result = PathValidator.validate_safe_path("readme.txt", tmp_path)
+ assert result.name == "readme.txt"
+
+
+# ---------------------------------------------------------------------------
+# validate_local_filesystem_path()
+# ---------------------------------------------------------------------------
+
+
+class TestValidateLocalFilesystemPath:
+ """Local filesystem path validation."""
+
+ def test_etc_restricted(self):
+ with pytest.raises(ValueError, match="system directories"):
+ PathValidator.validate_local_filesystem_path("/etc/passwd")
+
+ def test_sys_restricted(self):
+ with pytest.raises(ValueError, match="system directories"):
+ PathValidator.validate_local_filesystem_path("/sys/kernel")
+
+ def test_proc_restricted(self):
+ with pytest.raises(ValueError, match="system directories"):
+ PathValidator.validate_local_filesystem_path("/proc/self/environ")
+
+ def test_dev_restricted(self):
+ with pytest.raises(ValueError, match="system directories"):
+ PathValidator.validate_local_filesystem_path("/dev/null")
+
+ def test_tilde_expansion(self):
+ result = PathValidator.validate_local_filesystem_path(
+ "~/Documents", restricted_dirs=[]
+ )
+ assert str(result).startswith(str(Path.home()))
+
+ def test_tilde_alone(self):
+ result = PathValidator.validate_local_filesystem_path(
+ "~", restricted_dirs=[]
+ )
+ assert result == Path.home().resolve()
+
+ def test_control_chars_rejected(self):
+ with pytest.raises(ValueError, match="Control characters"):
+ PathValidator.validate_local_filesystem_path("/tmp/file\x01name")
+
+ def test_null_bytes_rejected(self):
+ with pytest.raises(ValueError, match="[Nn]ull"):
+ PathValidator.validate_local_filesystem_path("/tmp/file\x00name")
+
+ def test_dotdot_blocked(self):
+ with pytest.raises(ValueError, match="traversal"):
+ PathValidator.validate_local_filesystem_path("/tmp/../etc/passwd")
+
+ def test_absolute_unix_path_valid(self):
+ result = PathValidator.validate_local_filesystem_path("/tmp")
+ assert result.is_absolute()
+
+ def test_relative_path_resolved(self):
+ result = PathValidator.validate_local_filesystem_path("somedir")
+ assert result.is_absolute()
+
+ def test_empty_rejected(self):
+ with pytest.raises(ValueError, match="Invalid path input"):
+ PathValidator.validate_local_filesystem_path("")
+
+ def test_none_rejected(self):
+ with pytest.raises(ValueError, match="Invalid path input"):
+ PathValidator.validate_local_filesystem_path(None)
+
+ def test_custom_restricted_dirs(self):
+ with pytest.raises(ValueError, match="system directories"):
+ PathValidator.validate_local_filesystem_path(
+ "/custom/restricted/path",
+ restricted_dirs=[Path("/custom/restricted")],
+ )
+
+ def test_boot_restricted(self):
+ with pytest.raises(ValueError, match="system directories"):
+ PathValidator.validate_local_filesystem_path("/boot/vmlinuz")
+
+ def test_var_log_restricted(self):
+ with pytest.raises(ValueError, match="system directories"):
+ PathValidator.validate_local_filesystem_path("/var/log/syslog")
+
+
+# ---------------------------------------------------------------------------
+# sanitize_for_filesystem_ops()
+# ---------------------------------------------------------------------------
+
+
+class TestSanitizeForFilesystemOps:
+ """Re-sanitization for static analyzers."""
+
+ def test_non_absolute_rejected(self):
+ with pytest.raises(ValueError, match="absolute"):
+ PathValidator.sanitize_for_filesystem_ops(Path("relative/path"))
+
+ def test_absolute_path_passes(self):
+ result = PathValidator.sanitize_for_filesystem_ops(Path("/tmp/safe"))
+ assert result == Path("/tmp/safe")
+
+ def test_root_path(self):
+ result = PathValidator.sanitize_for_filesystem_ops(Path("/"))
+ assert result == Path("/")
+
+
+# ---------------------------------------------------------------------------
+# validate_config_path()
+# ---------------------------------------------------------------------------
+
+
+class TestValidateConfigPath:
+ """Config file path validation."""
+
+ def test_etc_prefix_rejected(self):
+ with pytest.raises(ValueError, match="restricted"):
+ PathValidator.validate_config_path("/etc/config.json")
+
+ def test_proc_prefix_rejected(self):
+ with pytest.raises(ValueError, match="restricted"):
+ PathValidator.validate_config_path("/proc/config.yaml")
+
+ def test_sys_prefix_rejected(self):
+ with pytest.raises(ValueError, match="restricted"):
+ PathValidator.validate_config_path("/sys/config.toml")
+
+ def test_dev_prefix_rejected(self):
+ with pytest.raises(ValueError, match="restricted"):
+ PathValidator.validate_config_path("/dev/config.ini")
+
+ def test_dotdot_blocked(self):
+ with pytest.raises(ValueError, match="traversal"):
+ PathValidator.validate_config_path("../etc/passwd")
+
+ def test_empty_rejected(self):
+ with pytest.raises(ValueError, match="Invalid config path"):
+ PathValidator.validate_config_path("")
+
+ def test_none_rejected(self):
+ with pytest.raises(ValueError, match="Invalid config path"):
+ PathValidator.validate_config_path(None)
+
+ def test_null_bytes_rejected(self):
+ with pytest.raises(ValueError, match="[Nn]ull"):
+ PathValidator.validate_config_path("/tmp/config\x00.json")
+
+ def test_relative_path_uses_config_root(self, tmp_path):
+ result = PathValidator.validate_config_path(
+ "settings.json", config_root=str(tmp_path)
+ )
+ assert str(tmp_path) in str(result)
+
+ def test_invalid_extension_rejected(self, tmp_path):
+ # Create a file with invalid extension
+ test_file = tmp_path / "script.py"
+ test_file.write_text("data")
+ with pytest.raises(ValueError, match="file type"):
+ PathValidator.validate_config_path(
+ "script.py", config_root=str(tmp_path)
+ )
+
+ def test_relative_config_path_with_config_root(self, tmp_path):
+ cfg = tmp_path / "cfg.json"
+ cfg.write_text("{}")
+ # validate_config_path uses safe_join("/", path) which requires
+ # stripping the leading slash; pass relative-to-root form
+ result = PathValidator.validate_config_path(
+ "cfg.json", config_root=str(tmp_path)
+ )
+ assert result.name == "cfg.json"
+
+ def test_absolute_config_path_rejected_for_invalid_extension(
+ self, tmp_path
+ ):
+ script = tmp_path / "config.py"
+ script.write_text("data")
+ with pytest.raises(ValueError, match="file type|Invalid absolute path"):
+ PathValidator.validate_config_path(str(script))
+
+
+# ---------------------------------------------------------------------------
+# SAFE_PATH_PATTERN regex
+# ---------------------------------------------------------------------------
+
+
+class TestSafePathPattern:
+ """SAFE_PATH_PATTERN regex validation."""
+
+ def test_alphanumeric(self):
+ assert PathValidator.SAFE_PATH_PATTERN.match("hello123")
+
+ def test_dots_and_dashes(self):
+ assert PathValidator.SAFE_PATH_PATTERN.match("file-name.txt")
+
+ def test_slashes(self):
+ assert PathValidator.SAFE_PATH_PATTERN.match("dir/sub/file.txt")
+
+ def test_spaces_rejected(self):
+ assert PathValidator.SAFE_PATH_PATTERN.match("hello world") is None
+
+ def test_special_chars_rejected(self):
+ assert PathValidator.SAFE_PATH_PATTERN.match("file;rm -rf") is None
+
+ def test_shell_injection_rejected(self):
+ assert PathValidator.SAFE_PATH_PATTERN.match("$(whoami)") is None
+
+ def test_underscore_allowed(self):
+ assert PathValidator.SAFE_PATH_PATTERN.match("my_file.txt")
+
+
+# ---------------------------------------------------------------------------
+# CONFIG_EXTENSIONS
+# ---------------------------------------------------------------------------
+
+
+class TestConfigExtensions:
+ def test_json_included(self):
+ assert ".json" in PathValidator.CONFIG_EXTENSIONS
+
+ def test_yaml_included(self):
+ assert ".yaml" in PathValidator.CONFIG_EXTENSIONS
+ assert ".yml" in PathValidator.CONFIG_EXTENSIONS
+
+ def test_toml_included(self):
+ assert ".toml" in PathValidator.CONFIG_EXTENSIONS
diff --git a/tests/security/test_ssrf_validator_high_value.py b/tests/security/test_ssrf_validator_high_value.py
new file mode 100644
index 0000000000..5b915cffa8
--- /dev/null
+++ b/tests/security/test_ssrf_validator_high_value.py
@@ -0,0 +1,317 @@
+"""High-value tests for security/ssrf_validator.py - SSRF Prevention."""
+
+import os
+import socket
+from unittest.mock import patch
+
+
+from local_deep_research.security.ssrf_validator import (
+ is_ip_blocked,
+ validate_url,
+ get_safe_url,
+ ALLOWED_SCHEMES,
+ AWS_METADATA_IP,
+)
+
+
+# ---------------------------------------------------------------------------
+# is_ip_blocked - loopback / RFC1918 / CGNAT / link-local / IPv6
+# ---------------------------------------------------------------------------
+
+
+class TestIsIpBlockedLoopback:
+ """Loopback address blocking."""
+
+ def test_ipv4_loopback_blocked_by_default(self):
+ assert is_ip_blocked("127.0.0.1") is True
+
+ def test_ipv4_loopback_127_0_0_2_blocked(self):
+ assert is_ip_blocked("127.0.0.2") is True
+
+ def test_ipv6_loopback_blocked_by_default(self):
+ assert is_ip_blocked("::1") is True
+
+ def test_ipv4_loopback_allowed_with_flag(self):
+ assert is_ip_blocked("127.0.0.1", allow_localhost=True) is False
+
+ def test_ipv6_loopback_allowed_with_flag(self):
+ assert is_ip_blocked("::1", allow_localhost=True) is False
+
+
+class TestIsIpBlockedRFC1918:
+ """RFC 1918 private ranges."""
+
+ def test_10_network_blocked(self):
+ assert is_ip_blocked("10.0.0.1") is True
+
+ def test_172_16_blocked(self):
+ assert is_ip_blocked("172.16.0.1") is True
+
+ def test_192_168_blocked(self):
+ assert is_ip_blocked("192.168.1.1") is True
+
+ def test_10_network_allowed_with_private_flag(self):
+ assert is_ip_blocked("10.0.0.1", allow_private_ips=True) is False
+
+ def test_172_16_allowed_with_private_flag(self):
+ assert is_ip_blocked("172.16.0.1", allow_private_ips=True) is False
+
+ def test_192_168_allowed_with_private_flag(self):
+ assert is_ip_blocked("192.168.1.1", allow_private_ips=True) is False
+
+
+class TestIsIpBlockedSpecialRanges:
+ """CGNAT, link-local, IPv6 private ranges."""
+
+ def test_cgnat_blocked(self):
+ assert is_ip_blocked("100.64.0.1") is True
+
+ def test_link_local_blocked(self):
+ assert is_ip_blocked("169.254.1.1") is True
+
+ def test_ipv6_unique_local_blocked(self):
+ assert is_ip_blocked("fc00::1") is True
+
+ def test_ipv6_link_local_blocked(self):
+ assert is_ip_blocked("fe80::1") is True
+
+ def test_cgnat_allowed_with_private_flag(self):
+ assert is_ip_blocked("100.64.0.1", allow_private_ips=True) is False
+
+ def test_link_local_allowed_with_private_flag(self):
+ assert is_ip_blocked("169.254.1.1", allow_private_ips=True) is False
+
+ def test_loopback_also_allowed_with_private_flag(self):
+ assert is_ip_blocked("127.0.0.1", allow_private_ips=True) is False
+
+
+class TestIsIpBlockedAWSMetadata:
+ """AWS metadata endpoint always blocked."""
+
+ def test_aws_metadata_blocked_default(self):
+ assert is_ip_blocked(AWS_METADATA_IP) is True
+
+ def test_aws_metadata_blocked_even_with_allow_localhost(self):
+ assert is_ip_blocked(AWS_METADATA_IP, allow_localhost=True) is True
+
+ def test_aws_metadata_blocked_even_with_allow_private(self):
+ assert is_ip_blocked(AWS_METADATA_IP, allow_private_ips=True) is True
+
+
+class TestIsIpBlockedIPv4Mapped:
+ """IPv4-mapped IPv6 address unwrapping."""
+
+ def test_ipv4_mapped_loopback_blocked(self):
+ assert is_ip_blocked("::ffff:127.0.0.1") is True
+
+ def test_ipv4_mapped_private_blocked(self):
+ assert is_ip_blocked("::ffff:10.0.0.1") is True
+
+ def test_ipv4_mapped_aws_metadata_blocked(self):
+ assert is_ip_blocked("::ffff:169.254.169.254") is True
+
+ def test_ipv4_mapped_public_not_blocked(self):
+ assert is_ip_blocked("::ffff:8.8.8.8") is False
+
+
+class TestIsIpBlockedPublicAndInvalid:
+ """Public IPs and invalid input."""
+
+ def test_public_ip_not_blocked(self):
+ assert is_ip_blocked("8.8.8.8") is False
+
+ def test_another_public_ip(self):
+ assert is_ip_blocked("1.1.1.1") is False
+
+ def test_invalid_ip_returns_false(self):
+ assert is_ip_blocked("not-an-ip") is False
+
+ def test_empty_string_returns_false(self):
+ assert is_ip_blocked("") is False
+
+
+# ---------------------------------------------------------------------------
+# validate_url
+# ---------------------------------------------------------------------------
+
+
+class TestValidateUrlScheme:
+ """Scheme validation."""
+
+ def _validate_without_pytest(self, url, **kwargs):
+ """Helper to validate without PYTEST_CURRENT_TEST bypass."""
+ env = os.environ.copy()
+ env.pop("PYTEST_CURRENT_TEST", None)
+ with patch.dict(os.environ, env, clear=True):
+ return validate_url(url, **kwargs)
+
+ def test_ftp_scheme_rejected(self):
+ assert self._validate_without_pytest("ftp://example.com/file") is False
+
+ def test_file_scheme_rejected(self):
+ assert self._validate_without_pytest("file:///etc/passwd") is False
+
+ def test_javascript_scheme_rejected(self):
+ assert self._validate_without_pytest("javascript:alert(1)") is False
+
+
+class TestValidateUrlHostname:
+ """Hostname and IP-based URL validation."""
+
+ def _validate_without_pytest(self, url, **kwargs):
+ """Helper to validate without PYTEST_CURRENT_TEST bypass."""
+ env = os.environ.copy()
+ env.pop("PYTEST_CURRENT_TEST", None)
+ with patch.dict(os.environ, env, clear=True):
+ return validate_url(url, **kwargs)
+
+ def test_missing_hostname_rejected(self):
+ assert self._validate_without_pytest("http://") is False
+
+ def test_ip_loopback_url_blocked(self):
+ assert self._validate_without_pytest("http://127.0.0.1/admin") is False
+
+ def test_ip_private_url_blocked(self):
+ assert self._validate_without_pytest("http://192.168.1.1/") is False
+
+ def test_aws_metadata_url_blocked(self):
+ assert (
+ self._validate_without_pytest(
+ "http://169.254.169.254/latest/meta-data/"
+ )
+ is False
+ )
+
+ @patch("local_deep_research.security.ssrf_validator.socket.getaddrinfo")
+ def test_hostname_resolving_to_public_ip_allowed(self, mock_dns):
+ mock_dns.return_value = [
+ (socket.AF_INET, socket.SOCK_STREAM, 0, "", ("93.184.216.34", 0))
+ ]
+ assert self._validate_without_pytest("http://example.com") is True
+
+ @patch("local_deep_research.security.ssrf_validator.socket.getaddrinfo")
+ def test_hostname_resolving_to_private_ip_blocked(self, mock_dns):
+ mock_dns.return_value = [
+ (socket.AF_INET, socket.SOCK_STREAM, 0, "", ("10.0.0.1", 0))
+ ]
+ assert self._validate_without_pytest("http://internal.corp") is False
+
+ @patch("local_deep_research.security.ssrf_validator.socket.getaddrinfo")
+ def test_dns_failure_blocks_url(self, mock_dns):
+ mock_dns.side_effect = socket.gaierror("Name resolution failed")
+ assert self._validate_without_pytest("http://nonexistent.test") is False
+
+
+class TestValidateUrlFlagPassthrough:
+ """Flag pass-through to is_ip_blocked."""
+
+ def _validate_without_pytest(self, url, **kwargs):
+ """Helper to validate without PYTEST_CURRENT_TEST bypass."""
+ env = os.environ.copy()
+ env.pop("PYTEST_CURRENT_TEST", None)
+ with patch.dict(os.environ, env, clear=True):
+ return validate_url(url, **kwargs)
+
+ @patch("local_deep_research.security.ssrf_validator.socket.getaddrinfo")
+ def test_allow_localhost_passes_loopback(self, mock_dns):
+ mock_dns.return_value = [
+ (socket.AF_INET, socket.SOCK_STREAM, 0, "", ("127.0.0.1", 0))
+ ]
+ assert (
+ self._validate_without_pytest(
+ "http://127.0.0.1/", allow_localhost=True
+ )
+ is True
+ )
+
+ @patch("local_deep_research.security.ssrf_validator.socket.getaddrinfo")
+ def test_allow_private_ips_passes_private(self, mock_dns):
+ mock_dns.return_value = [
+ (socket.AF_INET, socket.SOCK_STREAM, 0, "", ("10.0.0.1", 0))
+ ]
+ assert (
+ self._validate_without_pytest(
+ "http://10.0.0.1/", allow_private_ips=True
+ )
+ is True
+ )
+
+ @patch("local_deep_research.security.ssrf_validator.socket.getaddrinfo")
+ def test_multi_address_dns_one_private_blocked(self, mock_dns):
+ mock_dns.return_value = [
+ (socket.AF_INET, socket.SOCK_STREAM, 0, "", ("93.184.216.34", 0)),
+ (socket.AF_INET, socket.SOCK_STREAM, 0, "", ("10.0.0.1", 0)),
+ ]
+ assert self._validate_without_pytest("http://dual.example.com") is False
+
+
+class TestIsIpBlockedZeroNetwork:
+ """0.0.0.0/8 range blocking."""
+
+ def test_0001_blocked(self):
+ assert is_ip_blocked("0.0.0.1") is True
+
+ def test_0001_blocked_even_with_allow_private(self):
+ """0.0.0.0/8 is NOT in PRIVATE_RANGES, so it stays blocked."""
+ assert is_ip_blocked("0.0.0.1", allow_private_ips=True) is True
+
+
+class TestValidateUrlPytestBypass:
+ """PYTEST_CURRENT_TEST bypass logic."""
+
+ def test_pytest_env_var_bypasses_validation(self):
+ with patch.dict(
+ os.environ, {"PYTEST_CURRENT_TEST": "test_foo.py::test_bar"}
+ ):
+ assert validate_url("ftp://evil.com") is True
+
+ def test_no_pytest_env_does_not_bypass(self):
+ env = os.environ.copy()
+ env.pop("PYTEST_CURRENT_TEST", None)
+ with patch.dict(os.environ, env, clear=True):
+ assert validate_url("ftp://evil.com") is False
+
+
+# ---------------------------------------------------------------------------
+# get_safe_url
+# ---------------------------------------------------------------------------
+
+
+class TestGetSafeUrl:
+ """get_safe_url() wrapper."""
+
+ def test_none_returns_default(self):
+ assert get_safe_url(None, "fallback") == "fallback"
+
+ def test_empty_returns_default(self):
+ assert get_safe_url("", "fallback") == "fallback"
+
+ def test_safe_url_passes_through(self):
+ with patch(
+ "local_deep_research.security.ssrf_validator.validate_url",
+ return_value=True,
+ ):
+ assert get_safe_url("http://example.com") == "http://example.com"
+
+ def test_unsafe_url_returns_default(self):
+ with patch(
+ "local_deep_research.security.ssrf_validator.validate_url",
+ return_value=False,
+ ):
+ assert get_safe_url("http://evil.internal", "safe") == "safe"
+
+ def test_none_url_none_default(self):
+ assert get_safe_url(None) is None
+
+
+# ---------------------------------------------------------------------------
+# Constants
+# ---------------------------------------------------------------------------
+
+
+class TestConstants:
+ def test_allowed_schemes_http_https(self):
+ assert ALLOWED_SCHEMES == {"http", "https"}
+
+ def test_aws_metadata_ip_value(self):
+ assert AWS_METADATA_IP == "169.254.169.254"
diff --git a/tests/utilities/test_llm_utils_high_value.py b/tests/utilities/test_llm_utils_high_value.py
new file mode 100644
index 0000000000..3d88d56766
--- /dev/null
+++ b/tests/utilities/test_llm_utils_high_value.py
@@ -0,0 +1,197 @@
+"""High-value tests for utilities/llm_utils.py - LLM URL Resolution."""
+
+from unittest.mock import patch
+
+
+from local_deep_research.utilities.llm_utils import (
+ get_ollama_base_url,
+ get_server_url,
+)
+
+
+# ---------------------------------------------------------------------------
+# get_ollama_base_url()
+# ---------------------------------------------------------------------------
+
+
+class TestGetOllamaBaseUrl:
+ """Ollama base URL fallback chain."""
+
+ @patch("local_deep_research.utilities.llm_utils.get_setting_from_snapshot")
+ @patch(
+ "local_deep_research.utilities.url_utils.normalize_url",
+ side_effect=lambda x: x,
+ )
+ def test_embeddings_url_takes_priority(self, mock_normalize, mock_get):
+ mock_get.side_effect = (
+ lambda key, default=None, settings_snapshot=None: (
+ "http://ollama-embed:11434"
+ if key == "embeddings.ollama.url"
+ else default
+ )
+ )
+ result = get_ollama_base_url()
+ assert result == "http://ollama-embed:11434"
+
+ @patch("local_deep_research.utilities.llm_utils.get_setting_from_snapshot")
+ @patch(
+ "local_deep_research.utilities.url_utils.normalize_url",
+ side_effect=lambda x: x,
+ )
+ def test_llm_url_fallback(self, mock_normalize, mock_get):
+ def side_effect(key, default=None, settings_snapshot=None):
+ if key == "embeddings.ollama.url":
+ return default # not set
+ if key == "llm.ollama.url":
+ return "http://ollama-llm:11434"
+ return default
+
+ mock_get.side_effect = side_effect
+ result = get_ollama_base_url()
+ assert result == "http://ollama-llm:11434"
+
+ @patch("local_deep_research.utilities.llm_utils.get_setting_from_snapshot")
+ @patch(
+ "local_deep_research.utilities.url_utils.normalize_url",
+ side_effect=lambda x: x,
+ )
+ def test_default_localhost(self, mock_normalize, mock_get):
+ mock_get.side_effect = (
+ lambda key, default=None, settings_snapshot=None: default
+ )
+ result = get_ollama_base_url()
+ assert result == "http://localhost:11434"
+
+ @patch("local_deep_research.utilities.llm_utils.get_setting_from_snapshot")
+ @patch(
+ "local_deep_research.utilities.url_utils.normalize_url",
+ side_effect=lambda x: x,
+ )
+ def test_settings_snapshot_passed_through(self, mock_normalize, mock_get):
+ snapshot = {"embeddings": {"ollama": {"url": "http://custom:1234"}}}
+ mock_get.side_effect = (
+ lambda key, default=None, settings_snapshot=None: default
+ )
+ get_ollama_base_url(settings_snapshot=snapshot)
+ # Verify snapshot is passed to every get_setting_from_snapshot call
+ for call in mock_get.call_args_list:
+ assert call.kwargs.get("settings_snapshot") == snapshot
+
+ @patch("local_deep_research.utilities.llm_utils.get_setting_from_snapshot")
+ @patch(
+ "local_deep_research.utilities.url_utils.normalize_url",
+ side_effect=lambda x: x,
+ )
+ def test_normalize_url_called(self, mock_normalize, mock_get):
+ mock_get.side_effect = (
+ lambda key, default=None, settings_snapshot=None: (
+ "http://host:1234/"
+ if key == "embeddings.ollama.url"
+ else default
+ )
+ )
+ get_ollama_base_url()
+ mock_normalize.assert_called_once_with("http://host:1234/")
+
+ @patch("local_deep_research.utilities.llm_utils.get_setting_from_snapshot")
+ def test_none_url_returns_default(self, mock_get):
+ """If the resolved URL is None/empty, fall back to localhost."""
+ mock_get.side_effect = (
+ lambda key, default=None, settings_snapshot=None: None
+ )
+ result = get_ollama_base_url()
+ assert result == "http://localhost:11434"
+
+
+# ---------------------------------------------------------------------------
+# get_server_url()
+# ---------------------------------------------------------------------------
+
+
+class TestGetServerUrl:
+ """Server URL multi-source fallback chain."""
+
+ def test_no_snapshot_returns_default(self):
+ result = get_server_url(settings_snapshot=None)
+ assert result == "http://127.0.0.1:5000/"
+
+ def test_direct_server_url_in_snapshot(self):
+ snapshot = {"server_url": "https://myserver.com:8080/"}
+ result = get_server_url(settings_snapshot=snapshot)
+ assert result == "https://myserver.com:8080/"
+
+ def test_system_server_url_fallback(self):
+ snapshot = {"system": {"server_url": "https://system-server.com/"}}
+ result = get_server_url(settings_snapshot=snapshot)
+ assert result == "https://system-server.com/"
+
+ @patch("local_deep_research.utilities.llm_utils.get_setting_from_snapshot")
+ def test_construct_from_host_port_https(self, mock_get):
+ def side_effect(key, default_val=None, default=None):
+ mapping = {
+ "web.host": "192.168.1.100",
+ "web.port": 8443,
+ "web.use_https": True,
+ }
+ return mapping.get(key, default)
+
+ mock_get.side_effect = side_effect
+
+ snapshot = {"other": "stuff"} # no server_url, no system.server_url
+ result = get_server_url(settings_snapshot=snapshot)
+ assert "192.168.1.100" in result
+ assert "8443" in result
+ assert result.startswith("https://")
+
+ @patch("local_deep_research.utilities.llm_utils.get_setting_from_snapshot")
+ def test_construct_http_when_not_https(self, mock_get):
+ def side_effect(key, default_val=None, default=None):
+ mapping = {
+ "web.host": "myhost",
+ "web.port": 3000,
+ "web.use_https": False,
+ }
+ return mapping.get(key, default)
+
+ mock_get.side_effect = side_effect
+
+ snapshot = {"other": "stuff"}
+ result = get_server_url(settings_snapshot=snapshot)
+ assert result.startswith("http://")
+
+ @patch("local_deep_research.utilities.llm_utils.get_setting_from_snapshot")
+ def test_0000_replaced_with_127001(self, mock_get):
+ def side_effect(key, default_val=None, default=None):
+ mapping = {
+ "web.host": "0.0.0.0",
+ "web.port": 5000,
+ "web.use_https": True,
+ }
+ return mapping.get(key, default)
+
+ mock_get.side_effect = side_effect
+
+ snapshot = {"other": "stuff"}
+ result = get_server_url(settings_snapshot=snapshot)
+ assert "127.0.0.1" in result
+ assert "0.0.0.0" not in result
+
+ def test_direct_server_url_preferred_over_system(self):
+ snapshot = {
+ "server_url": "https://direct.com/",
+ "system": {"server_url": "https://system.com/"},
+ }
+ result = get_server_url(settings_snapshot=snapshot)
+ assert result == "https://direct.com/"
+
+ def test_empty_snapshot(self):
+ result = get_server_url(settings_snapshot={})
+ # Should construct from defaults or fall back
+ assert result is not None
+ assert len(result) > 0
+
+ def test_empty_string_server_url_falls_through(self):
+ snapshot = {"server_url": "", "system": {"server_url": ""}}
+ result = get_server_url(settings_snapshot=snapshot)
+ # Empty strings are falsy, should fall through to construction
+ assert result is not None
diff --git a/tests/web/warning_checks/test_hardware_high_value.py b/tests/web/warning_checks/test_hardware_high_value.py
new file mode 100644
index 0000000000..430d71ec9b
--- /dev/null
+++ b/tests/web/warning_checks/test_hardware_high_value.py
@@ -0,0 +1,132 @@
+"""High-value tests for web/warning_checks/hardware.py - Hardware Warnings."""
+
+from local_deep_research.web.warning_checks.hardware import (
+ check_high_context,
+ check_model_mismatch,
+ LOCAL_PROVIDERS,
+)
+
+
+# ---------------------------------------------------------------------------
+# LOCAL_PROVIDERS
+# ---------------------------------------------------------------------------
+
+
+class TestLocalProviders:
+ def test_is_frozenset(self):
+ assert isinstance(LOCAL_PROVIDERS, frozenset)
+
+ def test_expected_providers(self):
+ assert LOCAL_PROVIDERS == {"ollama", "llamacpp", "lmstudio", "vllm"}
+
+
+# ---------------------------------------------------------------------------
+# check_high_context()
+# ---------------------------------------------------------------------------
+
+
+class TestCheckHighContext:
+ """High context warning for local providers."""
+
+ def test_non_local_provider_returns_none(self):
+ assert check_high_context("openai", 16384, False) is None
+
+ def test_context_at_threshold_returns_none(self):
+ assert check_high_context("ollama", 8192, False) is None
+
+ def test_context_below_threshold_returns_none(self):
+ assert check_high_context("ollama", 4096, False) is None
+
+ def test_dismissed_returns_none(self):
+ assert check_high_context("ollama", 16384, True) is None
+
+ def test_ollama_high_context_returns_warning(self):
+ result = check_high_context("ollama", 16384, False)
+ assert result is not None
+ assert result["type"] == "high_context"
+ assert "16,384" in result["message"]
+ assert "ollama" in result["message"]
+
+ def test_llamacpp_high_context(self):
+ result = check_high_context("llamacpp", 32768, False)
+ assert result is not None
+ assert result["type"] == "high_context"
+
+ def test_vllm_high_context(self):
+ result = check_high_context("vllm", 10000, False)
+ assert result is not None
+ assert result["type"] == "high_context"
+
+ def test_lmstudio_high_context(self):
+ result = check_high_context("lmstudio", 10000, False)
+ assert result is not None
+ assert result["type"] == "high_context"
+
+ def test_warning_has_dismiss_key(self):
+ result = check_high_context("ollama", 16384, False)
+ assert "dismissKey" in result
+
+ def test_warning_has_icon(self):
+ result = check_high_context("ollama", 16384, False)
+ assert "icon" in result
+
+ def test_anthropic_not_local(self):
+ assert check_high_context("anthropic", 100000, False) is None
+
+ def test_boundary_8193_triggers_warning(self):
+ result = check_high_context("ollama", 8193, False)
+ assert result is not None
+ assert result["title"] == "High Context Warning"
+
+
+# ---------------------------------------------------------------------------
+# check_model_mismatch()
+# ---------------------------------------------------------------------------
+
+
+class TestCheckModelMismatch:
+ """Model mismatch warning for large models with high context."""
+
+ def test_empty_model_returns_none(self):
+ assert check_model_mismatch("ollama", "", 16384, False) is None
+
+ def test_none_model_returns_none(self):
+ assert check_model_mismatch("ollama", None, 16384, False) is None
+
+ def test_non_local_provider_returns_none(self):
+ assert (
+ check_model_mismatch("openai", "llama3-70b", 16384, False) is None
+ )
+
+ def test_non_70b_model_returns_none(self):
+ assert check_model_mismatch("ollama", "llama3-7b", 16384, False) is None
+
+ def test_low_context_returns_none(self):
+ assert check_model_mismatch("ollama", "llama3-70b", 8192, False) is None
+
+ def test_dismissed_returns_none(self):
+ assert check_model_mismatch("ollama", "llama3-70b", 16384, True) is None
+
+ def test_70b_high_context_returns_warning(self):
+ result = check_model_mismatch("ollama", "llama3-70b", 16384, False)
+ assert result is not None
+ assert result["type"] == "model_mismatch"
+ assert "llama3-70b" in result["message"]
+ assert "16,384" in result["message"]
+
+ def test_case_insensitive_70b(self):
+ result = check_model_mismatch("ollama", "Llama3-70B-Q4", 16384, False)
+ assert result is not None
+
+ def test_boundary_8193_triggers_warning(self):
+ result = check_model_mismatch("ollama", "llama3-70b", 8193, False)
+ assert result is not None
+ assert result["title"] == "Model & Context Warning"
+
+ def test_warning_has_dismiss_key(self):
+ result = check_model_mismatch("ollama", "model-70b", 16384, False)
+ assert "dismissKey" in result
+
+ def test_warning_has_icon(self):
+ result = check_model_mismatch("ollama", "model-70b", 16384, False)
+ assert "icon" in result