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 42 security-focused tests for safe_requests and settings validation (round 15) (#2645)

LearningCircuitca0da39364f2
diff --git a/tests/security/test_check_response_size.py b/tests/security/test_check_response_size.py
new file mode 100644
index 0000000000..8ab43e0a69
--- /dev/null
+++ b/tests/security/test_check_response_size.py
@@ -0,0 +1,238 @@
+"""Tests for _check_response_size() and SafeSession.send() intermediate redirect branching.
+
+Covers:
+- _check_response_size() direct unit tests (8 tests) — zero prior coverage
+- SafeSession.send() intermediate redirect size-check logic (10 tests) — lines 437-443
+"""
+
+import pytest
+from unittest.mock import patch, MagicMock
+
+import requests
+
+from local_deep_research.security.safe_requests import (
+ _check_response_size,
+ SafeSession,
+ MAX_RESPONSE_SIZE,
+ _REDIRECT_STATUS_CODES,
+)
+
+
+def _mock_response(status_code=200, headers=None):
+ """Build a MagicMock Response with the given status and headers."""
+ resp = MagicMock(spec=requests.Response)
+ resp.status_code = status_code
+ resp.headers = headers or {}
+ resp.url = "https://example.com"
+ return resp
+
+
+# ── _check_response_size() direct unit tests ────────────────────────
+
+
+class TestCheckResponseSizeDirect:
+ """Direct unit tests for _check_response_size (lines 29-53)."""
+
+ def test_no_content_length_header(self):
+ """No Content-Length header → no raise."""
+ resp = _mock_response(headers={})
+ _check_response_size(resp) # should not raise
+
+ def test_empty_string_content_length(self):
+ """Empty string Content-Length is falsy → no raise."""
+ resp = _mock_response(headers={"Content-Length": ""})
+ _check_response_size(resp)
+
+ def test_negative_content_length(self):
+ """Negative Content-Length → returns silently (line 46-47)."""
+ resp = _mock_response(headers={"Content-Length": "-1"})
+ _check_response_size(resp)
+
+ def test_non_numeric_content_length(self):
+ """Non-numeric Content-Length → ValueError caught, returns (line 44)."""
+ resp = _mock_response(headers={"Content-Length": "abc"})
+ _check_response_size(resp)
+
+ def test_content_length_type_error(self):
+ """Content-Length value that causes TypeError in int() → caught (line 44)."""
+ resp = _mock_response(headers={"Content-Length": None})
+ _check_response_size(resp)
+
+ def test_exactly_at_max_size(self):
+ """Content-Length exactly at MAX_RESPONSE_SIZE → no raise (> not >=)."""
+ resp = _mock_response(
+ headers={"Content-Length": str(MAX_RESPONSE_SIZE)}
+ )
+ _check_response_size(resp)
+
+ def test_one_over_max_raises(self):
+ """Content-Length one over MAX → raises ValueError, response.close() called."""
+ resp = _mock_response(
+ headers={"Content-Length": str(MAX_RESPONSE_SIZE + 1)}
+ )
+ with pytest.raises(ValueError, match="Response too large"):
+ _check_response_size(resp)
+ resp.close.assert_called_once()
+
+ def test_normal_size_under_limit(self):
+ """Normal Content-Length well under limit → no raise."""
+ resp = _mock_response(headers={"Content-Length": "1024"})
+ _check_response_size(resp)
+
+
+# ── SafeSession.send() intermediate redirect branching ──────────────
+
+
+def _prep_request(url="https://example.com"):
+ """Build a minimal PreparedRequest."""
+ prep = requests.PreparedRequest()
+ prep.prepare_url(url, {})
+ prep.prepare_method("GET")
+ return prep
+
+
+def _bypass_ssrf():
+ """Patch validate_url to always return True (bypass SSRF check)."""
+ with patch(
+ "local_deep_research.security.safe_requests.validate_url",
+ return_value=True,
+ ):
+ yield
+
+
+class TestSendIntermediateRedirectBranching:
+ """Tests for is_intermediate_redirect logic (lines 437-443)."""
+
+ def test_302_with_location_and_allow_redirects_skips_size_check(
+ self, _bypass_ssrf
+ ):
+ """302 + Location + allow_redirects=True → skip size check (oversized OK)."""
+ oversized = _mock_response(
+ 302,
+ {
+ "Location": "https://other.com",
+ "Content-Length": str(MAX_RESPONSE_SIZE + 1),
+ },
+ )
+ session = SafeSession()
+ with patch.object(requests.Session, "send", return_value=oversized):
+ result = session.send(_prep_request(), allow_redirects=True)
+ assert result.status_code == 302
+
+ def test_302_with_location_and_allow_redirects_false_applies_size_check(
+ self, _bypass_ssrf
+ ):
+ """302 + Location + allow_redirects=False → apply size check → raises."""
+ oversized = _mock_response(
+ 302,
+ {
+ "Location": "https://other.com",
+ "Content-Length": str(MAX_RESPONSE_SIZE + 1),
+ },
+ )
+ session = SafeSession()
+ with patch.object(requests.Session, "send", return_value=oversized):
+ with pytest.raises(ValueError, match="Response too large"):
+ session.send(_prep_request(), allow_redirects=False)
+
+ def test_302_without_location_applies_size_check(self, _bypass_ssrf):
+ """302 without Location header → apply size check → raises."""
+ oversized = _mock_response(
+ 302, {"Content-Length": str(MAX_RESPONSE_SIZE + 1)}
+ )
+ session = SafeSession()
+ with patch.object(requests.Session, "send", return_value=oversized):
+ with pytest.raises(ValueError, match="Response too large"):
+ session.send(_prep_request(), allow_redirects=True)
+
+ def test_302_without_location_normal_size_passes(self, _bypass_ssrf):
+ """302 without Location, normal Content-Length → no raise."""
+ resp = _mock_response(302, {"Content-Length": "512"})
+ session = SafeSession()
+ with patch.object(requests.Session, "send", return_value=resp):
+ result = session.send(_prep_request(), allow_redirects=True)
+ assert result.status_code == 302
+
+ def test_200_normal_size_passes(self, _bypass_ssrf):
+ """200 response, normal size → passes."""
+ resp = _mock_response(200, {"Content-Length": "1024"})
+ session = SafeSession()
+ with patch.object(requests.Session, "send", return_value=resp):
+ result = session.send(_prep_request())
+ assert result.status_code == 200
+
+ def test_200_oversized_raises(self, _bypass_ssrf):
+ """200 response, oversized Content-Length → raises."""
+ oversized = _mock_response(
+ 200, {"Content-Length": str(MAX_RESPONSE_SIZE + 1)}
+ )
+ session = SafeSession()
+ with patch.object(requests.Session, "send", return_value=oversized):
+ with pytest.raises(ValueError, match="Response too large"):
+ session.send(_prep_request())
+
+ @pytest.mark.parametrize("status_code", [301, 302, 303, 307, 308])
+ def test_all_redirect_codes_skip_size_check(
+ self, _bypass_ssrf, status_code
+ ):
+ """All 5 redirect codes + Location + allow_redirects=True → skip size check."""
+ oversized = _mock_response(
+ status_code,
+ {
+ "Location": "https://other.com",
+ "Content-Length": str(MAX_RESPONSE_SIZE + 1),
+ },
+ )
+ session = SafeSession()
+ with patch.object(requests.Session, "send", return_value=oversized):
+ result = session.send(_prep_request(), allow_redirects=True)
+ assert result.status_code == status_code
+
+ def test_allow_redirects_defaults_to_true(self, _bypass_ssrf):
+ """No allow_redirects in kwargs → defaults to True → skip size check."""
+ oversized = _mock_response(
+ 302,
+ {
+ "Location": "https://other.com",
+ "Content-Length": str(MAX_RESPONSE_SIZE + 1),
+ },
+ )
+ session = SafeSession()
+ with patch.object(requests.Session, "send", return_value=oversized):
+ # No allow_redirects kwarg at all
+ result = session.send(_prep_request())
+ assert result.status_code == 302
+
+ def test_304_not_in_redirect_set_applies_size_check(self, _bypass_ssrf):
+ """304 Not Modified is NOT in the redirect frozenset → size check applies."""
+ assert 304 not in _REDIRECT_STATUS_CODES
+ oversized = _mock_response(
+ 304,
+ {
+ "Location": "https://other.com",
+ "Content-Length": str(MAX_RESPONSE_SIZE + 1),
+ },
+ )
+ session = SafeSession()
+ with patch.object(requests.Session, "send", return_value=oversized):
+ with pytest.raises(ValueError, match="Response too large"):
+ session.send(_prep_request(), allow_redirects=True)
+
+ def test_oversized_intermediate_redirect_not_rejected(self, _bypass_ssrf):
+ """301 + Location + allow_redirects=True + oversized → no raise.
+
+ This validates the security design: intermediate redirects are not
+ size-checked because their body is discarded during redirect following.
+ """
+ oversized = _mock_response(
+ 301,
+ {
+ "Location": "https://other.com",
+ "Content-Length": str(MAX_RESPONSE_SIZE + 1),
+ },
+ )
+ session = SafeSession()
+ with patch.object(requests.Session, "send", return_value=oversized):
+ result = session.send(_prep_request(), allow_redirects=True)
+ assert result.status_code == 301
diff --git a/tests/web/routes/test_settings_validation_edge_cases.py b/tests/web/routes/test_settings_validation_edge_cases.py
new file mode 100644
index 0000000000..965535a93f
--- /dev/null
+++ b/tests/web/routes/test_settings_validation_edge_cases.py
@@ -0,0 +1,196 @@
+"""Tests for is_blocked_setting() and validate_setting() edge cases.
+
+Covers:
+- is_blocked_setting() unit tests (8 tests) — zero prior direct coverage
+- validate_setting() min/max constraints, select edge cases, unknown ui_element (12 tests)
+"""
+
+from unittest.mock import patch
+
+from local_deep_research.web.routes.settings_routes import (
+ is_blocked_setting,
+ validate_setting,
+ DYNAMIC_SETTINGS,
+)
+from local_deep_research.web.models.settings import BaseSetting, SettingType
+
+
+# ── is_blocked_setting() unit tests ─────────────────────────────────
+
+
+class TestIsBlockedSetting:
+ """Direct unit tests for is_blocked_setting (lines 100-117)."""
+
+ def test_module_path_pattern(self):
+ """'module_path' substring → blocked."""
+ assert is_blocked_setting("search.engine.module_path") is True
+
+ def test_class_name_pattern(self):
+ """'class_name' substring → blocked."""
+ assert is_blocked_setting("handler.class_name") is True
+
+ def test_module_pattern(self):
+ """'module' substring → blocked."""
+ assert is_blocked_setting("custom_module") is True
+
+ def test_class_pattern(self):
+ """'class' substring → blocked."""
+ assert is_blocked_setting("handler_class") is True
+
+ def test_case_insensitivity(self):
+ """Key is lowered before matching → case-insensitive."""
+ assert is_blocked_setting("SEARCH.MODULE_PATH") is True
+
+ def test_substring_match(self):
+ """'submodule_config' contains 'module' → blocked."""
+ assert is_blocked_setting("submodule_config") is True
+
+ def test_non_matching_key(self):
+ """'search.max_results' matches no pattern → not blocked."""
+ assert is_blocked_setting("search.max_results") is False
+
+ def test_empty_string(self):
+ """Empty string matches no pattern → not blocked."""
+ assert is_blocked_setting("") is False
+
+
+# ── validate_setting() edge case tests ──────────────────────────────
+
+
+def _make_setting(ui_element, **kwargs):
+ """Helper to build a BaseSetting with minimal boilerplate."""
+ defaults = dict(
+ key="test.key",
+ value=0,
+ type=SettingType.APP,
+ name="Test",
+ )
+ defaults.update(kwargs)
+ defaults["ui_element"] = ui_element
+ return BaseSetting(**defaults)
+
+
+class TestValidateSettingMinMax:
+ """Tests for number/slider/range min/max constraint validation."""
+
+ def test_number_below_min(self):
+ """Number below min_value → (False, error)."""
+ setting = _make_setting("number", min_value=0)
+ valid, msg = validate_setting(setting, -1)
+ assert valid is False
+ assert "at least" in msg
+
+ def test_number_above_max(self):
+ """Number above max_value → (False, error)."""
+ setting = _make_setting("number", max_value=100)
+ valid, msg = validate_setting(setting, 150)
+ assert valid is False
+ assert "at most" in msg
+
+ def test_number_no_constraints(self):
+ """Number with no min/max → (True, None)."""
+ setting = _make_setting("number")
+ valid, msg = validate_setting(setting, 999)
+ assert valid is True
+ assert msg is None
+
+ def test_number_only_min_passes(self):
+ """Number with only min_value, value above → (True, None)."""
+ setting = _make_setting("number", min_value=0)
+ valid, msg = validate_setting(setting, 5)
+ assert valid is True
+
+ def test_number_only_max_passes(self):
+ """Number with only max_value, value below → (True, None)."""
+ setting = _make_setting("number", max_value=100)
+ valid, msg = validate_setting(setting, 50)
+ assert valid is True
+
+ def test_slider_below_min(self):
+ """Slider below min_value → (False, error).
+
+ 'slider' is not in UI_ELEMENT_TO_SETTING_TYPE, so get_typed_setting_value
+ returns default=None. We patch it to pass through the numeric value so
+ we can test the min/max constraint logic in validate_setting.
+ """
+ setting = _make_setting("slider", min_value=5)
+ with patch(
+ "local_deep_research.web.routes.settings_routes.get_typed_setting_value",
+ return_value=2,
+ ):
+ valid, msg = validate_setting(setting, 2)
+ assert valid is False
+ assert "at least" in msg
+
+ def test_range_above_max(self):
+ """Range above max_value → (False, error)."""
+ setting = _make_setting("range", max_value=10)
+ valid, msg = validate_setting(setting, 15)
+ assert valid is False
+ assert "at most" in msg
+
+
+class TestValidateSettingSelect:
+ """Tests for select ui_element edge cases."""
+
+ def test_select_invalid_option(self):
+ """Select with value not in options → (False, error)."""
+ setting = _make_setting(
+ "select",
+ options=[{"value": "a"}, {"value": "b"}],
+ )
+ valid, msg = validate_setting(setting, "x")
+ assert valid is False
+ assert "must be one of" in msg
+
+ def test_select_plain_string_options(self):
+ """Select with plain string options list → valid option passes.
+
+ The Pydantic model enforces List[Dict], but at runtime the
+ validate_setting code handles both dict and non-dict options
+ (line 199). We use a mock to bypass Pydantic validation.
+ """
+ from unittest.mock import MagicMock
+
+ setting = MagicMock()
+ setting.key = "test.select"
+ setting.ui_element = "select"
+ setting.options = ["a", "b", "c"]
+
+ # Patch get_typed_setting_value to pass through the value unchanged
+ with patch(
+ "local_deep_research.web.routes.settings_routes.get_typed_setting_value",
+ return_value="b",
+ ):
+ valid, msg = validate_setting(setting, "b")
+ assert valid is True
+
+ def test_select_empty_options_skips_validation(self):
+ """Select with empty options list → validation skipped → (True, None)."""
+ setting = _make_setting("select", options=[])
+ valid, msg = validate_setting(setting, "anything")
+ assert valid is True
+
+ def test_select_dynamic_setting_skips_validation(self):
+ """Select with key in DYNAMIC_SETTINGS → validation skipped."""
+ # Use a real DYNAMIC_SETTINGS key
+ dynamic_key = DYNAMIC_SETTINGS[0] # "llm.provider"
+ setting = _make_setting(
+ "select",
+ key=dynamic_key,
+ options=[{"value": "a"}, {"value": "b"}],
+ )
+ # Value not in options, but should pass because it's dynamic
+ valid, msg = validate_setting(setting, "nonexistent_provider")
+ assert valid is True
+
+
+class TestValidateSettingUnknownElement:
+ """Test that unknown ui_element types pass through."""
+
+ def test_unknown_ui_element_passes(self):
+ """Unknown ui_element like 'custom_widget' → (True, None)."""
+ setting = _make_setting("custom_widget")
+ valid, msg = validate_setting(setting, "any value")
+ assert valid is True
+ assert msg is None