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 1024 comprehensive tests across 12 new test files (#2447)

LearningCircuit0e621a3299e1
diff --git a/tests/config/test_thread_settings_extended.py b/tests/config/test_thread_settings_extended.py
new file mode 100644
index 0000000000..bb1e8c5cfe
--- /dev/null
+++ b/tests/config/test_thread_settings_extended.py
@@ -0,0 +1,476 @@
+"""Extended tests for the thread_settings module.
+
+Covers thread-context management, get_setting_from_snapshot logic,
+get_llm_setting_from_snapshot delegation, and get_bool_setting_from_snapshot
+boolean conversion.
+"""
+
+import threading
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from local_deep_research.config.thread_settings import (
+ NoSettingsContextError,
+ clear_settings_context,
+ get_bool_setting_from_snapshot,
+ get_llm_setting_from_snapshot,
+ get_setting_from_snapshot,
+ get_settings_context,
+ set_settings_context,
+ settings_context,
+)
+
+
+# ---------------------------------------------------------------------------
+# Thread context management
+# ---------------------------------------------------------------------------
+
+
+class TestThreadContextManagement:
+ """Tests for set/get/clear thread-local settings context."""
+
+ def test_set_get_round_trip(self, clean_thread_local):
+ """Setting a context and immediately getting it returns the same object."""
+ ctx = MagicMock()
+ set_settings_context(ctx)
+ assert get_settings_context() is ctx
+
+ def test_clear_removes_context(self, clean_thread_local):
+ """After clearing, get_settings_context returns None."""
+ set_settings_context(MagicMock())
+ clear_settings_context()
+ assert get_settings_context() is None
+
+ def test_clear_when_nothing_set_does_not_error(self, clean_thread_local):
+ """Clearing without a prior set must not raise."""
+ clear_settings_context() # should be a no-op
+
+ def test_get_returns_none_when_not_set(self, clean_thread_local):
+ """get_settings_context returns None when no context has been set."""
+ assert get_settings_context() is None
+
+ def test_settings_context_manager_sets_and_clears(self, clean_thread_local):
+ """The settings_context context manager sets context on entry and
+ clears it on exit."""
+ ctx = MagicMock()
+ with settings_context(ctx):
+ assert get_settings_context() is ctx
+ assert get_settings_context() is None
+
+ def test_settings_context_manager_clears_on_exception(
+ self, clean_thread_local
+ ):
+ """Context is cleared even when the body raises an exception."""
+ ctx = MagicMock()
+ with pytest.raises(RuntimeError):
+ with settings_context(ctx):
+ raise RuntimeError("boom")
+ assert get_settings_context() is None
+
+ def test_overwrite_previous_context(self, clean_thread_local):
+ """Setting a second context replaces the first."""
+ ctx1 = MagicMock()
+ ctx2 = MagicMock()
+ set_settings_context(ctx1)
+ set_settings_context(ctx2)
+ assert get_settings_context() is ctx2
+
+ def test_thread_isolation(self, clean_thread_local):
+ """Contexts set in different threads are independent."""
+ barrier = threading.Barrier(2)
+ results = {}
+
+ def worker(name, value):
+ ctx = MagicMock()
+ ctx.value = value
+ set_settings_context(ctx)
+ barrier.wait() # force both threads to overlap
+ results[name] = get_settings_context().value
+
+ t1 = threading.Thread(target=worker, args=("t1", "val1"))
+ t2 = threading.Thread(target=worker, args=("t2", "val2"))
+ t1.start()
+ t2.start()
+ t1.join()
+ t2.join()
+
+ assert results["t1"] == "val1"
+ assert results["t2"] == "val2"
+
+
+# ---------------------------------------------------------------------------
+# get_setting_from_snapshot
+# ---------------------------------------------------------------------------
+
+
+class TestGetSettingFromSnapshotDirect:
+ """Tests for direct key lookups in get_setting_from_snapshot."""
+
+ def test_direct_value_from_snapshot(self, clean_thread_local):
+ """A plain (non-dict) value stored under the exact key is returned."""
+ snapshot = {"my_key": "hello"}
+ assert (
+ get_setting_from_snapshot("my_key", settings_snapshot=snapshot)
+ == "hello"
+ )
+
+ def test_direct_integer_value(self, clean_thread_local):
+ """Integer values are returned without coercion."""
+ snapshot = {"count": 42}
+ assert (
+ get_setting_from_snapshot("count", settings_snapshot=snapshot) == 42
+ )
+
+ @patch("local_deep_research.config.thread_settings.get_typed_setting_value")
+ def test_dict_format_with_value_key(self, mock_gtsv, clean_thread_local):
+ """A dict containing 'value' triggers get_typed_setting_value."""
+ mock_gtsv.return_value = "typed_result"
+ snapshot = {"key": {"value": "raw", "ui_element": "select"}}
+ result = get_setting_from_snapshot("key", settings_snapshot=snapshot)
+ mock_gtsv.assert_called_once_with("key", "raw", "select")
+ assert result == "typed_result"
+
+ @patch("local_deep_research.config.thread_settings.get_typed_setting_value")
+ def test_dict_format_defaults_ui_element_to_text(
+ self, mock_gtsv, clean_thread_local
+ ):
+ """When ui_element is missing from the dict, 'text' is used."""
+ mock_gtsv.return_value = "typed"
+ snapshot = {"k": {"value": 10}}
+ get_setting_from_snapshot("k", settings_snapshot=snapshot)
+ mock_gtsv.assert_called_once_with("k", 10, "text")
+
+ def test_raw_non_dict_value(self, clean_thread_local):
+ """A non-dict raw value (e.g. list) is returned as-is."""
+ snapshot = {"tags": ["a", "b"]}
+ result = get_setting_from_snapshot("tags", settings_snapshot=snapshot)
+ assert result == ["a", "b"]
+
+ def test_dict_without_value_key_returned_as_is(self, clean_thread_local):
+ """A dict that does NOT contain a 'value' key is returned unchanged
+ (it is treated as a raw value, not as the full-format dict)."""
+ snapshot = {"cfg": {"host": "localhost", "port": 8080}}
+ result = get_setting_from_snapshot("cfg", settings_snapshot=snapshot)
+ assert result == {"host": "localhost", "port": 8080}
+
+
+class TestGetSettingFromSnapshotChildKeys:
+ """Tests for child-key aggregation logic."""
+
+ def test_child_key_aggregation(self, clean_thread_local):
+ """Keys starting with 'parent.' are collected into a dict."""
+ snapshot = {
+ "parent.sub1": "v1",
+ "parent.sub2": "v2",
+ }
+ result = get_setting_from_snapshot("parent", settings_snapshot=snapshot)
+ assert result == {"sub1": "v1", "sub2": "v2"}
+
+ def test_single_child_key(self, clean_thread_local):
+ """A single matching child key still produces a dict."""
+ snapshot = {"section.only_child": 99}
+ result = get_setting_from_snapshot(
+ "section", settings_snapshot=snapshot
+ )
+ assert result == {"only_child": 99}
+
+ @patch("local_deep_research.config.thread_settings.get_typed_setting_value")
+ def test_child_key_dict_format(self, mock_gtsv, clean_thread_local):
+ """Child keys in full dict format trigger get_typed_setting_value."""
+ mock_gtsv.return_value = "typed_child"
+ snapshot = {
+ "parent.child": {"value": "raw_child", "ui_element": "checkbox"},
+ }
+ result = get_setting_from_snapshot("parent", settings_snapshot=snapshot)
+ mock_gtsv.assert_called_once_with("parent", "raw_child", "checkbox")
+ assert result == {"child": "typed_child"}
+
+ def test_no_partial_prefix_confusion(self, clean_thread_local):
+ """'search_extra.x' must NOT match parent key 'search'."""
+ snapshot = {
+ "search_extra.engine": "nope",
+ "search.engine": "yes",
+ }
+ result = get_setting_from_snapshot("search", settings_snapshot=snapshot)
+ assert result == {"engine": "yes"}
+
+
+class TestGetSettingFromSnapshotThreadContext:
+ """Tests for falling back to the thread-local settings context."""
+
+ def test_falls_back_to_thread_context(self, clean_thread_local):
+ """When key not in snapshot, the thread context is consulted."""
+ ctx = MagicMock()
+ ctx.get_setting.return_value = "from_ctx"
+ set_settings_context(ctx)
+ result = get_setting_from_snapshot(
+ "missing_key", settings_snapshot={"other": 1}
+ )
+ assert result == "from_ctx"
+ ctx.get_setting.assert_called_once_with("missing_key", None)
+
+ def test_thread_context_dict_format_extraction(self, clean_thread_local):
+ """If the thread context returns a dict with 'value', the inner value
+ is extracted."""
+ ctx = MagicMock()
+ ctx.get_setting.return_value = {"value": "inner"}
+ set_settings_context(ctx)
+ result = get_setting_from_snapshot("key")
+ assert result == "inner"
+
+ def test_thread_context_plain_value(self, clean_thread_local):
+ """Thread context returning a plain value passes it through."""
+ ctx = MagicMock()
+ ctx.get_setting.return_value = 7
+ set_settings_context(ctx)
+ result = get_setting_from_snapshot("key")
+ assert result == 7
+
+ def test_thread_context_with_default_passes_default(
+ self, clean_thread_local
+ ):
+ """The default argument is forwarded to context.get_setting."""
+ ctx = MagicMock()
+ ctx.get_setting.return_value = "fallback"
+ set_settings_context(ctx)
+ get_setting_from_snapshot("k", default="fallback")
+ ctx.get_setting.assert_called_once_with("k", "fallback")
+
+ def test_empty_snapshot_falls_back_to_context(self, clean_thread_local):
+ """An empty snapshot dict (truthy={} is falsy) skips snapshot lookup
+ and goes to thread context."""
+ ctx = MagicMock()
+ ctx.get_setting.return_value = "ctx_val"
+ set_settings_context(ctx)
+ # Note: {} is falsy in Python, so `if settings_snapshot` is False
+ result = get_setting_from_snapshot("k", settings_snapshot={})
+ assert result == "ctx_val"
+
+
+class TestGetSettingFromSnapshotDefaults:
+ """Tests for default value handling and error raising."""
+
+ def test_returns_default_when_nothing_found(self, clean_thread_local):
+ """When snapshot misses, no context, and a default is given, return it."""
+ result = get_setting_from_snapshot("key", default="def_val")
+ assert result == "def_val"
+
+ def test_raises_no_settings_context_error_when_no_default(
+ self, clean_thread_local
+ ):
+ """With no snapshot, no context, and no default, raises
+ NoSettingsContextError."""
+ with pytest.raises(NoSettingsContextError, match="key_xyz"):
+ get_setting_from_snapshot("key_xyz")
+
+ def test_none_snapshot_and_no_context_with_default(
+ self, clean_thread_local
+ ):
+ """None snapshot + no context + default provided -> returns default."""
+ result = get_setting_from_snapshot(
+ "x", default="safe", settings_snapshot=None
+ )
+ assert result == "safe"
+
+ def test_none_default_still_raises(self, clean_thread_local):
+ """Explicitly passing default=None still raises (it is the sentinel
+ checked via `if default is not None`)."""
+ with pytest.raises(NoSettingsContextError):
+ get_setting_from_snapshot("missing", default=None)
+
+
+class TestGetSettingFromSnapshotFallbackLLM:
+ """Tests for check_fallback_llm behaviour."""
+
+ def test_fallback_llm_env_returns_default(
+ self, clean_thread_local, monkeypatch
+ ):
+ """When LDR_USE_FALLBACK_LLM is set and check_fallback_llm=True,
+ the default is returned."""
+ monkeypatch.setenv("LDR_USE_FALLBACK_LLM", "1")
+ monkeypatch.delenv("LDR_TESTING_WITH_MOCKS", raising=False)
+ result = get_setting_from_snapshot(
+ "llm.key", default="fb_default", check_fallback_llm=True
+ )
+ assert result == "fb_default"
+
+ def test_fallback_llm_env_returns_none_default(
+ self, clean_thread_local, monkeypatch
+ ):
+ """Even None default is returned when fallback LLM env is set."""
+ monkeypatch.setenv("LDR_USE_FALLBACK_LLM", "yes")
+ monkeypatch.delenv("LDR_TESTING_WITH_MOCKS", raising=False)
+ result = get_setting_from_snapshot(
+ "llm.key", default=None, check_fallback_llm=True
+ )
+ assert result is None
+
+ def test_testing_with_mocks_skips_fallback(
+ self, clean_thread_local, monkeypatch
+ ):
+ """When LDR_TESTING_WITH_MOCKS is also set, the fallback path is
+ skipped."""
+ monkeypatch.setenv("LDR_USE_FALLBACK_LLM", "1")
+ monkeypatch.setenv("LDR_TESTING_WITH_MOCKS", "1")
+ # No context and no default -> should raise
+ with pytest.raises(NoSettingsContextError):
+ get_setting_from_snapshot("llm.key", check_fallback_llm=True)
+
+ def test_check_fallback_false_ignores_env(
+ self, clean_thread_local, monkeypatch
+ ):
+ """When check_fallback_llm=False, the env var is irrelevant."""
+ monkeypatch.setenv("LDR_USE_FALLBACK_LLM", "1")
+ monkeypatch.delenv("LDR_TESTING_WITH_MOCKS", raising=False)
+ # check_fallback_llm defaults to False, so default path runs instead
+ result = get_setting_from_snapshot("key", default="normal_default")
+ assert result == "normal_default"
+
+ def test_snapshot_value_takes_precedence_over_fallback(
+ self, clean_thread_local, monkeypatch
+ ):
+ """Even with fallback env set, a snapshot hit returns the snapshot value."""
+ monkeypatch.setenv("LDR_USE_FALLBACK_LLM", "1")
+ monkeypatch.delenv("LDR_TESTING_WITH_MOCKS", raising=False)
+ snapshot = {"key": "snap_val"}
+ result = get_setting_from_snapshot(
+ "key",
+ default="fb_default",
+ settings_snapshot=snapshot,
+ check_fallback_llm=True,
+ )
+ assert result == "snap_val"
+
+
+# ---------------------------------------------------------------------------
+# get_llm_setting_from_snapshot
+# ---------------------------------------------------------------------------
+
+
+class TestGetLlmSettingFromSnapshot:
+ """Tests for the get_llm_setting_from_snapshot convenience wrapper."""
+
+ def test_delegates_with_check_fallback_llm_true(self, clean_thread_local):
+ """Should call get_setting_from_snapshot with check_fallback_llm=True."""
+ with patch(
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
+ ) as mock_gs:
+ mock_gs.return_value = "result"
+ result = get_llm_setting_from_snapshot(
+ "llm.model",
+ default="gpt-4",
+ username="user1",
+ settings_snapshot={"llm.model": "gpt-3.5"},
+ )
+ mock_gs.assert_called_once_with(
+ "llm.model",
+ "gpt-4",
+ "user1",
+ {"llm.model": "gpt-3.5"},
+ check_fallback_llm=True,
+ )
+ assert result == "result"
+
+ def test_returns_expected_value_from_snapshot(self, clean_thread_local):
+ """End-to-end: returns value from snapshot dict."""
+ snapshot = {"llm.model": "claude-3"}
+ result = get_llm_setting_from_snapshot(
+ "llm.model", settings_snapshot=snapshot
+ )
+ assert result == "claude-3"
+
+
+# ---------------------------------------------------------------------------
+# get_bool_setting_from_snapshot
+# ---------------------------------------------------------------------------
+
+
+class TestGetBoolSettingFromSnapshot:
+ """Tests for get_bool_setting_from_snapshot boolean conversion."""
+
+ @patch("local_deep_research.config.thread_settings.to_bool")
+ def test_calls_to_bool_with_value_and_default(
+ self, mock_to_bool, clean_thread_local
+ ):
+ """Should pass the retrieved value and the default to to_bool."""
+ mock_to_bool.return_value = True
+ snapshot = {"flag": "yes"}
+ get_bool_setting_from_snapshot(
+ "flag", default=False, settings_snapshot=snapshot
+ )
+ mock_to_bool.assert_called_once_with("yes", False)
+
+ def test_converts_string_true_to_true(self, clean_thread_local):
+ """String 'true' is converted to boolean True."""
+ snapshot = {"flag": "true"}
+ assert (
+ get_bool_setting_from_snapshot("flag", settings_snapshot=snapshot)
+ is True
+ )
+
+ def test_converts_string_false_to_false(self, clean_thread_local):
+ """String 'false' is converted to boolean False."""
+ snapshot = {"flag": "false"}
+ assert (
+ get_bool_setting_from_snapshot("flag", settings_snapshot=snapshot)
+ is False
+ )
+
+ def test_uses_default_when_not_found(self, clean_thread_local):
+ """When key is missing, the default boolean is returned."""
+ result = get_bool_setting_from_snapshot(
+ "missing", default=True, settings_snapshot={"other": 1}
+ )
+ assert result is True
+
+ def test_passes_through_boolean_true(self, clean_thread_local):
+ """A native boolean True in the snapshot passes through unchanged."""
+ snapshot = {"flag": True}
+ assert (
+ get_bool_setting_from_snapshot("flag", settings_snapshot=snapshot)
+ is True
+ )
+
+ def test_passes_through_boolean_false(self, clean_thread_local):
+ """A native boolean False in the snapshot passes through unchanged."""
+ snapshot = {"flag": False}
+ # False is falsy but still a valid value for the snapshot; however
+ # the code checks `if value is not None` before returning so False
+ # goes through the normal return -> to_bool(False, default) -> False
+ assert (
+ get_bool_setting_from_snapshot(
+ "flag", default=True, settings_snapshot=snapshot
+ )
+ is False
+ )
+
+ def test_converts_string_one_to_true(self, clean_thread_local):
+ """String '1' is converted to boolean True by to_bool."""
+ snapshot = {"flag": "1"}
+ assert (
+ get_bool_setting_from_snapshot("flag", settings_snapshot=snapshot)
+ is True
+ )
+
+ def test_converts_string_zero_to_false(self, clean_thread_local):
+ """String '0' is converted to boolean False by to_bool."""
+ snapshot = {"flag": "0"}
+ assert (
+ get_bool_setting_from_snapshot("flag", settings_snapshot=snapshot)
+ is False
+ )
+
+ def test_check_fallback_llm_passed_through(
+ self, clean_thread_local, monkeypatch
+ ):
+ """The check_fallback_llm flag is forwarded to get_setting_from_snapshot."""
+ monkeypatch.setenv("LDR_USE_FALLBACK_LLM", "1")
+ monkeypatch.delenv("LDR_TESTING_WITH_MOCKS", raising=False)
+ result = get_bool_setting_from_snapshot(
+ "missing_key",
+ default=True,
+ check_fallback_llm=True,
+ )
+ # Fallback path returns the default (True), then to_bool(True, True) -> True
+ assert result is True
diff --git a/tests/database/models/test_download_tracker_models.py b/tests/database/models/test_download_tracker_models.py
new file mode 100644
index 0000000000..ec34032146
--- /dev/null
+++ b/tests/database/models/test_download_tracker_models.py
@@ -0,0 +1,424 @@
+"""
+Tests for download tracking models (DownloadTracker, DownloadDuplicates, DownloadAttempt).
+
+Tests model structure, column constraints, default values, and __repr__ methods
+WITHOUT requiring a real database -- uses direct attribute assignment on model instances.
+"""
+
+from sqlalchemy import Boolean, Integer, String, Text
+
+from local_deep_research.database.models.download_tracker import (
+ DownloadAttempt,
+ DownloadDuplicates,
+ DownloadTracker,
+)
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _col(model_cls, name):
+ """Return a Column object from a model's __table__."""
+ return model_cls.__table__.columns[name]
+
+
+def _make(model_cls, **kwargs):
+ """Instantiate a model via its normal constructor (no DB session needed).
+
+ SQLAlchemy's declarative ``__init__`` accepts column names as keyword
+ arguments and properly initialises the instance state so that
+ instrumented attribute access (used by ``__repr__``) works correctly.
+ """
+ return model_cls(**kwargs)
+
+
+# ===========================================================================
+# DownloadTracker
+# ===========================================================================
+
+
+class TestDownloadTrackerTablename:
+ """Test 1: __tablename__ is 'download_tracker'."""
+
+ def test_tablename(self):
+ assert DownloadTracker.__tablename__ == "download_tracker"
+
+
+class TestDownloadTrackerColumns:
+ """Test 2: Column types and nullable constraints."""
+
+ def test_url_column_is_text_and_not_nullable(self):
+ col = _col(DownloadTracker, "url")
+ assert isinstance(col.type, Text)
+ assert col.nullable is False
+
+ def test_url_hash_is_string64_not_nullable_unique_indexed(self):
+ col = _col(DownloadTracker, "url_hash")
+ assert isinstance(col.type, String)
+ assert col.type.length == 64
+ assert col.nullable is False
+ assert col.unique is True
+ assert col.index is True
+
+ def test_first_resource_id_is_integer_not_nullable(self):
+ col = _col(DownloadTracker, "first_resource_id")
+ assert isinstance(col.type, Integer)
+ assert col.nullable is False
+
+ def test_first_resource_id_has_foreign_key(self):
+ col = _col(DownloadTracker, "first_resource_id")
+ fk_targets = [fk.target_fullname for fk in col.foreign_keys]
+ assert "research_resources.id" in fk_targets
+
+ def test_file_hash_is_nullable(self):
+ col = _col(DownloadTracker, "file_hash")
+ assert isinstance(col.type, String)
+ assert col.type.length == 64
+ assert col.nullable is True
+ assert col.index is True
+
+ def test_file_path_is_nullable_text(self):
+ col = _col(DownloadTracker, "file_path")
+ assert isinstance(col.type, Text)
+ assert col.nullable is True
+
+ def test_file_name_is_nullable_string255_indexed(self):
+ col = _col(DownloadTracker, "file_name")
+ assert isinstance(col.type, String)
+ assert col.type.length == 255
+ assert col.nullable is True
+ assert col.index is True
+
+ def test_file_size_is_nullable_integer(self):
+ col = _col(DownloadTracker, "file_size")
+ assert isinstance(col.type, Integer)
+ assert col.nullable is True
+
+ def test_is_downloaded_is_boolean_not_nullable_indexed(self):
+ col = _col(DownloadTracker, "is_downloaded")
+ assert isinstance(col.type, Boolean)
+ assert col.nullable is False
+ assert col.index is True
+
+ def test_is_accessible_is_boolean(self):
+ col = _col(DownloadTracker, "is_accessible")
+ assert isinstance(col.type, Boolean)
+
+ def test_downloaded_at_is_nullable(self):
+ col = _col(DownloadTracker, "downloaded_at")
+ assert col.nullable is True
+
+ def test_first_seen_is_not_nullable(self):
+ col = _col(DownloadTracker, "first_seen")
+ assert col.nullable is False
+
+ def test_last_checked_is_not_nullable(self):
+ col = _col(DownloadTracker, "last_checked")
+ assert col.nullable is False
+
+ def test_library_document_id_is_nullable_with_fk(self):
+ col = _col(DownloadTracker, "library_document_id")
+ assert isinstance(col.type, Integer)
+ assert col.nullable is True
+ fk_targets = [fk.target_fullname for fk in col.foreign_keys]
+ assert "documents.id" in fk_targets
+
+ def test_id_is_primary_key_autoincrement(self):
+ col = _col(DownloadTracker, "id")
+ assert col.primary_key is True
+ assert col.autoincrement is True
+
+
+class TestDownloadTrackerReprDownloaded:
+ """Test 3: __repr__ shows 'downloaded' when is_downloaded=True."""
+
+ def test_repr_downloaded(self):
+ obj = _make(
+ DownloadTracker,
+ url_hash="abcdef1234567890",
+ is_downloaded=True,
+ )
+ result = repr(obj)
+ assert "downloaded" in result
+ assert "not downloaded" not in result
+
+
+class TestDownloadTrackerReprNotDownloaded:
+ """Test 4: __repr__ shows 'not downloaded' when is_downloaded=False."""
+
+ def test_repr_not_downloaded(self):
+ obj = _make(
+ DownloadTracker,
+ url_hash="abcdef1234567890",
+ is_downloaded=False,
+ )
+ result = repr(obj)
+ assert "not downloaded" in result
+
+
+class TestDownloadTrackerReprTruncation:
+ """Test 5: __repr__ truncates url_hash to first 8 characters."""
+
+ def test_repr_truncates_url_hash(self):
+ full_hash = "a1b2c3d4e5f6g7h8i9j0"
+ obj = _make(
+ DownloadTracker,
+ url_hash=full_hash,
+ is_downloaded=False,
+ )
+ result = repr(obj)
+ assert "a1b2c3d4..." in result
+ # The full hash should NOT appear in the repr
+ assert full_hash not in result
+
+
+class TestDownloadTrackerDefaultIsDownloaded:
+ """Test 6: Default is_downloaded is False."""
+
+ def test_default_is_downloaded(self):
+ col = _col(DownloadTracker, "is_downloaded")
+ assert col.default is not None
+ assert col.default.arg is False
+
+
+class TestDownloadTrackerDefaultIsAccessible:
+ """Test 7: Default is_accessible is True."""
+
+ def test_default_is_accessible(self):
+ col = _col(DownloadTracker, "is_accessible")
+ assert col.default is not None
+ assert col.default.arg is True
+
+
+# ===========================================================================
+# DownloadDuplicates
+# ===========================================================================
+
+
+class TestDownloadDuplicatesTablename:
+ """Test 8: __tablename__ is 'download_duplicates'."""
+
+ def test_tablename(self):
+ assert DownloadDuplicates.__tablename__ == "download_duplicates"
+
+
+class TestDownloadDuplicatesUniqueConstraint:
+ """Test 9: Has UniqueConstraint on (url_hash, resource_id)."""
+
+ def test_unique_constraint_exists(self):
+ table = DownloadDuplicates.__table__
+ unique_constraints = [
+ c
+ for c in table.constraints
+ if c.__class__.__name__ == "UniqueConstraint"
+ ]
+ # Find the constraint named 'uix_url_resource'
+ matching = [
+ c for c in unique_constraints if c.name == "uix_url_resource"
+ ]
+ assert len(matching) == 1
+ col_names = {col.name for col in matching[0].columns}
+ assert col_names == {"url_hash", "resource_id"}
+
+
+class TestDownloadDuplicatesRepr:
+ """Test 10: __repr__ shows url_hash and resource_id."""
+
+ def test_repr_content(self):
+ obj = _make(
+ DownloadDuplicates,
+ url_hash="deadbeef12345678",
+ resource_id=42,
+ )
+ result = repr(obj)
+ assert "deadbeef..." in result
+ assert "resource_id=42" in result
+ assert "DownloadDuplicates" in result
+
+
+class TestDownloadDuplicatesCompositeIndex:
+ """Test 11: Has composite index on (research_id, url_hash)."""
+
+ def test_composite_index_exists(self):
+ table = DownloadDuplicates.__table__
+ index_names = {idx.name for idx in table.indexes}
+ assert "idx_research_duplicates" in index_names
+
+ # Verify the columns in the index
+ target_index = next(
+ idx
+ for idx in table.indexes
+ if idx.name == "idx_research_duplicates"
+ )
+ col_names = [col.name for col in target_index.columns]
+ assert "research_id" in col_names
+ assert "url_hash" in col_names
+
+
+class TestDownloadDuplicatesColumns:
+ """Additional column validation for DownloadDuplicates."""
+
+ def test_url_hash_not_nullable_with_fk(self):
+ col = _col(DownloadDuplicates, "url_hash")
+ assert col.nullable is False
+ fk_targets = [fk.target_fullname for fk in col.foreign_keys]
+ assert "download_tracker.url_hash" in fk_targets
+
+ def test_resource_id_not_nullable_with_fk(self):
+ col = _col(DownloadDuplicates, "resource_id")
+ assert col.nullable is False
+ fk_targets = [fk.target_fullname for fk in col.foreign_keys]
+ assert "research_resources.id" in fk_targets
+
+ def test_research_id_not_nullable_indexed(self):
+ col = _col(DownloadDuplicates, "research_id")
+ assert isinstance(col.type, String)
+ assert col.type.length == 36
+ assert col.nullable is False
+ assert col.index is True
+
+ def test_added_at_not_nullable(self):
+ col = _col(DownloadDuplicates, "added_at")
+ assert col.nullable is False
+
+
+# ===========================================================================
+# DownloadAttempt
+# ===========================================================================
+
+
+class TestDownloadAttemptTablename:
+ """Test 12: __tablename__ is 'download_attempts'."""
+
+ def test_tablename(self):
+ assert DownloadAttempt.__tablename__ == "download_attempts"
+
+
+class TestDownloadAttemptReprSuccess:
+ """Test 13: __repr__ shows 'success' when succeeded=True."""
+
+ def test_repr_success(self):
+ obj = _make(
+ DownloadAttempt,
+ attempt_number=1,
+ succeeded=True,
+ status_code=200,
+ error_type=None,
+ )
+ result = repr(obj)
+ assert "success" in result
+ assert "failed" not in result
+ assert "attempt=1" in result
+
+
+class TestDownloadAttemptReprFailedWithStatusCode:
+ """Test 14: __repr__ shows 'failed (404)' when succeeded=False, status_code=404."""
+
+ def test_repr_failed_status_code(self):
+ obj = _make(
+ DownloadAttempt,
+ attempt_number=2,
+ succeeded=False,
+ status_code=404,
+ error_type=None,
+ )
+ result = repr(obj)
+ assert "failed (404)" in result
+ assert "attempt=2" in result
+
+
+class TestDownloadAttemptReprFailedWithErrorType:
+ """Test 15: __repr__ shows 'failed (timeout)' when no status_code, error_type='timeout'."""
+
+ def test_repr_failed_error_type(self):
+ obj = _make(
+ DownloadAttempt,
+ attempt_number=3,
+ succeeded=False,
+ status_code=None,
+ error_type="timeout",
+ )
+ result = repr(obj)
+ assert "failed (timeout)" in result
+ assert "attempt=3" in result
+
+
+class TestDownloadAttemptReprFailedNoInfo:
+ """Test 16: __repr__ shows 'failed (None)' when no status_code or error_type."""
+
+ def test_repr_failed_none(self):
+ obj = _make(
+ DownloadAttempt,
+ attempt_number=1,
+ succeeded=False,
+ status_code=None,
+ error_type=None,
+ )
+ result = repr(obj)
+ assert "failed (None)" in result
+
+
+class TestDownloadAttemptDefaultSucceeded:
+ """Test 17: Default succeeded is False."""
+
+ def test_default_succeeded(self):
+ col = _col(DownloadAttempt, "succeeded")
+ assert col.default is not None
+ assert col.default.arg is False
+
+
+class TestDownloadAttemptColumns:
+ """Additional column validation for DownloadAttempt."""
+
+ def test_url_hash_not_nullable_with_fk(self):
+ col = _col(DownloadAttempt, "url_hash")
+ assert col.nullable is False
+ assert col.index is True
+ fk_targets = [fk.target_fullname for fk in col.foreign_keys]
+ assert "download_tracker.url_hash" in fk_targets
+
+ def test_attempt_number_not_nullable(self):
+ col = _col(DownloadAttempt, "attempt_number")
+ assert isinstance(col.type, Integer)
+ assert col.nullable is False
+
+ def test_status_code_nullable(self):
+ col = _col(DownloadAttempt, "status_code")
+ assert isinstance(col.type, Integer)
+ assert col.nullable is True
+
+ def test_error_type_nullable_string100(self):
+ col = _col(DownloadAttempt, "error_type")
+ assert isinstance(col.type, String)
+ assert col.type.length == 100
+ assert col.nullable is True
+
+ def test_error_message_nullable_text(self):
+ col = _col(DownloadAttempt, "error_message")
+ assert isinstance(col.type, Text)
+ assert col.nullable is True
+
+ def test_attempted_at_not_nullable(self):
+ col = _col(DownloadAttempt, "attempted_at")
+ assert col.nullable is False
+
+ def test_duration_ms_nullable(self):
+ col = _col(DownloadAttempt, "duration_ms")
+ assert isinstance(col.type, Integer)
+ assert col.nullable is True
+
+ def test_succeeded_not_nullable(self):
+ col = _col(DownloadAttempt, "succeeded")
+ assert isinstance(col.type, Boolean)
+ assert col.nullable is False
+
+ def test_bytes_downloaded_nullable(self):
+ col = _col(DownloadAttempt, "bytes_downloaded")
+ assert isinstance(col.type, Integer)
+ assert col.nullable is True
+
+ def test_id_primary_key(self):
+ col = _col(DownloadAttempt, "id")
+ assert col.primary_key is True
diff --git a/tests/database/models/test_file_integrity_models.py b/tests/database/models/test_file_integrity_models.py
new file mode 100644
index 0000000000..fcb7659310
--- /dev/null
+++ b/tests/database/models/test_file_integrity_models.py
@@ -0,0 +1,1025 @@
+"""
+Comprehensive tests for file integrity and report SQLAlchemy models.
+
+Tests cover structural inspection (columns, types, constraints, defaults,
+indexes, foreign keys) and __repr__ output for:
+
+- FileIntegrityRecord
+- FileVerificationFailure
+- Report
+- ReportSection
+
+All tests run WITHOUT a real database by inspecting the SQLAlchemy
+`__table__` metadata and by instantiating model objects with keyword args.
+"""
+
+import pytest
+from sqlalchemy import Boolean, Float, Integer, String, Text
+from sqlalchemy import JSON as SA_JSON
+from sqlalchemy_utc import UtcDateTime
+
+from local_deep_research.database.models.file_integrity import (
+ FileIntegrityRecord,
+ FileVerificationFailure,
+)
+from local_deep_research.database.models.reports import (
+ Report,
+ ReportSection,
+)
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _col(model, name):
+ """Return a column object from the model's table metadata."""
+ return model.__table__.columns[name]
+
+
+def _col_names(model):
+ """Return the set of all column names for a model."""
+ return set(model.__table__.columns.keys())
+
+
+def _pk_col_names(model):
+ """Return the set of primary key column names."""
+ return {c.name for c in model.__table__.primary_key.columns}
+
+
+def _fk_targets(model, col_name):
+ """Return the set of foreign key target strings for a column."""
+ return {fk.target_fullname for fk in _col(model, col_name).foreign_keys}
+
+
+def _has_index(model, col_name):
+ """Check whether a column participates in at least one index."""
+ for index in model.__table__.indexes:
+ if col_name in {c.name for c in index.columns}:
+ return True
+ return False
+
+
+def _has_unique_constraint(model, col_name):
+ """Check whether a column has a unique constraint (column-level or table-level)."""
+ col = _col(model, col_name)
+ if col.unique:
+ return True
+ for uc in model.__table__.constraints:
+ if hasattr(uc, "columns") and col_name in {c.name for c in uc.columns}:
+ if getattr(uc, "_pending_colargs", None) is not None:
+ continue
+ from sqlalchemy import UniqueConstraint
+
+ if isinstance(uc, UniqueConstraint):
+ return True
+ return False
+
+
+# ============================================================================
+# FileIntegrityRecord
+# ============================================================================
+
+
+class TestFileIntegrityRecordTableName:
+ """Verify the __tablename__ value."""
+
+ def test_tablename(self):
+ assert FileIntegrityRecord.__tablename__ == "file_integrity_records"
+
+
+class TestFileIntegrityRecordColumns:
+ """Verify that all expected columns exist."""
+
+ EXPECTED_COLUMNS = {
+ "id",
+ "file_path",
+ "file_type",
+ "checksum",
+ "algorithm",
+ "file_size",
+ "file_mtime",
+ "verify_on_load",
+ "allow_modifications",
+ "total_verifications",
+ "last_verified_at",
+ "last_verification_passed",
+ "consecutive_successes",
+ "consecutive_failures",
+ "created_at",
+ "updated_at",
+ "related_entity_type",
+ "related_entity_id",
+ }
+
+ def test_all_expected_columns_present(self):
+ actual = _col_names(FileIntegrityRecord)
+ missing = self.EXPECTED_COLUMNS - actual
+ assert not missing, f"Missing columns: {missing}"
+
+ def test_no_unexpected_columns(self):
+ actual = _col_names(FileIntegrityRecord)
+ extra = actual - self.EXPECTED_COLUMNS
+ assert not extra, f"Unexpected columns: {extra}"
+
+
+class TestFileIntegrityRecordColumnTypes:
+ """Verify the SQLAlchemy column type for each column."""
+
+ @pytest.mark.parametrize(
+ "col_name, expected_type",
+ [
+ ("id", Integer),
+ ("file_path", Text),
+ ("file_type", String),
+ ("checksum", String),
+ ("algorithm", String),
+ ("file_size", Integer),
+ ("file_mtime", Float),
+ ("verify_on_load", Boolean),
+ ("allow_modifications", Boolean),
+ ("total_verifications", Integer),
+ ("last_verified_at", UtcDateTime),
+ ("last_verification_passed", Boolean),
+ ("consecutive_successes", Integer),
+ ("consecutive_failures", Integer),
+ ("created_at", UtcDateTime),
+ ("updated_at", UtcDateTime),
+ ("related_entity_type", String),
+ ("related_entity_id", Integer),
+ ],
+ )
+ def test_column_type(self, col_name, expected_type):
+ col = _col(FileIntegrityRecord, col_name)
+ assert isinstance(col.type, expected_type), (
+ f"Column '{col_name}' type is {type(col.type).__name__}, "
+ f"expected {expected_type.__name__}"
+ )
+
+
+class TestFileIntegrityRecordStringLengths:
+ """Verify length limits on String columns."""
+
+ @pytest.mark.parametrize(
+ "col_name, expected_length",
+ [
+ ("file_type", 50),
+ ("checksum", 64),
+ ("algorithm", 20),
+ ("related_entity_type", 50),
+ ],
+ )
+ def test_string_length(self, col_name, expected_length):
+ col = _col(FileIntegrityRecord, col_name)
+ assert col.type.length == expected_length
+
+
+class TestFileIntegrityRecordNullable:
+ """Verify nullable constraints on each column."""
+
+ @pytest.mark.parametrize(
+ "col_name, expected_nullable",
+ [
+ ("id", False),
+ ("file_path", False),
+ ("file_type", False),
+ ("checksum", False),
+ ("algorithm", True),
+ ("file_size", True),
+ ("file_mtime", True),
+ ("verify_on_load", True),
+ ("allow_modifications", True),
+ ("total_verifications", True),
+ ("last_verified_at", True),
+ ("last_verification_passed", True),
+ ("consecutive_successes", True),
+ ("consecutive_failures", True),
+ ("created_at", True),
+ ("updated_at", True),
+ ("related_entity_type", True),
+ ("related_entity_id", True),
+ ],
+ )
+ def test_nullable(self, col_name, expected_nullable):
+ col = _col(FileIntegrityRecord, col_name)
+ assert col.nullable is expected_nullable, (
+ f"Column '{col_name}' nullable={col.nullable}, "
+ f"expected {expected_nullable}"
+ )
+
+
+class TestFileIntegrityRecordDefaults:
+ """Verify default values set on columns."""
+
+ def test_algorithm_default(self):
+ col = _col(FileIntegrityRecord, "algorithm")
+ assert col.default is not None
+ assert col.default.arg == "sha256"
+
+ def test_verify_on_load_default(self):
+ col = _col(FileIntegrityRecord, "verify_on_load")
+ assert col.default is not None
+ assert col.default.arg is True
+
+ def test_allow_modifications_default(self):
+ col = _col(FileIntegrityRecord, "allow_modifications")
+ assert col.default is not None
+ assert col.default.arg is False
+
+ def test_total_verifications_default(self):
+ col = _col(FileIntegrityRecord, "total_verifications")
+ assert col.default is not None
+ assert col.default.arg == 0
+
+ def test_last_verification_passed_default(self):
+ col = _col(FileIntegrityRecord, "last_verification_passed")
+ assert col.default is not None
+ assert col.default.arg is True
+
+ def test_consecutive_successes_default(self):
+ col = _col(FileIntegrityRecord, "consecutive_successes")
+ assert col.default is not None
+ assert col.default.arg == 0
+
+ def test_consecutive_failures_default(self):
+ col = _col(FileIntegrityRecord, "consecutive_failures")
+ assert col.default is not None
+ assert col.default.arg == 0
+
+ def test_created_at_has_default(self):
+ col = _col(FileIntegrityRecord, "created_at")
+ assert col.default is not None
+
+ def test_updated_at_has_onupdate(self):
+ col = _col(FileIntegrityRecord, "updated_at")
+ assert col.onupdate is not None
+
+
+class TestFileIntegrityRecordPrimaryKey:
+ """Verify primary key configuration."""
+
+ def test_primary_key_is_id(self):
+ assert _pk_col_names(FileIntegrityRecord) == {"id"}
+
+ def test_id_autoincrement(self):
+ col = _col(FileIntegrityRecord, "id")
+ # autoincrement is True or "auto" (depending on SQLAlchemy version)
+ assert col.autoincrement in (True, "auto")
+
+
+class TestFileIntegrityRecordIndexes:
+ """Verify indexes exist on expected columns."""
+
+ def test_file_path_index(self):
+ assert _has_index(FileIntegrityRecord, "file_path")
+
+ def test_file_type_index(self):
+ assert _has_index(FileIntegrityRecord, "file_type")
+
+
+class TestFileIntegrityRecordUniqueConstraints:
+ """Verify unique constraints on expected columns."""
+
+ def test_file_path_unique(self):
+ assert _has_unique_constraint(FileIntegrityRecord, "file_path")
+
+ def test_checksum_not_unique(self):
+ col = _col(FileIntegrityRecord, "checksum")
+ assert not col.unique
+
+
+class TestFileIntegrityRecordRepr:
+ """Verify __repr__ output format."""
+
+ def test_repr_basic(self):
+ record = FileIntegrityRecord(
+ id=42,
+ file_path="/data/index.faiss",
+ file_type="faiss_index",
+ total_verifications=7,
+ )
+ expected = (
+ "<FileIntegrityRecord(id=42, "
+ "path=/data/index.faiss, "
+ "type=faiss_index, "
+ "verifications=7)>"
+ )
+ assert repr(record) == expected
+
+ def test_repr_none_values(self):
+ record = FileIntegrityRecord()
+ expected = (
+ "<FileIntegrityRecord(id=None, "
+ "path=None, "
+ "type=None, "
+ "verifications=None)>"
+ )
+ assert repr(record) == expected
+
+ def test_repr_empty_strings(self):
+ record = FileIntegrityRecord(
+ id=0,
+ file_path="",
+ file_type="",
+ total_verifications=0,
+ )
+ expected = "<FileIntegrityRecord(id=0, path=, type=, verifications=0)>"
+ assert repr(record) == expected
+
+
+class TestFileIntegrityRecordRelationship:
+ """Verify the verification_failures relationship is declared."""
+
+ def test_has_verification_failures_relationship(self):
+ mapper = FileIntegrityRecord.__mapper__
+ assert "verification_failures" in mapper.relationships
+
+
+# ============================================================================
+# FileVerificationFailure
+# ============================================================================
+
+
+class TestFileVerificationFailureTableName:
+ """Verify the __tablename__ value."""
+
+ def test_tablename(self):
+ assert (
+ FileVerificationFailure.__tablename__
+ == "file_verification_failures"
+ )
+
+
+class TestFileVerificationFailureColumns:
+ """Verify that all expected columns exist."""
+
+ EXPECTED_COLUMNS = {
+ "id",
+ "file_record_id",
+ "verified_at",
+ "expected_checksum",
+ "actual_checksum",
+ "file_size",
+ "failure_reason",
+ }
+
+ def test_all_expected_columns_present(self):
+ actual = _col_names(FileVerificationFailure)
+ missing = self.EXPECTED_COLUMNS - actual
+ assert not missing, f"Missing columns: {missing}"
+
+ def test_no_unexpected_columns(self):
+ actual = _col_names(FileVerificationFailure)
+ extra = actual - self.EXPECTED_COLUMNS
+ assert not extra, f"Unexpected columns: {extra}"
+
+
+class TestFileVerificationFailureColumnTypes:
+ """Verify the SQLAlchemy column type for each column."""
+
+ @pytest.mark.parametrize(
+ "col_name, expected_type",
+ [
+ ("id", Integer),
+ ("file_record_id", Integer),
+ ("verified_at", UtcDateTime),
+ ("expected_checksum", String),
+ ("actual_checksum", String),
+ ("file_size", Integer),
+ ("failure_reason", Text),
+ ],
+ )
+ def test_column_type(self, col_name, expected_type):
+ col = _col(FileVerificationFailure, col_name)
+ assert isinstance(col.type, expected_type)
+
+
+class TestFileVerificationFailureStringLengths:
+ """Verify length limits on String columns."""
+
+ @pytest.mark.parametrize(
+ "col_name, expected_length",
+ [
+ ("expected_checksum", 64),
+ ("actual_checksum", 64),
+ ],
+ )
+ def test_string_length(self, col_name, expected_length):
+ col = _col(FileVerificationFailure, col_name)
+ assert col.type.length == expected_length
+
+
+class TestFileVerificationFailureNullable:
+ """Verify nullable constraints on each column."""
+
+ @pytest.mark.parametrize(
+ "col_name, expected_nullable",
+ [
+ ("id", False),
+ ("file_record_id", False),
+ ("verified_at", True),
+ ("expected_checksum", False),
+ ("actual_checksum", True),
+ ("file_size", True),
+ ("failure_reason", False),
+ ],
+ )
+ def test_nullable(self, col_name, expected_nullable):
+ col = _col(FileVerificationFailure, col_name)
+ assert col.nullable is expected_nullable
+
+
+class TestFileVerificationFailureDefaults:
+ """Verify default values set on columns."""
+
+ def test_verified_at_has_default(self):
+ col = _col(FileVerificationFailure, "verified_at")
+ assert col.default is not None
+
+
+class TestFileVerificationFailurePrimaryKey:
+ """Verify primary key configuration."""
+
+ def test_primary_key_is_id(self):
+ assert _pk_col_names(FileVerificationFailure) == {"id"}
+
+ def test_id_autoincrement(self):
+ col = _col(FileVerificationFailure, "id")
+ assert col.autoincrement in (True, "auto")
+
+
+class TestFileVerificationFailureForeignKeys:
+ """Verify foreign key references."""
+
+ def test_file_record_id_fk(self):
+ targets = _fk_targets(FileVerificationFailure, "file_record_id")
+ assert "file_integrity_records.id" in targets
+
+
+class TestFileVerificationFailureIndexes:
+ """Verify indexes on expected columns."""
+
+ def test_file_record_id_index(self):
+ assert _has_index(FileVerificationFailure, "file_record_id")
+
+
+class TestFileVerificationFailureRepr:
+ """Verify __repr__ output format."""
+
+ def test_repr_basic(self):
+ failure = FileVerificationFailure(
+ id=5,
+ file_record_id=42,
+ failure_reason="checksum_mismatch",
+ verified_at="2025-01-15T10:30:00",
+ )
+ expected = (
+ "<FileVerificationFailure(id=5, "
+ "file_record_id=42, "
+ "reason=checksum_mismatch, "
+ "verified_at=2025-01-15T10:30:00)>"
+ )
+ assert repr(failure) == expected
+
+ def test_repr_none_values(self):
+ failure = FileVerificationFailure()
+ expected = (
+ "<FileVerificationFailure(id=None, "
+ "file_record_id=None, "
+ "reason=None, "
+ "verified_at=None)>"
+ )
+ assert repr(failure) == expected
+
+
+class TestFileVerificationFailureRelationship:
+ """Verify the file_record relationship is declared."""
+
+ def test_has_file_record_relationship(self):
+ mapper = FileVerificationFailure.__mapper__
+ assert "file_record" in mapper.relationships
+
+
+# ============================================================================
+# Report
+# ============================================================================
+
+
+class TestReportTableName:
+ """Verify the __tablename__ value."""
+
+ def test_tablename(self):
+ assert Report.__tablename__ == "reports"
+
+
+class TestReportColumns:
+ """Verify that all expected columns exist."""
+
+ EXPECTED_COLUMNS = {
+ "id",
+ "research_task_id",
+ "title",
+ "subtitle",
+ "abstract",
+ "content",
+ "format",
+ "template",
+ "style",
+ "language",
+ "word_count",
+ "section_count",
+ "reference_count",
+ "image_count",
+ "generation_params",
+ "generation_model",
+ "generation_time_seconds",
+ "version",
+ "is_draft",
+ "created_at",
+ "updated_at",
+ "published_at",
+ }
+
+ def test_all_expected_columns_present(self):
+ actual = _col_names(Report)
+ missing = self.EXPECTED_COLUMNS - actual
+ assert not missing, f"Missing columns: {missing}"
+
+ def test_no_unexpected_columns(self):
+ actual = _col_names(Report)
+ extra = actual - self.EXPECTED_COLUMNS
+ assert not extra, f"Unexpected columns: {extra}"
+
+
+class TestReportColumnTypes:
+ """Verify the SQLAlchemy column type for each column."""
+
+ @pytest.mark.parametrize(
+ "col_name, expected_type",
+ [
+ ("id", Integer),
+ ("research_task_id", Integer),
+ ("title", String),
+ ("subtitle", String),
+ ("abstract", Text),
+ ("content", Text),
+ ("format", String),
+ ("template", String),
+ ("style", String),
+ ("language", String),
+ ("word_count", Integer),
+ ("section_count", Integer),
+ ("reference_count", Integer),
+ ("image_count", Integer),
+ ("generation_params", SA_JSON),
+ ("generation_model", String),
+ ("generation_time_seconds", Float),
+ ("version", Integer),
+ ("is_draft", Boolean),
+ ("created_at", UtcDateTime),
+ ("updated_at", UtcDateTime),
+ ("published_at", UtcDateTime),
+ ],
+ )
+ def test_column_type(self, col_name, expected_type):
+ col = _col(Report, col_name)
+ assert isinstance(col.type, expected_type), (
+ f"Column '{col_name}' type is {type(col.type).__name__}, "
+ f"expected {expected_type.__name__}"
+ )
+
+
+class TestReportStringLengths:
+ """Verify length limits on String columns."""
+
+ @pytest.mark.parametrize(
+ "col_name, expected_length",
+ [
+ ("title", 500),
+ ("subtitle", 500),
+ ("format", 50),
+ ("template", 100),
+ ("style", 100),
+ ("language", 10),
+ ("generation_model", 100),
+ ],
+ )
+ def test_string_length(self, col_name, expected_length):
+ col = _col(Report, col_name)
+ assert col.type.length == expected_length
+
+
+class TestReportNullable:
+ """Verify nullable constraints on columns.
+
+ Note: Columns without explicit nullable=False default to True in SQLAlchemy.
+ """
+
+ @pytest.mark.parametrize(
+ "col_name, expected_nullable",
+ [
+ ("id", False),
+ ("research_task_id", True),
+ ("title", True),
+ ("subtitle", True),
+ ("abstract", True),
+ ("content", True),
+ ("format", True),
+ ("template", True),
+ ("style", True),
+ ("language", True),
+ ("word_count", True),
+ ("section_count", True),
+ ("reference_count", True),
+ ("image_count", True),
+ ("generation_params", True),
+ ("generation_model", True),
+ ("generation_time_seconds", True),
+ ("version", True),
+ ("is_draft", True),
+ ("created_at", True),
+ ("updated_at", True),
+ ("published_at", True),
+ ],
+ )
+ def test_nullable(self, col_name, expected_nullable):
+ col = _col(Report, col_name)
+ assert col.nullable is expected_nullable
+
+
+class TestReportDefaults:
+ """Verify default values set on columns."""
+
+ def test_format_default(self):
+ col = _col(Report, "format")
+ assert col.default is not None
+ assert col.default.arg == "markdown"
+
+ def test_language_default(self):
+ col = _col(Report, "language")
+ assert col.default is not None
+ assert col.default.arg == "en"
+
+ def test_version_default(self):
+ col = _col(Report, "version")
+ assert col.default is not None
+ assert col.default.arg == 1
+
+ def test_is_draft_default(self):
+ col = _col(Report, "is_draft")
+ assert col.default is not None
+ assert col.default.arg is False
+
+ def test_created_at_has_default(self):
+ col = _col(Report, "created_at")
+ assert col.default is not None
+
+ def test_updated_at_has_default(self):
+ col = _col(Report, "updated_at")
+ assert col.default is not None
+
+ def test_updated_at_has_onupdate(self):
+ col = _col(Report, "updated_at")
+ assert col.onupdate is not None
+
+
+class TestReportPrimaryKey:
+ """Verify primary key configuration."""
+
+ def test_primary_key_is_id(self):
+ assert _pk_col_names(Report) == {"id"}
+
+
+class TestReportForeignKeys:
+ """Verify foreign key references."""
+
+ def test_research_task_id_fk(self):
+ targets = _fk_targets(Report, "research_task_id")
+ assert "research_tasks.id" in targets
+
+ def test_research_task_id_fk_ondelete_cascade(self):
+ fks = _col(Report, "research_task_id").foreign_keys
+ for fk in fks:
+ assert fk.ondelete == "CASCADE"
+
+
+class TestReportRepr:
+ """Verify __repr__ output format."""
+
+ def test_repr_basic(self):
+ report = Report(
+ title="Climate Change Analysis",
+ format="markdown",
+ is_draft=False,
+ )
+ expected = "<Report(title='Climate Change Analysis', format='markdown', draft=False)>"
+ assert repr(report) == expected
+
+ def test_repr_draft(self):
+ report = Report(
+ title="Draft Report",
+ format="html",
+ is_draft=True,
+ )
+ expected = "<Report(title='Draft Report', format='html', draft=True)>"
+ assert repr(report) == expected
+
+ def test_repr_none_values(self):
+ report = Report()
+ expected = "<Report(title='None', format='None', draft=None)>"
+ assert repr(report) == expected
+
+ def test_repr_title_with_special_characters(self):
+ report = Report(
+ title="Analysis of O'Brien's Data",
+ format="pdf",
+ is_draft=False,
+ )
+ expected = "<Report(title='Analysis of O'Brien's Data', format='pdf', draft=False)>"
+ assert repr(report) == expected
+
+
+class TestReportRelationships:
+ """Verify relationships are declared on the mapper."""
+
+ def test_has_research_task_relationship(self):
+ mapper = Report.__mapper__
+ assert "research_task" in mapper.relationships
+
+ def test_has_sections_relationship(self):
+ mapper = Report.__mapper__
+ assert "sections" in mapper.relationships
+
+
+# ============================================================================
+# ReportSection
+# ============================================================================
+
+
+class TestReportSectionTableName:
+ """Verify the __tablename__ value."""
+
+ def test_tablename(self):
+ assert ReportSection.__tablename__ == "report_sections"
+
+
+class TestReportSectionColumns:
+ """Verify that all expected columns exist."""
+
+ EXPECTED_COLUMNS = {
+ "id",
+ "report_id",
+ "title",
+ "subtitle",
+ "content",
+ "section_order",
+ "section_type",
+ "section_level",
+ "parent_section_id",
+ "references",
+ "citations",
+ "auto_generated",
+ "edited",
+ "created_at",
+ "updated_at",
+ }
+
+ def test_all_expected_columns_present(self):
+ actual = _col_names(ReportSection)
+ missing = self.EXPECTED_COLUMNS - actual
+ assert not missing, f"Missing columns: {missing}"
+
+ def test_no_unexpected_columns(self):
+ actual = _col_names(ReportSection)
+ extra = actual - self.EXPECTED_COLUMNS
+ assert not extra, f"Unexpected columns: {extra}"
+
+
+class TestReportSectionColumnTypes:
+ """Verify the SQLAlchemy column type for each column."""
+
+ @pytest.mark.parametrize(
+ "col_name, expected_type",
+ [
+ ("id", Integer),
+ ("report_id", Integer),
+ ("title", String),
+ ("subtitle", String),
+ ("content", Text),
+ ("section_order", Integer),
+ ("section_type", String),
+ ("section_level", Integer),
+ ("parent_section_id", Integer),
+ ("references", SA_JSON),
+ ("citations", SA_JSON),
+ ("auto_generated", Boolean),
+ ("edited", Boolean),
+ ("created_at", UtcDateTime),
+ ("updated_at", UtcDateTime),
+ ],
+ )
+ def test_column_type(self, col_name, expected_type):
+ col = _col(ReportSection, col_name)
+ assert isinstance(col.type, expected_type), (
+ f"Column '{col_name}' type is {type(col.type).__name__}, "
+ f"expected {expected_type.__name__}"
+ )
+
+
+class TestReportSectionStringLengths:
+ """Verify length limits on String columns."""
+
+ @pytest.mark.parametrize(
+ "col_name, expected_length",
+ [
+ ("title", 500),
+ ("subtitle", 500),
+ ("section_type", 50),
+ ],
+ )
+ def test_string_length(self, col_name, expected_length):
+ col = _col(ReportSection, col_name)
+ assert col.type.length == expected_length
+
+
+class TestReportSectionNullable:
+ """Verify nullable constraints on columns."""
+
+ @pytest.mark.parametrize(
+ "col_name, expected_nullable",
+ [
+ ("id", False),
+ ("report_id", True),
+ ("title", True),
+ ("subtitle", True),
+ ("content", True),
+ ("section_order", False),
+ ("section_type", True),
+ ("section_level", True),
+ ("parent_section_id", True),
+ ("references", True),
+ ("citations", True),
+ ("auto_generated", True),
+ ("edited", True),
+ ("created_at", True),
+ ("updated_at", True),
+ ],
+ )
+ def test_nullable(self, col_name, expected_nullable):
+ col = _col(ReportSection, col_name)
+ assert col.nullable is expected_nullable
+
+
+class TestReportSectionDefaults:
+ """Verify default values set on columns."""
+
+ def test_section_level_default(self):
+ col = _col(ReportSection, "section_level")
+ assert col.default is not None
+ assert col.default.arg == 1
+
+ def test_auto_generated_default(self):
+ col = _col(ReportSection, "auto_generated")
+ assert col.default is not None
+ assert col.default.arg is True
+
+ def test_edited_default(self):
+ col = _col(ReportSection, "edited")
+ assert col.default is not None
+ assert col.default.arg is False
+
+ def test_created_at_has_default(self):
+ col = _col(ReportSection, "created_at")
+ assert col.default is not None
+
+ def test_updated_at_has_default(self):
+ col = _col(ReportSection, "updated_at")
+ assert col.default is not None
+
+ def test_updated_at_has_onupdate(self):
+ col = _col(ReportSection, "updated_at")
+ assert col.onupdate is not None
+
+
+class TestReportSectionPrimaryKey:
+ """Verify primary key configuration."""
+
+ def test_primary_key_is_id(self):
+ assert _pk_col_names(ReportSection) == {"id"}
+
+
+class TestReportSectionForeignKeys:
+ """Verify foreign key references."""
+
+ def test_report_id_fk(self):
+ targets = _fk_targets(ReportSection, "report_id")
+ assert "reports.id" in targets
+
+ def test_report_id_fk_ondelete_cascade(self):
+ fks = _col(ReportSection, "report_id").foreign_keys
+ for fk in fks:
+ assert fk.ondelete == "CASCADE"
+
+ def test_parent_section_id_fk(self):
+ targets = _fk_targets(ReportSection, "parent_section_id")
+ assert "report_sections.id" in targets
+
+
+class TestReportSectionRepr:
+ """Verify __repr__ output format."""
+
+ def test_repr_basic(self):
+ section = ReportSection(
+ title="Introduction",
+ section_order=1,
+ section_type="introduction",
+ )
+ expected = "<ReportSection(title='Introduction', order=1, type='introduction')>"
+ assert repr(section) == expected
+
+ def test_repr_none_values(self):
+ section = ReportSection()
+ expected = "<ReportSection(title='None', order=None, type='None')>"
+ assert repr(section) == expected
+
+ def test_repr_high_order(self):
+ section = ReportSection(
+ title="Appendix B",
+ section_order=99,
+ section_type="appendix",
+ )
+ expected = (
+ "<ReportSection(title='Appendix B', order=99, type='appendix')>"
+ )
+ assert repr(section) == expected
+
+ def test_repr_references_section(self):
+ section = ReportSection(
+ title="References",
+ section_order=10,
+ section_type="references",
+ )
+ expected = (
+ "<ReportSection(title='References', order=10, type='references')>"
+ )
+ assert repr(section) == expected
+
+
+class TestReportSectionRelationships:
+ """Verify relationships are declared on the mapper."""
+
+ def test_has_report_relationship(self):
+ mapper = ReportSection.__mapper__
+ assert "report" in mapper.relationships
+
+ def test_has_subsections_relationship(self):
+ mapper = ReportSection.__mapper__
+ assert "subsections" in mapper.relationships
+
+
+# ============================================================================
+# Cross-model consistency checks
+# ============================================================================
+
+
+class TestCrossModelConsistency:
+ """Verify consistency across related models."""
+
+ def test_file_integrity_and_failure_fk_alignment(self):
+ """The FK in FileVerificationFailure must point to
+ FileIntegrityRecord's primary key table."""
+ fk_targets = _fk_targets(FileVerificationFailure, "file_record_id")
+ assert f"{FileIntegrityRecord.__tablename__}.id" in fk_targets
+
+ def test_report_section_fk_points_to_report(self):
+ """The FK in ReportSection must point to Report's table."""
+ fk_targets = _fk_targets(ReportSection, "report_id")
+ assert f"{Report.__tablename__}.id" in fk_targets
+
+ def test_report_section_self_referential_fk(self):
+ """The parent_section_id FK must reference ReportSection's own table."""
+ fk_targets = _fk_targets(ReportSection, "parent_section_id")
+ assert f"{ReportSection.__tablename__}.id" in fk_targets
+
+ def test_all_models_share_base(self):
+ """All four models should inherit from the same Base."""
+ for model_cls in [
+ FileIntegrityRecord,
+ FileVerificationFailure,
+ Report,
+ ReportSection,
+ ]:
+ from local_deep_research.database.models.base import Base
+
+ assert issubclass(model_cls, Base)
+
+ def test_all_tablenames_unique(self):
+ """No two models should share the same __tablename__."""
+ names = [
+ FileIntegrityRecord.__tablename__,
+ FileVerificationFailure.__tablename__,
+ Report.__tablename__,
+ ReportSection.__tablename__,
+ ]
+ assert len(names) == len(set(names))
diff --git a/tests/security/test_data_sanitizer_extended.py b/tests/security/test_data_sanitizer_extended.py
new file mode 100644
index 0000000000..59030302be
--- /dev/null
+++ b/tests/security/test_data_sanitizer_extended.py
@@ -0,0 +1,1102 @@
+"""
+Extended security-focused tests for the data_sanitizer module.
+
+Goes beyond the base test suite to cover advanced attack vectors,
+deeply nested credential hiding, realistic metadata payloads,
+and edge cases that could lead to accidental credential leakage.
+"""
+
+import json
+
+import pytest
+
+from local_deep_research.security.data_sanitizer import (
+ DataSanitizer,
+ filter_research_metadata,
+ redact_data,
+ sanitize_data,
+ strip_settings_snapshot,
+)
+
+
+# ---------------------------------------------------------------------------
+# sanitize -- every DEFAULT_SENSITIVE_KEY in every case permutation
+# ---------------------------------------------------------------------------
+class TestSanitizeAllDefaultKeysAllCases:
+ """Ensure each default sensitive key is removed regardless of casing."""
+
+ @pytest.mark.parametrize(
+ "key",
+ sorted(DataSanitizer.DEFAULT_SENSITIVE_KEYS),
+ )
+ def test_lowercase_key_removed(self, key):
+ """Lowercase form of each default key is removed."""
+ data = {"safe": "keep", key: "credential-value"}
+ result = DataSanitizer.sanitize(data)
+ assert key not in result
+ assert result["safe"] == "keep"
+
+ @pytest.mark.parametrize(
+ "key",
+ sorted(DataSanitizer.DEFAULT_SENSITIVE_KEYS),
+ )
+ def test_uppercase_key_removed(self, key):
+ """UPPERCASE form of each default key is removed."""
+ upper = key.upper()
+ data = {"safe": "keep", upper: "credential-value"}
+ result = DataSanitizer.sanitize(data)
+ assert upper not in result
+
+ @pytest.mark.parametrize(
+ "key",
+ sorted(DataSanitizer.DEFAULT_SENSITIVE_KEYS),
+ )
+ def test_titlecase_key_removed(self, key):
+ """Title_Case form of each default key is removed."""
+ title = key.title()
+ data = {"safe": "keep", title: "credential-value"}
+ result = DataSanitizer.sanitize(data)
+ assert title not in result
+
+ @pytest.mark.parametrize(
+ "key",
+ sorted(DataSanitizer.DEFAULT_SENSITIVE_KEYS),
+ )
+ def test_alternating_case_key_removed(self, key):
+ """aLtErNaTiNg case form is removed (case-insensitive guarantee)."""
+ alt = "".join(
+ c.upper() if i % 2 else c.lower() for i, c in enumerate(key)
+ )
+ data = {"safe": "keep", alt: "credential-value"}
+ result = DataSanitizer.sanitize(data)
+ assert alt not in result
+
+
+# ---------------------------------------------------------------------------
+# sanitize -- deeply nested and complex structures
+# ---------------------------------------------------------------------------
+class TestSanitizeDeeplyNested:
+ """Tests for deeply nested and complex structure sanitization."""
+
+ def test_five_levels_deep(self):
+ """Sensitive key removed five levels deep."""
+ data = {
+ "a": {
+ "b": {"c": {"d": {"e": {"password": "deep-secret", "ok": 1}}}}
+ }
+ }
+ result = DataSanitizer.sanitize(data)
+ assert result["a"]["b"]["c"]["d"]["e"] == {"ok": 1}
+
+ def test_mixed_list_and_dict_nesting(self):
+ """Sensitive keys removed in alternating list/dict nesting."""
+ data = {
+ "items": [
+ {
+ "name": "first",
+ "children": [
+ {"api_key": "sk-1", "value": 10},
+ {"api_key": "sk-2", "value": 20},
+ ],
+ }
+ ]
+ }
+ result = DataSanitizer.sanitize(data)
+ children = result["items"][0]["children"]
+ assert len(children) == 2
+ assert all("api_key" not in child for child in children)
+ assert children[0]["value"] == 10
+ assert children[1]["value"] == 20
+
+ def test_list_of_lists_of_dicts(self):
+ """Handles list of lists containing dicts with secrets."""
+ data = [[{"secret": "s1", "x": 1}], [{"secret": "s2", "x": 2}]]
+ result = DataSanitizer.sanitize(data)
+ assert "secret" not in result[0][0]
+ assert "secret" not in result[1][0]
+ assert result[0][0]["x"] == 1
+ assert result[1][0]["x"] == 2
+
+ def test_dict_with_list_of_primitives(self):
+ """Lists of primitives are passed through unchanged."""
+ data = {"tags": ["alpha", "beta", "gamma"], "api_key": "remove-me"}
+ result = DataSanitizer.sanitize(data)
+ assert result["tags"] == ["alpha", "beta", "gamma"]
+ assert "api_key" not in result
+
+ def test_empty_nested_structures(self):
+ """Empty nested dicts and lists are preserved."""
+ data = {"config": {}, "items": [], "secret": "gone"}
+ result = DataSanitizer.sanitize(data)
+ assert result == {"config": {}, "items": []}
+
+
+# ---------------------------------------------------------------------------
+# sanitize -- real-world credential formats
+# ---------------------------------------------------------------------------
+class TestSanitizeRealWorldCredentials:
+ """Ensure realistic credential values are fully removed."""
+
+ def test_openai_api_key_format(self):
+ """OpenAI-style API key removed completely."""
+ data = {"model": "gpt-4", "api_key": "sk-proj-abc123def456ghi789"}
+ result = DataSanitizer.sanitize(data)
+ assert "api_key" not in result
+ assert "sk-proj-abc123def456ghi789" not in str(result)
+
+ def test_jwt_access_token_removed(self):
+ """JWT-formatted access_token removed completely."""
+ jwt = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.sig"
+ data = {"user": "alice", "access_token": jwt}
+ result = DataSanitizer.sanitize(data)
+ assert "access_token" not in result
+ assert jwt not in str(result)
+
+ def test_pem_private_key_removed(self):
+ """PEM-formatted private key value removed."""
+ pem = "-----BEGIN RSA PRIVATE KEY-----\nMIIE...\n-----END RSA PRIVATE KEY-----"
+ data = {"key_id": "k-1", "private_key": pem}
+ result = DataSanitizer.sanitize(data)
+ assert "private_key" not in result
+ assert "BEGIN RSA PRIVATE KEY" not in str(result)
+
+ def test_multiline_secret_removed(self):
+ """Multi-line secret value fully removed."""
+ data = {"secret": "line1\nline2\nline3", "name": "svc"}
+ result = DataSanitizer.sanitize(data)
+ assert "secret" not in result
+ assert "line1" not in str(result)
+
+ def test_very_long_token_removed(self):
+ """Very long token string fully removed."""
+ long_token = "a" * 10000
+ data = {"refresh_token": long_token, "ok": True}
+ result = DataSanitizer.sanitize(data)
+ assert "refresh_token" not in result
+ assert long_token not in str(result)
+
+
+# ---------------------------------------------------------------------------
+# sanitize -- multiple sensitive keys in one dict
+# ---------------------------------------------------------------------------
+class TestSanitizeMultipleKeys:
+ """Multiple sensitive keys in the same dict are all removed."""
+
+ def test_all_ten_default_keys_removed_at_once(self):
+ """All 10 default sensitive keys removed from a single dict."""
+ data = {
+ k: f"value-{i}"
+ for i, k in enumerate(DataSanitizer.DEFAULT_SENSITIVE_KEYS)
+ }
+ data["safe_field"] = "preserved"
+ result = DataSanitizer.sanitize(data)
+ assert result == {"safe_field": "preserved"}
+
+ def test_sensitive_keys_with_various_value_types(self):
+ """Sensitive keys are removed regardless of value type."""
+ data = {
+ "api_key": 12345,
+ "password": None,
+ "secret": ["nested", "list"],
+ "access_token": {"nested": "dict"},
+ "refresh_token": True,
+ "name": "keep",
+ }
+ result = DataSanitizer.sanitize(data)
+ assert set(result.keys()) == {"name"}
+
+
+# ---------------------------------------------------------------------------
+# sanitize -- custom sensitive_keys
+# ---------------------------------------------------------------------------
+class TestSanitizeCustomKeysExtended:
+ """Extended tests for custom sensitive_keys parameter."""
+
+ def test_custom_keys_case_insensitive(self):
+ """Custom keys are also matched case-insensitively."""
+ data = {"MY_CUSTOM_SECRET": "value", "ok": True}
+ result = DataSanitizer.sanitize(
+ data, sensitive_keys={"my_custom_secret"}
+ )
+ assert "MY_CUSTOM_SECRET" not in result
+ assert result["ok"] is True
+
+ def test_custom_keys_do_not_remove_defaults(self):
+ """When custom keys provided, default keys are NOT removed."""
+ data = {"api_key": "stays", "my_field": "goes"}
+ result = DataSanitizer.sanitize(data, sensitive_keys={"my_field"})
+ assert "api_key" in result
+ assert "my_field" not in result
+
+ def test_custom_keys_in_nested_structures(self):
+ """Custom keys work recursively in nested structures."""
+ data = {"outer": {"inner": {"custom_field": "secret", "value": 42}}}
+ result = DataSanitizer.sanitize(data, sensitive_keys={"custom_field"})
+ assert "custom_field" not in result["outer"]["inner"]
+ assert result["outer"]["inner"]["value"] == 42
+
+ def test_single_custom_key(self):
+ """Single-element custom key set works."""
+ data = {"x": "remove", "y": "keep"}
+ result = DataSanitizer.sanitize(data, sensitive_keys={"x"})
+ assert result == {"y": "keep"}
+
+
+# ---------------------------------------------------------------------------
+# sanitize -- immutability guarantees
+# ---------------------------------------------------------------------------
+class TestSanitizeImmutability:
+ """Verify sanitize never mutates the original data."""
+
+ def test_original_dict_unchanged_after_sanitize(self):
+ """Original top-level dict is not mutated."""
+ original = {"api_key": "secret", "name": "test", "password": "pwd"}
+ original_copy = dict(original)
+ DataSanitizer.sanitize(original)
+ assert original == original_copy
+
+ def test_nested_dict_unchanged_after_sanitize(self):
+ """Nested dict inside original is not mutated."""
+ inner = {"api_key": "nested-secret", "value": 1}
+ original = {"config": inner}
+ DataSanitizer.sanitize(original)
+ assert "api_key" in inner
+ assert inner["api_key"] == "nested-secret"
+
+ def test_list_items_unchanged_after_sanitize(self):
+ """List items in original are not mutated."""
+ item = {"password": "p1", "name": "a"}
+ original = [item]
+ DataSanitizer.sanitize(original)
+ assert "password" in item
+ assert item["password"] == "p1"
+
+
+# ---------------------------------------------------------------------------
+# redact -- every DEFAULT_SENSITIVE_KEY in every case permutation
+# ---------------------------------------------------------------------------
+class TestRedactAllDefaultKeysAllCases:
+ """Ensure each default sensitive key is redacted regardless of casing."""
+
+ @pytest.mark.parametrize(
+ "key",
+ sorted(DataSanitizer.DEFAULT_SENSITIVE_KEYS),
+ )
+ def test_lowercase_key_redacted(self, key):
+ """Lowercase form of each default key is redacted."""
+ data = {"safe": "keep", key: "credential-value"}
+ result = DataSanitizer.redact(data)
+ assert result[key] == "[REDACTED]"
+ assert result["safe"] == "keep"
+
+ @pytest.mark.parametrize(
+ "key",
+ sorted(DataSanitizer.DEFAULT_SENSITIVE_KEYS),
+ )
+ def test_uppercase_key_redacted(self, key):
+ """UPPERCASE form of each default key is redacted."""
+ upper = key.upper()
+ data = {"safe": "keep", upper: "credential-value"}
+ result = DataSanitizer.redact(data)
+ assert result[upper] == "[REDACTED]"
+
+ @pytest.mark.parametrize(
+ "key",
+ sorted(DataSanitizer.DEFAULT_SENSITIVE_KEYS),
+ )
+ def test_titlecase_key_redacted(self, key):
+ """Title_Case form of each default key is redacted."""
+ title = key.title()
+ data = {"safe": "keep", title: "credential-value"}
+ result = DataSanitizer.redact(data)
+ assert result[title] == "[REDACTED]"
+
+
+# ---------------------------------------------------------------------------
+# redact -- deeply nested structures
+# ---------------------------------------------------------------------------
+class TestRedactDeeplyNested:
+ """Tests for deeply nested redaction."""
+
+ def test_five_levels_deep(self):
+ """Sensitive key redacted five levels deep."""
+ data = {
+ "a": {
+ "b": {"c": {"d": {"e": {"password": "deep-secret", "ok": 1}}}}
+ }
+ }
+ result = DataSanitizer.redact(data)
+ assert result["a"]["b"]["c"]["d"]["e"]["password"] == "[REDACTED]"
+ assert result["a"]["b"]["c"]["d"]["e"]["ok"] == 1
+
+ def test_mixed_list_and_dict_nesting(self):
+ """Sensitive keys redacted in alternating list/dict nesting."""
+ data = {
+ "items": [
+ {
+ "name": "first",
+ "children": [
+ {"api_key": "sk-1", "value": 10},
+ ],
+ }
+ ]
+ }
+ result = DataSanitizer.redact(data)
+ assert result["items"][0]["children"][0]["api_key"] == "[REDACTED]"
+ assert result["items"][0]["children"][0]["value"] == 10
+
+ def test_list_of_lists_of_dicts_redacted(self):
+ """Handles list of lists containing dicts with secrets."""
+ data = [[{"secret": "s1", "x": 1}], [{"secret": "s2", "x": 2}]]
+ result = DataSanitizer.redact(data)
+ assert result[0][0]["secret"] == "[REDACTED]"
+ assert result[1][0]["secret"] == "[REDACTED]"
+ assert result[0][0]["x"] == 1
+
+
+# ---------------------------------------------------------------------------
+# redact -- custom redaction_text variations
+# ---------------------------------------------------------------------------
+class TestRedactCustomTextVariations:
+ """Extended tests for custom redaction_text."""
+
+ @pytest.mark.parametrize(
+ "text",
+ [
+ "",
+ "***",
+ "<REMOVED>",
+ "N/A",
+ "0" * 100,
+ "null",
+ "undefined",
+ ],
+ )
+ def test_various_redaction_texts(self, text):
+ """Various custom redaction text strings are applied correctly."""
+ data = {"password": "secret123"}
+ result = DataSanitizer.redact(data, redaction_text=text)
+ assert result["password"] == text
+
+ def test_redaction_text_with_special_characters(self):
+ """Redaction text with special chars works."""
+ data = {"api_key": "secret"}
+ result = DataSanitizer.redact(data, redaction_text="<b>HIDDEN</b>")
+ assert result["api_key"] == "<b>HIDDEN</b>"
+
+ def test_redaction_text_with_newlines(self):
+ """Redaction text with newlines works."""
+ data = {"secret": "val"}
+ result = DataSanitizer.redact(data, redaction_text="line1\nline2")
+ assert result["secret"] == "line1\nline2"
+
+
+# ---------------------------------------------------------------------------
+# redact -- immutability guarantees
+# ---------------------------------------------------------------------------
+class TestRedactImmutability:
+ """Verify redact never mutates the original data."""
+
+ def test_original_dict_unchanged_after_redact(self):
+ """Original top-level dict is not mutated."""
+ original = {"password": "secret", "name": "test"}
+ DataSanitizer.redact(original)
+ assert original["password"] == "secret"
+
+ def test_nested_dict_unchanged_after_redact(self):
+ """Nested dict inside original is not mutated."""
+ inner = {"api_key": "nested-secret", "value": 1}
+ original = {"config": inner}
+ DataSanitizer.redact(original)
+ assert inner["api_key"] == "nested-secret"
+
+ def test_list_items_unchanged_after_redact(self):
+ """List items in original are not mutated."""
+ item = {"password": "p1"}
+ original = [item]
+ DataSanitizer.redact(original)
+ assert item["password"] == "p1"
+
+
+# ---------------------------------------------------------------------------
+# redact -- sensitive values with various types are still redacted
+# ---------------------------------------------------------------------------
+class TestRedactValueTypes:
+ """Sensitive keys redacted regardless of value type."""
+
+ def test_integer_value_redacted(self):
+ """Integer value for sensitive key is replaced with redaction text."""
+ data = {"api_key": 12345}
+ result = DataSanitizer.redact(data)
+ assert result["api_key"] == "[REDACTED]"
+
+ def test_none_value_redacted(self):
+ """None value for sensitive key is replaced with redaction text."""
+ data = {"password": None}
+ result = DataSanitizer.redact(data)
+ assert result["password"] == "[REDACTED]"
+
+ def test_boolean_value_redacted(self):
+ """Boolean value for sensitive key is replaced with redaction text."""
+ data = {"secret": True}
+ result = DataSanitizer.redact(data)
+ assert result["secret"] == "[REDACTED]"
+
+ def test_list_value_redacted(self):
+ """List value for sensitive key is replaced with redaction text."""
+ data = {"api_key": ["k1", "k2"]}
+ result = DataSanitizer.redact(data)
+ assert result["api_key"] == "[REDACTED]"
+
+ def test_dict_value_redacted(self):
+ """Dict value for sensitive key is replaced with redaction text."""
+ data = {"password": {"hash": "abc", "salt": "xyz"}}
+ result = DataSanitizer.redact(data)
+ assert result["password"] == "[REDACTED]"
+
+
+# ---------------------------------------------------------------------------
+# sanitize_data / redact_data convenience functions -- extended
+# ---------------------------------------------------------------------------
+class TestConvenienceFunctionsExtended:
+ """Extended tests for sanitize_data and redact_data convenience functions."""
+
+ def test_sanitize_data_delegates_correctly(self):
+ """sanitize_data produces identical results to DataSanitizer.sanitize."""
+ data = {
+ "api_key": "sk-123",
+ "config": {"password": "pwd", "theme": "dark"},
+ "items": [{"secret": "s1", "x": 1}],
+ }
+ assert sanitize_data(data) == DataSanitizer.sanitize(data)
+
+ def test_redact_data_delegates_correctly(self):
+ """redact_data produces identical results to DataSanitizer.redact."""
+ data = {
+ "api_key": "sk-123",
+ "config": {"password": "pwd", "theme": "dark"},
+ "items": [{"secret": "s1", "x": 1}],
+ }
+ assert redact_data(data) == DataSanitizer.redact(data)
+
+ def test_sanitize_data_with_nested_custom_keys(self):
+ """sanitize_data with custom keys works on nested structures."""
+ data = {"outer": {"my_secret": "gone", "keep": "this"}}
+ result = sanitize_data(data, sensitive_keys={"my_secret"})
+ assert "my_secret" not in result["outer"]
+ assert result["outer"]["keep"] == "this"
+
+ def test_redact_data_with_custom_keys_and_text(self):
+ """redact_data with both custom keys and custom text."""
+ data = {"my_field": "sensitive", "ok": "fine"}
+ result = redact_data(
+ data, sensitive_keys={"my_field"}, redaction_text="<SCRUBBED>"
+ )
+ assert result["my_field"] == "<SCRUBBED>"
+ assert result["ok"] == "fine"
+
+ def test_sanitize_data_primitives(self):
+ """sanitize_data passes primitives through unchanged."""
+ assert sanitize_data("hello") == "hello"
+ assert sanitize_data(42) == 42
+ assert sanitize_data(None) is None
+ assert sanitize_data(True) is True
+
+ def test_redact_data_primitives(self):
+ """redact_data passes primitives through unchanged."""
+ assert redact_data("hello") == "hello"
+ assert redact_data(42) == 42
+ assert redact_data(None) is None
+ assert redact_data(False) is False
+
+ def test_sanitize_data_empty_containers(self):
+ """sanitize_data handles empty containers."""
+ assert sanitize_data({}) == {}
+ assert sanitize_data([]) == []
+
+ def test_redact_data_empty_containers(self):
+ """redact_data handles empty containers."""
+ assert redact_data({}) == {}
+ assert redact_data([]) == []
+
+
+# ---------------------------------------------------------------------------
+# filter_research_metadata -- extended security-focused tests
+# ---------------------------------------------------------------------------
+class TestFilterResearchMetadataExtended:
+ """Extended tests for filter_research_metadata with security focus."""
+
+ def test_settings_snapshot_with_api_keys_never_leaks(self):
+ """settings_snapshot containing API keys is never in output."""
+ meta = {
+ "is_news_search": True,
+ "settings_snapshot": {
+ "llm_api_key": "sk-secret-key-123",
+ "search_api_key": "cx-another-key",
+ "password": "admin123",
+ "nested": {"private_key": "-----BEGIN-----"},
+ },
+ }
+ result = filter_research_metadata(meta)
+ result_str = json.dumps(result)
+ assert "settings_snapshot" not in result
+ assert "sk-secret-key-123" not in result_str
+ assert "cx-another-key" not in result_str
+ assert "admin123" not in result_str
+ assert "BEGIN" not in result_str
+
+ def test_api_key_at_top_level_never_leaks(self):
+ """api_key at top level of metadata is not passed through."""
+ meta = {"is_news_search": False, "api_key": "sk-top-level-key"}
+ result = filter_research_metadata(meta)
+ assert "api_key" not in result
+ assert "sk-top-level-key" not in json.dumps(result)
+
+ def test_password_at_top_level_never_leaks(self):
+ """password at top level of metadata is not passed through."""
+ meta = {"is_news_search": True, "password": "supersecret"}
+ result = filter_research_metadata(meta)
+ assert "password" not in result
+ assert "supersecret" not in json.dumps(result)
+
+ def test_only_is_news_search_in_output(self):
+ """Only is_news_search key appears in output regardless of input."""
+ meta = {
+ "is_news_search": True,
+ "phase": "complete",
+ "duration": 42.5,
+ "error_type": None,
+ "mode": "deep",
+ "processed_query": "test query",
+ }
+ result = filter_research_metadata(meta)
+ assert set(result.keys()) == {"is_news_search"}
+ assert result["is_news_search"] is True
+
+ def test_dict_without_is_news_search_returns_false(self):
+ """Dict missing is_news_search key returns False default."""
+ meta = {"phase": "complete", "duration": 10.0}
+ result = filter_research_metadata(meta)
+ assert result == {"is_news_search": False}
+
+ def test_is_news_search_truthy_values_coerced_to_bool(self):
+ """Truthy non-bool values for is_news_search are coerced to bool."""
+ assert filter_research_metadata({"is_news_search": 1}) == {
+ "is_news_search": True
+ }
+ assert filter_research_metadata({"is_news_search": "yes"}) == {
+ "is_news_search": True
+ }
+
+ def test_is_news_search_falsy_values_coerced_to_bool(self):
+ """Falsy non-bool values for is_news_search are coerced to bool."""
+ assert filter_research_metadata({"is_news_search": 0}) == {
+ "is_news_search": False
+ }
+ assert filter_research_metadata({"is_news_search": ""}) == {
+ "is_news_search": False
+ }
+
+ def test_json_string_with_settings_snapshot_never_leaks(self):
+ """JSON string containing settings_snapshot does not leak it."""
+ meta_str = json.dumps(
+ {
+ "is_news_search": True,
+ "settings_snapshot": {"api_key": "sk-from-json-string"},
+ }
+ )
+ result = filter_research_metadata(meta_str)
+ assert "settings_snapshot" not in result
+ assert "sk-from-json-string" not in json.dumps(result)
+
+ def test_json_string_with_api_key_never_leaks(self):
+ """JSON string containing api_key at top level does not leak it."""
+ meta_str = json.dumps(
+ {"is_news_search": False, "api_key": "sk-json-key"}
+ )
+ result = filter_research_metadata(meta_str)
+ assert "api_key" not in result
+ assert "sk-json-key" not in json.dumps(result)
+
+ def test_none_input(self):
+ """None input returns safe default."""
+ result = filter_research_metadata(None)
+ assert result == {"is_news_search": False}
+
+ def test_empty_string_input(self):
+ """Empty string input returns safe default."""
+ result = filter_research_metadata("")
+ assert result == {"is_news_search": False}
+
+ def test_non_dict_int_input(self):
+ """Integer input returns safe default."""
+ result = filter_research_metadata(42)
+ assert result == {"is_news_search": False}
+
+ def test_non_dict_list_input(self):
+ """List input returns safe default."""
+ result = filter_research_metadata([1, 2, 3])
+ assert result == {"is_news_search": False}
+
+ def test_non_dict_bool_input(self):
+ """Boolean input returns safe default."""
+ result = filter_research_metadata(True)
+ assert result == {"is_news_search": False}
+
+ def test_invalid_json_string(self):
+ """Invalid JSON string returns safe default."""
+ result = filter_research_metadata("{not valid json")
+ assert result == {"is_news_search": False}
+
+ def test_json_array_string(self):
+ """JSON array string returns safe default."""
+ result = filter_research_metadata("[1, 2, 3]")
+ assert result == {"is_news_search": False}
+
+ def test_json_string_non_dict(self):
+ """JSON string containing a number returns safe default."""
+ result = filter_research_metadata("42")
+ assert result == {"is_news_search": False}
+
+ def test_json_string_null(self):
+ """JSON string 'null' returns safe default."""
+ result = filter_research_metadata("null")
+ assert result == {"is_news_search": False}
+
+ def test_empty_dict_input(self):
+ """Empty dict returns safe default for is_news_search."""
+ result = filter_research_metadata({})
+ assert result == {"is_news_search": False}
+
+ def test_large_metadata_payload_only_extracts_is_news_search(self):
+ """Large realistic metadata payload only returns is_news_search."""
+ meta = {
+ "is_news_search": True,
+ "phase": "complete",
+ "error_type": None,
+ "processed_query": "what is quantum computing?",
+ "mode": "deep",
+ "duration": 123.45,
+ "search_results_count": 50,
+ "sources_used": ["google", "bing", "arxiv"],
+ "settings_snapshot": {
+ "llm_model": "gpt-4",
+ "api_key": "sk-prod-key-12345",
+ "temperature": 0.7,
+ "max_tokens": 4096,
+ "search_config": {
+ "google_api_key": "AIza-google-key",
+ "bing_api_key": "bing-secret-key",
+ },
+ },
+ }
+ result = filter_research_metadata(meta)
+ assert result == {"is_news_search": True}
+ result_str = json.dumps(result)
+ assert "sk-prod-key-12345" not in result_str
+ assert "AIza-google-key" not in result_str
+ assert "bing-secret-key" not in result_str
+ assert "settings_snapshot" not in result_str
+
+
+# ---------------------------------------------------------------------------
+# strip_settings_snapshot -- extended tests
+# ---------------------------------------------------------------------------
+class TestStripSettingsSnapshotExtended:
+ """Extended tests for strip_settings_snapshot."""
+
+ def test_removes_settings_snapshot_preserves_all_other_keys(self):
+ """All non-settings_snapshot keys are preserved."""
+ meta = {
+ "phase": "complete",
+ "error_type": None,
+ "processed_query": "test",
+ "mode": "deep",
+ "duration": 42.5,
+ "is_news_search": True,
+ "settings_snapshot": {"api_key": "sk-secret"},
+ }
+ result = strip_settings_snapshot(meta)
+ assert "settings_snapshot" not in result
+ assert result["phase"] == "complete"
+ assert result["error_type"] is None
+ assert result["processed_query"] == "test"
+ assert result["mode"] == "deep"
+ assert result["duration"] == 42.5
+ assert result["is_news_search"] is True
+
+ def test_settings_snapshot_api_keys_never_in_output(self):
+ """API keys within settings_snapshot never appear in output."""
+ meta = {
+ "phase": "done",
+ "settings_snapshot": {
+ "llm_api_key": "sk-very-secret-key",
+ "search_api_key": "another-secret",
+ "password": "admin",
+ "config": {"private_key": "pem-data"},
+ },
+ }
+ result = strip_settings_snapshot(meta)
+ result_str = json.dumps(result)
+ assert "sk-very-secret-key" not in result_str
+ assert "another-secret" not in result_str
+ assert "admin" not in result_str
+ assert "pem-data" not in result_str
+
+ def test_no_settings_snapshot_returns_full_copy(self):
+ """Dict without settings_snapshot returns copy with all keys."""
+ meta = {"phase": "error", "error_type": "timeout", "duration": 30.0}
+ result = strip_settings_snapshot(meta)
+ assert result == meta
+
+ def test_does_not_mutate_original_dict(self):
+ """Original dict is not mutated."""
+ original = {
+ "phase": "complete",
+ "settings_snapshot": {"api_key": "sk-key"},
+ }
+ strip_settings_snapshot(original)
+ assert "settings_snapshot" in original
+ assert original["settings_snapshot"]["api_key"] == "sk-key"
+
+ def test_only_exact_settings_snapshot_key_removed(self):
+ """Only 'settings_snapshot' key removed, not similar names."""
+ meta = {
+ "settings_version": 2,
+ "settings_backup": {"x": 1},
+ "snapshot": {"y": 2},
+ "settings_snapshot": {"api_key": "secret"},
+ }
+ result = strip_settings_snapshot(meta)
+ assert "settings_version" in result
+ assert "settings_backup" in result
+ assert "snapshot" in result
+ assert "settings_snapshot" not in result
+
+ def test_none_input(self):
+ """None input returns empty dict."""
+ assert strip_settings_snapshot(None) == {}
+
+ def test_empty_dict_input(self):
+ """Empty dict input returns empty dict."""
+ assert strip_settings_snapshot({}) == {}
+
+ def test_empty_string_input(self):
+ """Empty string input returns empty dict."""
+ assert strip_settings_snapshot("") == {}
+
+ def test_non_dict_int_input(self):
+ """Integer input returns empty dict."""
+ assert strip_settings_snapshot(42) == {}
+
+ def test_non_dict_list_input(self):
+ """List input returns empty dict."""
+ assert strip_settings_snapshot([1, 2, 3]) == {}
+
+ def test_non_dict_bool_input(self):
+ """Boolean input returns empty dict."""
+ assert strip_settings_snapshot(True) == {}
+
+ def test_invalid_json_string(self):
+ """Invalid JSON string returns empty dict."""
+ assert strip_settings_snapshot("not valid json{") == {}
+
+ def test_json_string_with_settings_snapshot(self):
+ """JSON string with settings_snapshot strips it correctly."""
+ meta_str = json.dumps(
+ {
+ "phase": "complete",
+ "duration": 10.5,
+ "settings_snapshot": {"api_key": "sk-from-json"},
+ }
+ )
+ result = strip_settings_snapshot(meta_str)
+ assert result == {"phase": "complete", "duration": 10.5}
+ assert "sk-from-json" not in json.dumps(result)
+
+ def test_json_string_without_settings_snapshot(self):
+ """JSON string without settings_snapshot returns all keys."""
+ meta_str = json.dumps({"phase": "error", "error_type": "network"})
+ result = strip_settings_snapshot(meta_str)
+ assert result == {"phase": "error", "error_type": "network"}
+
+ def test_json_array_string(self):
+ """JSON array string returns empty dict."""
+ assert strip_settings_snapshot("[1, 2, 3]") == {}
+
+ def test_json_null_string(self):
+ """JSON null string returns empty dict."""
+ assert strip_settings_snapshot("null") == {}
+
+ def test_settings_snapshot_with_empty_dict_value(self):
+ """settings_snapshot with empty dict is still removed."""
+ meta = {"phase": "done", "settings_snapshot": {}}
+ result = strip_settings_snapshot(meta)
+ assert result == {"phase": "done"}
+
+ def test_settings_snapshot_with_none_value(self):
+ """settings_snapshot with None value is still removed."""
+ meta = {"phase": "done", "settings_snapshot": None}
+ result = strip_settings_snapshot(meta)
+ assert result == {"phase": "done"}
+
+
+# ---------------------------------------------------------------------------
+# Security attack vectors -- ensuring no credential leakage paths
+# ---------------------------------------------------------------------------
+class TestSecurityAttackVectors:
+ """Tests simulating attack vectors for credential leakage."""
+
+ def test_sanitize_dict_only_safe_keys_survive(self):
+ """After sanitize, only non-sensitive keys remain."""
+ data = {
+ "username": "alice",
+ "email": "[email protected]",
+ "api_key": "sk-123",
+ "password": "pass",
+ "secret": "sec",
+ "access_token": "at",
+ "refresh_token": "rt",
+ "private_key": "pk",
+ "auth_token": "aut",
+ "session_token": "st",
+ "csrf_token": "csrf",
+ "apikey": "ak",
+ }
+ result = DataSanitizer.sanitize(data)
+ assert set(result.keys()) == {"username", "email"}
+
+ def test_redact_dict_all_secrets_redacted(self):
+ """After redact, all sensitive values are '[REDACTED]'."""
+ data = {
+ "username": "alice",
+ "api_key": "sk-123",
+ "password": "hunter2-secret",
+ "secret": "very-secret-value",
+ }
+ result = DataSanitizer.redact(data)
+ assert result["username"] == "alice"
+ assert result["api_key"] == "[REDACTED]"
+ assert result["password"] == "[REDACTED]"
+ assert result["secret"] == "[REDACTED]"
+ # Verify no original secret values in serialized output
+ result_str = json.dumps(result)
+ assert "sk-123" not in result_str
+ assert "hunter2-secret" not in result_str
+ assert "very-secret-value" not in result_str
+
+ def test_sanitize_prevents_secret_in_nested_list_of_configs(self):
+ """Secrets in list of config objects are fully removed."""
+ configs = [
+ {
+ "provider": "openai",
+ "api_key": "sk-openai-key",
+ "model": "gpt-4",
+ },
+ {
+ "provider": "anthropic",
+ "api_key": "sk-ant-key",
+ "model": "claude",
+ },
+ {"provider": "google", "apikey": "AIza-key", "model": "gemini"},
+ ]
+ result = DataSanitizer.sanitize(configs)
+ for item in result:
+ assert "api_key" not in item
+ assert "apikey" not in item
+ assert "provider" in item
+ assert "model" in item
+ result_str = json.dumps(result)
+ assert "sk-openai-key" not in result_str
+ assert "sk-ant-key" not in result_str
+ assert "AIza-key" not in result_str
+
+ def test_filter_metadata_cannot_extract_arbitrary_keys(self):
+ """filter_research_metadata only returns is_news_search, nothing else."""
+ meta = {
+ "is_news_search": True,
+ "secret": "should-not-appear",
+ "api_key": "should-not-appear",
+ "password": "should-not-appear",
+ "some_other_field": "should-not-appear",
+ }
+ result = filter_research_metadata(meta)
+ assert set(result.keys()) == {"is_news_search"}
+ result_str = json.dumps(result)
+ assert "should-not-appear" not in result_str
+
+ def test_strip_snapshot_then_filter_metadata_double_protection(self):
+ """Applying strip_settings_snapshot then filter_research_metadata
+ provides defense in depth against credential leakage."""
+ meta = {
+ "is_news_search": True,
+ "phase": "complete",
+ "settings_snapshot": {
+ "api_key": "sk-double-layered",
+ "password": "admin-pwd",
+ },
+ }
+ stripped = strip_settings_snapshot(meta)
+ filtered = filter_research_metadata(stripped)
+ combined_str = json.dumps(filtered)
+ assert "sk-double-layered" not in combined_str
+ assert "admin-pwd" not in combined_str
+ assert filtered == {"is_news_search": True}
+
+ def test_sanitize_then_redact_no_leakage(self):
+ """Applying sanitize then redact results in no credential values."""
+ data = {
+ "api_key": "sk-key",
+ "password": "pwd",
+ "name": "test",
+ "config": {"secret": "s1", "url": "http://safe.com"},
+ }
+ sanitized = DataSanitizer.sanitize(data)
+ redacted = DataSanitizer.redact(sanitized)
+ result_str = json.dumps(redacted)
+ assert "sk-key" not in result_str
+ assert "pwd" not in result_str
+ assert "s1" not in result_str
+
+ def test_sensitive_key_with_complex_nested_value_fully_removed(self):
+ """Sensitive key whose value is a complex nested structure is fully removed."""
+ data = {
+ "api_key": {
+ "primary": "sk-primary",
+ "secondary": "sk-secondary",
+ "nested": {"deep": "sk-deep"},
+ },
+ "name": "service",
+ }
+ result = DataSanitizer.sanitize(data)
+ assert "api_key" not in result
+ result_str = json.dumps(result)
+ assert "sk-primary" not in result_str
+ assert "sk-secondary" not in result_str
+ assert "sk-deep" not in result_str
+
+ def test_sensitive_key_with_complex_nested_value_fully_redacted(self):
+ """Sensitive key whose value is a complex nested structure is fully redacted."""
+ data = {
+ "api_key": {
+ "primary": "sk-primary",
+ "secondary": "sk-secondary",
+ },
+ "name": "service",
+ }
+ result = DataSanitizer.redact(data)
+ assert result["api_key"] == "[REDACTED]"
+ result_str = json.dumps(result)
+ assert "sk-primary" not in result_str
+ assert "sk-secondary" not in result_str
+
+
+# ---------------------------------------------------------------------------
+# Edge cases -- unusual but valid inputs
+# ---------------------------------------------------------------------------
+class TestEdgeCasesExtended:
+ """Extended edge case tests."""
+
+ def test_sanitize_dict_with_numeric_keys(self):
+ """Dict with integer keys (not matching any sensitive key) passes through."""
+ # Note: JSON doesn't support int keys, but Python dicts do
+ data = {1: "a", 2: "b"}
+ # int.lower() would fail, but these keys should not match sensitive keys
+ # This tests that the code handles non-string keys gracefully
+ # The implementation uses k.lower() which requires string keys.
+ # With int keys this would raise AttributeError, which is expected
+ # behavior -- we test that string keys work properly instead.
+ data = {"1": "a", "2": "b", "api_key": "secret"}
+ result = DataSanitizer.sanitize(data)
+ assert result == {"1": "a", "2": "b"}
+
+ def test_sanitize_unicode_keys_preserved(self):
+ """Non-ASCII unicode keys that are not sensitive are preserved."""
+ data = {"nombre": "test", "api_key": "secret", "clé": "value"}
+ result = DataSanitizer.sanitize(data)
+ assert "nombre" in result
+ assert "clé" in result
+ assert "api_key" not in result
+
+ def test_sanitize_empty_string_value(self):
+ """Sensitive key with empty string value is still removed."""
+ data = {"api_key": "", "name": "test"}
+ result = DataSanitizer.sanitize(data)
+ assert "api_key" not in result
+
+ def test_redact_empty_string_value(self):
+ """Sensitive key with empty string value is still redacted."""
+ data = {"api_key": "", "name": "test"}
+ result = DataSanitizer.redact(data)
+ assert result["api_key"] == "[REDACTED]"
+
+ def test_sanitize_preserves_zero_values(self):
+ """Non-sensitive keys with falsy values (0, False, '') are preserved."""
+ data = {
+ "count": 0,
+ "enabled": False,
+ "description": "",
+ "items": [],
+ "config": {},
+ }
+ result = DataSanitizer.sanitize(data)
+ assert result["count"] == 0
+ assert result["enabled"] is False
+ assert result["description"] == ""
+ assert result["items"] == []
+ assert result["config"] == {}
+
+ def test_redact_preserves_zero_values(self):
+ """Non-sensitive keys with falsy values are preserved by redact."""
+ data = {"count": 0, "enabled": False}
+ result = DataSanitizer.redact(data)
+ assert result["count"] == 0
+ assert result["enabled"] is False
+
+ def test_sanitize_single_key_dict_sensitive(self):
+ """Dict with only a sensitive key results in empty dict."""
+ data = {"password": "only-key"}
+ result = DataSanitizer.sanitize(data)
+ assert result == {}
+
+ def test_sanitize_tuple_passthrough(self):
+ """Tuples are returned unchanged (treated as primitives)."""
+ data = (1, 2, 3)
+ result = DataSanitizer.sanitize(data)
+ assert result == (1, 2, 3)
+
+ def test_redact_tuple_passthrough(self):
+ """Tuples are returned unchanged by redact."""
+ data = (1, 2, 3)
+ result = DataSanitizer.redact(data)
+ assert result == (1, 2, 3)
+
+ def test_sanitize_set_passthrough(self):
+ """Sets are returned unchanged (treated as primitives)."""
+ data = {1, 2, 3}
+ result = DataSanitizer.sanitize(data)
+ assert result == {1, 2, 3}
+
+ def test_sanitize_float_passthrough(self):
+ """Float values pass through unchanged."""
+ assert DataSanitizer.sanitize(3.14159) == 3.14159
+
+ def test_redact_float_passthrough(self):
+ """Float values pass through unchanged from redact."""
+ assert DataSanitizer.redact(3.14159) == 3.14159
+
+ def test_filter_metadata_with_false_value_types(self):
+ """filter_research_metadata with 0 as input returns default."""
+ assert filter_research_metadata(0) == {"is_news_search": False}
+
+ def test_filter_metadata_with_empty_list(self):
+ """filter_research_metadata with empty list returns default."""
+ assert filter_research_metadata([]) == {"is_news_search": False}
+
+ def test_strip_snapshot_with_zero_input(self):
+ """strip_settings_snapshot with 0 input returns empty dict."""
+ assert strip_settings_snapshot(0) == {}
+
+ def test_strip_snapshot_with_false_input(self):
+ """strip_settings_snapshot with False input returns empty dict."""
+ assert strip_settings_snapshot(False) == {}
diff --git a/tests/security/test_module_whitelist_extended.py b/tests/security/test_module_whitelist_extended.py
new file mode 100644
index 0000000000..4f73eb8613
--- /dev/null
+++ b/tests/security/test_module_whitelist_extended.py
@@ -0,0 +1,494 @@
+"""
+Extended tests for the module whitelist security system.
+
+Tests the whitelist constants, validation functions, error hierarchy,
+and security-critical edge cases in local_deep_research.security.module_whitelist.
+"""
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from local_deep_research.security.module_whitelist import (
+ ALLOWED_MODULE_PATHS,
+ ALLOWED_CLASS_NAMES,
+ ALLOWED_MODULES,
+ SecurityError,
+ ModuleNotAllowedError,
+ validate_module_import,
+ get_safe_module_class,
+)
+
+
+# ---------------------------------------------------------------------------
+# ALLOWED_MODULE_PATHS
+# ---------------------------------------------------------------------------
+
+
+class TestAllowedModulePathsExtended:
+ """Extended tests for the ALLOWED_MODULE_PATHS constant."""
+
+ def test_is_frozenset(self):
+ """ALLOWED_MODULE_PATHS must be a frozenset (immutable)."""
+ assert isinstance(ALLOWED_MODULE_PATHS, frozenset)
+
+ def test_contains_brave_engine(self):
+ """Whitelist contains the Brave search engine module."""
+ assert ".engines.search_engine_brave" in ALLOWED_MODULE_PATHS
+
+ def test_contains_arxiv_engine(self):
+ """Whitelist contains the ArXiv search engine module."""
+ assert ".engines.search_engine_arxiv" in ALLOWED_MODULE_PATHS
+
+ def test_all_entries_start_with_dot(self):
+ """Every entry must start with '.' enforcing relative-import-only policy."""
+ for path in ALLOWED_MODULE_PATHS:
+ assert path.startswith("."), (
+ f"Path {path!r} violates the relative-import-only policy"
+ )
+
+ def test_does_not_contain_os(self):
+ """Whitelist must never contain the 'os' module."""
+ assert "os" not in ALLOWED_MODULE_PATHS
+
+ def test_does_not_contain_subprocess(self):
+ """Whitelist must never contain the 'subprocess' module."""
+ assert "subprocess" not in ALLOWED_MODULE_PATHS
+
+ def test_does_not_contain_sys(self):
+ """Whitelist must never contain the 'sys' module."""
+ assert "sys" not in ALLOWED_MODULE_PATHS
+
+ def test_no_dangerous_stdlib_paths(self):
+ """Whitelist must not contain any well-known dangerous stdlib modules."""
+ dangerous = {
+ "os",
+ "sys",
+ "subprocess",
+ "shutil",
+ "ctypes",
+ "socket",
+ "pickle",
+ "shelve",
+ "code",
+ "codeop",
+ "compileall",
+ "importlib",
+ "builtins",
+ "io",
+ "signal",
+ }
+ for module in dangerous:
+ assert module not in ALLOWED_MODULE_PATHS, (
+ f"Dangerous module {module!r} must not appear in whitelist"
+ )
+
+ def test_immutability(self):
+ """frozenset must refuse mutation attempts."""
+ with pytest.raises(AttributeError):
+ ALLOWED_MODULE_PATHS.add("os") # type: ignore[attr-defined]
+
+ with pytest.raises(AttributeError):
+ ALLOWED_MODULE_PATHS.discard( # type: ignore[attr-defined]
+ ".engines.search_engine_brave"
+ )
+
+
+# ---------------------------------------------------------------------------
+# ALLOWED_CLASS_NAMES
+# ---------------------------------------------------------------------------
+
+
+class TestAllowedClassNamesExtended:
+ """Extended tests for the ALLOWED_CLASS_NAMES constant."""
+
+ def test_is_frozenset(self):
+ """ALLOWED_CLASS_NAMES must be a frozenset (immutable)."""
+ assert isinstance(ALLOWED_CLASS_NAMES, frozenset)
+
+ def test_contains_brave_search_engine(self):
+ """Whitelist contains the BraveSearchEngine class."""
+ assert "BraveSearchEngine" in ALLOWED_CLASS_NAMES
+
+ def test_contains_arxiv_search_engine(self):
+ """Whitelist contains the ArXivSearchEngine class."""
+ assert "ArXivSearchEngine" in ALLOWED_CLASS_NAMES
+
+ def test_does_not_contain_system(self):
+ """Whitelist must not contain 'system' (os.system target)."""
+ assert "system" not in ALLOWED_CLASS_NAMES
+
+ def test_does_not_contain_exec(self):
+ """Whitelist must not contain 'exec' (code execution target)."""
+ assert "exec" not in ALLOWED_CLASS_NAMES
+
+ def test_does_not_contain_eval(self):
+ """Whitelist must not contain 'eval' (code execution target)."""
+ assert "eval" not in ALLOWED_CLASS_NAMES
+
+ def test_no_dangerous_class_names(self):
+ """Whitelist must not contain any well-known dangerous class/function names."""
+ dangerous = {
+ "system",
+ "exec",
+ "eval",
+ "Popen",
+ "call",
+ "run",
+ "loads",
+ "load",
+ "CDLL",
+ "interact",
+ "__import__",
+ "import_module",
+ "compile",
+ }
+ for name in dangerous:
+ assert name not in ALLOWED_CLASS_NAMES, (
+ f"Dangerous name {name!r} must not appear in class whitelist"
+ )
+
+ def test_immutability(self):
+ """frozenset must refuse mutation attempts."""
+ with pytest.raises(AttributeError):
+ ALLOWED_CLASS_NAMES.add("system") # type: ignore[attr-defined]
+
+
+# ---------------------------------------------------------------------------
+# ALLOWED_MODULES (legacy alias)
+# ---------------------------------------------------------------------------
+
+
+class TestAllowedModulesAlias:
+ """Tests for the ALLOWED_MODULES legacy alias."""
+
+ def test_is_same_object_as_allowed_module_paths(self):
+ """ALLOWED_MODULES must be the exact same object as ALLOWED_MODULE_PATHS."""
+ assert ALLOWED_MODULES is ALLOWED_MODULE_PATHS
+
+
+# ---------------------------------------------------------------------------
+# SecurityError and ModuleNotAllowedError
+# ---------------------------------------------------------------------------
+
+
+class TestSecurityErrorHierarchy:
+ """Tests for the SecurityError and ModuleNotAllowedError exception classes."""
+
+ def test_security_error_is_exception_subclass(self):
+ """SecurityError must be a subclass of Exception."""
+ assert issubclass(SecurityError, Exception)
+
+ def test_module_not_allowed_error_is_security_error(self):
+ """ModuleNotAllowedError must be the same class as SecurityError (legacy alias)."""
+ assert ModuleNotAllowedError is SecurityError
+
+ def test_security_error_is_catchable_as_exception(self):
+ """SecurityError instances must be catchable as plain Exception."""
+ with pytest.raises(Exception):
+ raise SecurityError("test")
+
+ def test_module_not_allowed_error_is_catchable_as_security_error(self):
+ """ModuleNotAllowedError instances must be catchable as SecurityError."""
+ with pytest.raises(SecurityError):
+ raise ModuleNotAllowedError("test")
+
+ def test_security_error_preserves_message(self):
+ """SecurityError must preserve its error message."""
+ err = SecurityError("blocked import attempt")
+ assert str(err) == "blocked import attempt"
+
+
+# ---------------------------------------------------------------------------
+# validate_module_import
+# ---------------------------------------------------------------------------
+
+
+class TestValidateModuleImportExtended:
+ """Extended tests for the validate_module_import function."""
+
+ # --- happy-path ---
+
+ def test_valid_module_and_valid_class_returns_true(self):
+ """Returns True when both module and class are whitelisted."""
+ assert (
+ validate_module_import(
+ ".engines.search_engine_brave", "BraveSearchEngine"
+ )
+ is True
+ )
+
+ # --- single-invalid dimension ---
+
+ def test_invalid_module_valid_class_returns_false(self):
+ """Returns False when only the module is not whitelisted."""
+ assert (
+ validate_module_import(
+ ".engines.nonexistent_engine", "BraveSearchEngine"
+ )
+ is False
+ )
+
+ def test_valid_module_invalid_class_returns_false(self):
+ """Returns False when only the class is not whitelisted."""
+ assert (
+ validate_module_import(".engines.search_engine_brave", "EvilClass")
+ is False
+ )
+
+ # --- both-invalid dimension ---
+
+ def test_both_invalid_returns_false(self):
+ """Returns False when neither module nor class is whitelisted."""
+ assert validate_module_import(".evil.module", "EvilClass") is False
+
+ # --- empty / None inputs ---
+
+ def test_empty_module_path_returns_false(self):
+ """Returns False for an empty string module_path."""
+ assert validate_module_import("", "BraveSearchEngine") is False
+
+ def test_empty_class_name_returns_false(self):
+ """Returns False for an empty string class_name."""
+ assert (
+ validate_module_import(".engines.search_engine_brave", "") is False
+ )
+
+ def test_none_module_path_returns_false(self):
+ """Returns False when module_path is None."""
+ assert validate_module_import(None, "BraveSearchEngine") is False
+
+ def test_none_class_name_returns_false(self):
+ """Returns False when class_name is None."""
+ assert (
+ validate_module_import(".engines.search_engine_brave", None)
+ is False
+ )
+
+ def test_both_none_returns_false(self):
+ """Returns False when both arguments are None."""
+ assert validate_module_import(None, None) is False
+
+ # --- CRITICAL SECURITY: non-relative paths ---
+
+ def test_non_relative_os_returns_false(self):
+ """CRITICAL: bare 'os' module must be rejected as non-relative path."""
+ assert validate_module_import("os", "system") is False
+
+ def test_absolute_fully_qualified_path_returns_false(self):
+ """Absolute fully-qualified module path must be rejected."""
+ assert (
+ validate_module_import(
+ "local_deep_research.web_search_engines.engines.search_engine_brave",
+ "BraveSearchEngine",
+ )
+ is False
+ )
+
+ def test_double_dot_prefix_returns_false(self):
+ """Path starting with '..' must be rejected (not in whitelist)."""
+ assert validate_module_import("..os", "system") is False
+
+ def test_triple_dot_prefix_returns_false(self):
+ """Path starting with '...' must be rejected."""
+ assert validate_module_import("...os", "system") is False
+
+ def test_non_relative_subprocess_returns_false(self):
+ """Bare 'subprocess' module must be rejected."""
+ assert validate_module_import("subprocess", "Popen") is False
+
+ def test_non_relative_sys_returns_false(self):
+ """Bare 'sys' module must be rejected."""
+ assert validate_module_import("sys", "exit") is False
+
+ # --- path traversal attempts ---
+
+ def test_path_traversal_slash(self):
+ """Path traversal using forward slashes must be rejected."""
+ assert validate_module_import(".engines/../../../os", "system") is False
+
+ def test_path_traversal_backslash(self):
+ """Path traversal using backslashes must be rejected."""
+ assert (
+ validate_module_import(".engines\\..\\..\\subprocess", "Popen")
+ is False
+ )
+
+ # --- case sensitivity ---
+
+ def test_case_sensitive_module_path(self):
+ """Module paths are case-sensitive -- upper-cased variant must be rejected."""
+ assert (
+ validate_module_import(
+ ".ENGINES.SEARCH_ENGINE_BRAVE", "BraveSearchEngine"
+ )
+ is False
+ )
+
+ def test_case_sensitive_class_name(self):
+ """Class names are case-sensitive -- lower-cased variant must be rejected."""
+ assert (
+ validate_module_import(
+ ".engines.search_engine_brave", "bravesearchengine"
+ )
+ is False
+ )
+
+ # --- whitespace / special chars ---
+
+ def test_whitespace_module_path_returns_false(self):
+ """A whitespace-only module_path must be rejected (not starting with '.')."""
+ assert validate_module_import(" ", "BraveSearchEngine") is False
+
+ def test_module_path_with_trailing_space_returns_false(self):
+ """Module path with trailing space must not match whitelist entry."""
+ assert (
+ validate_module_import(
+ ".engines.search_engine_brave ", "BraveSearchEngine"
+ )
+ is False
+ )
+
+ def test_class_name_with_trailing_space_returns_false(self):
+ """Class name with trailing space must not match whitelist entry."""
+ assert (
+ validate_module_import(
+ ".engines.search_engine_brave", "BraveSearchEngine "
+ )
+ is False
+ )
+
+ # --- injection-style inputs ---
+
+ def test_semicolon_injection_in_module_path(self):
+ """Semicolon-based injection attempt in module path must be rejected."""
+ assert validate_module_import(".engines; import os;", "system") is False
+
+ def test_newline_injection_in_module_path(self):
+ """Newline injection attempt in module path must be rejected."""
+ assert validate_module_import(".engines\nimport os", "system") is False
+
+
+# ---------------------------------------------------------------------------
+# get_safe_module_class
+# ---------------------------------------------------------------------------
+
+
+class TestGetSafeModuleClassExtended:
+ """Extended tests for the get_safe_module_class function."""
+
+ def test_raises_security_error_for_non_whitelisted_module(self):
+ """Raises SecurityError when the module path is not whitelisted."""
+ with pytest.raises(SecurityError):
+ get_safe_module_class(".evil.module", "BraveSearchEngine")
+
+ def test_raises_security_error_for_non_whitelisted_class(self):
+ """Raises SecurityError when the class name is not whitelisted."""
+ with pytest.raises(SecurityError):
+ get_safe_module_class(
+ ".engines.search_engine_brave", "MaliciousClass"
+ )
+
+ def test_raises_security_error_for_absolute_os(self):
+ """Raises SecurityError for absolute path 'os'."""
+ with pytest.raises(SecurityError):
+ get_safe_module_class("os", "system")
+
+ def test_raises_security_error_for_subprocess(self):
+ """Raises SecurityError for absolute path 'subprocess'."""
+ with pytest.raises(SecurityError):
+ get_safe_module_class("subprocess", "Popen")
+
+ def test_error_message_contains_module_path(self):
+ """The SecurityError message must include the rejected module path."""
+ with pytest.raises(SecurityError, match=r"\.evil\.module"):
+ get_safe_module_class(".evil.module", "EvilClass")
+
+ def test_error_message_contains_class_name(self):
+ """The SecurityError message must include the rejected class name."""
+ with pytest.raises(SecurityError, match="EvilClass"):
+ get_safe_module_class(".evil.module", "EvilClass")
+
+ def test_error_message_mentions_whitelist(self):
+ """The SecurityError message must mention 'whitelist' for clarity."""
+ with pytest.raises(SecurityError, match="whitelist"):
+ get_safe_module_class("os", "system")
+
+ # --- default package for relative imports ---
+
+ def test_default_package_used_for_relative_import(self):
+ """When no package kwarg is given, the default package is used for relative imports."""
+ with patch(
+ "local_deep_research.security.module_whitelist.validate_module_import",
+ return_value=True,
+ ):
+ with patch(
+ "local_deep_research.security.module_whitelist.importlib.import_module",
+ ) as mock_import:
+ mock_module = MagicMock()
+ mock_module.FakeEngine = type("FakeEngine", (), {})
+ mock_import.return_value = mock_module
+
+ get_safe_module_class(".engines.fake", "FakeEngine")
+
+ mock_import.assert_called_once_with(
+ ".engines.fake",
+ package="local_deep_research.web_search_engines",
+ )
+
+ # --- custom package parameter ---
+
+ def test_custom_package_parameter_is_used(self):
+ """When a custom package kwarg is given, it overrides the default."""
+ with patch(
+ "local_deep_research.security.module_whitelist.validate_module_import",
+ return_value=True,
+ ):
+ with patch(
+ "local_deep_research.security.module_whitelist.importlib.import_module",
+ ) as mock_import:
+ mock_module = MagicMock()
+ mock_module.FakeEngine = type("FakeEngine", (), {})
+ mock_import.return_value = mock_module
+
+ get_safe_module_class(
+ ".engines.fake",
+ "FakeEngine",
+ package="my.custom.package",
+ )
+
+ mock_import.assert_called_once_with(
+ ".engines.fake",
+ package="my.custom.package",
+ )
+
+ # --- downstream exception propagation ---
+
+ def test_module_not_found_error_propagates(self):
+ """ModuleNotFoundError propagates when a whitelisted module cannot be found."""
+ with patch(
+ "local_deep_research.security.module_whitelist.validate_module_import",
+ return_value=True,
+ ):
+ with patch(
+ "local_deep_research.security.module_whitelist.importlib.import_module",
+ side_effect=ModuleNotFoundError("No module named 'fake'"),
+ ):
+ with pytest.raises(ModuleNotFoundError):
+ get_safe_module_class(".engines.fake_module", "FakeEngine")
+
+ def test_attribute_error_propagates(self):
+ """AttributeError propagates when the class is missing from the module."""
+ with patch(
+ "local_deep_research.security.module_whitelist.validate_module_import",
+ return_value=True,
+ ):
+ mock_module = MagicMock(spec=[])
+ with patch(
+ "local_deep_research.security.module_whitelist.importlib.import_module",
+ return_value=mock_module,
+ ):
+ with pytest.raises(AttributeError):
+ get_safe_module_class(
+ ".engines.search_engine_brave",
+ "NonExistentClass",
+ )
diff --git a/tests/security/test_ssrf_validator_extended.py b/tests/security/test_ssrf_validator_extended.py
new file mode 100644
index 0000000000..296c3b87a9
--- /dev/null
+++ b/tests/security/test_ssrf_validator_extended.py
@@ -0,0 +1,622 @@
+"""
+Extended tests for the SSRF validator module.
+
+Provides comprehensive coverage of is_ip_blocked, get_safe_url, and module
+constants (AWS_METADATA_IP, ALLOWED_SCHEMES). The validate_url function is
+bypassed when PYTEST_CURRENT_TEST is set, so its SSRF blocking logic is
+exercised indirectly through is_ip_blocked; the get_safe_url tests cover
+the None/empty handling path and the pass-through behaviour in test mode.
+"""
+
+import pytest
+
+from local_deep_research.security.ssrf_validator import (
+ AWS_METADATA_IP,
+ ALLOWED_SCHEMES,
+ get_safe_url,
+ is_ip_blocked,
+ validate_url,
+)
+
+
+# ---------------------------------------------------------------------------
+# Constants
+# ---------------------------------------------------------------------------
+
+
+class TestAWSMetadataIPConstant:
+ """Verify the AWS_METADATA_IP constant value."""
+
+ def test_aws_metadata_ip_is_correct_string(self):
+ """AWS_METADATA_IP must be the well-known metadata endpoint."""
+ assert AWS_METADATA_IP == "169.254.169.254"
+
+ def test_aws_metadata_ip_type(self):
+ """AWS_METADATA_IP must be a plain string."""
+ assert isinstance(AWS_METADATA_IP, str)
+
+
+class TestAllowedSchemesConstant:
+ """Verify the ALLOWED_SCHEMES constant."""
+
+ def test_http_in_allowed_schemes(self):
+ """http must be an allowed scheme."""
+ assert "http" in ALLOWED_SCHEMES
+
+ def test_https_in_allowed_schemes(self):
+ """https must be an allowed scheme."""
+ assert "https" in ALLOWED_SCHEMES
+
+ def test_ftp_not_in_allowed_schemes(self):
+ """ftp must NOT be an allowed scheme."""
+ assert "ftp" not in ALLOWED_SCHEMES
+
+ def test_file_not_in_allowed_schemes(self):
+ """file must NOT be an allowed scheme."""
+ assert "file" not in ALLOWED_SCHEMES
+
+ def test_allowed_schemes_is_a_set(self):
+ """ALLOWED_SCHEMES should be a set for O(1) lookups."""
+ assert isinstance(ALLOWED_SCHEMES, set)
+
+ def test_allowed_schemes_contains_only_expected_values(self):
+ """ALLOWED_SCHEMES should contain exactly http and https."""
+ assert ALLOWED_SCHEMES == {"http", "https"}
+
+
+# ---------------------------------------------------------------------------
+# is_ip_blocked -- public / safe IPs
+# ---------------------------------------------------------------------------
+
+
+class TestIsIpBlockedPublicIPs:
+ """Public IPs must never be blocked regardless of flags."""
+
+ @pytest.mark.parametrize(
+ "ip",
+ [
+ "8.8.8.8",
+ "8.8.4.4",
+ "1.1.1.1",
+ "1.0.0.1",
+ "208.67.222.222",
+ "142.250.185.206",
+ "93.184.216.34",
+ "198.51.100.1",
+ "203.0.113.5",
+ ],
+ )
+ def test_public_ipv4_not_blocked(self, ip):
+ """Well-known public IPv4 addresses are not blocked."""
+ assert is_ip_blocked(ip) is False
+
+ @pytest.mark.parametrize(
+ "ip",
+ [
+ "8.8.8.8",
+ "1.1.1.1",
+ "93.184.216.34",
+ ],
+ )
+ def test_public_ipv4_not_blocked_with_allow_localhost(self, ip):
+ """Public IPs remain unblocked when allow_localhost=True."""
+ assert is_ip_blocked(ip, allow_localhost=True) is False
+
+ @pytest.mark.parametrize(
+ "ip",
+ [
+ "8.8.8.8",
+ "1.1.1.1",
+ ],
+ )
+ def test_public_ipv4_not_blocked_with_allow_private_ips(self, ip):
+ """Public IPs remain unblocked when allow_private_ips=True."""
+ assert is_ip_blocked(ip, allow_private_ips=True) is False
+
+ def test_public_ipv6_not_blocked(self):
+ """Public IPv6 addresses are not blocked."""
+ # Google public DNS IPv6
+ assert is_ip_blocked("2001:4860:4860::8888") is False
+
+ def test_public_ipv6_not_blocked_with_flags(self):
+ """Public IPv6 remains unblocked regardless of flags."""
+ assert (
+ is_ip_blocked("2001:4860:4860::8888", allow_localhost=True) is False
+ )
+ assert (
+ is_ip_blocked("2001:4860:4860::8888", allow_private_ips=True)
+ is False
+ )
+
+
+# ---------------------------------------------------------------------------
+# is_ip_blocked -- localhost / loopback
+# ---------------------------------------------------------------------------
+
+
+class TestIsIpBlockedLoopback:
+ """Loopback addresses blocked by default, allowed via flags."""
+
+ def test_127_0_0_1_blocked_by_default(self):
+ """Standard IPv4 loopback is blocked."""
+ assert is_ip_blocked("127.0.0.1") is True
+
+ def test_127_0_0_2_blocked_by_default(self):
+ """Alternate IPv4 loopback address in 127/8 is blocked."""
+ assert is_ip_blocked("127.0.0.2") is True
+
+ def test_127_255_255_255_blocked_by_default(self):
+ """End of IPv4 loopback range is blocked."""
+ assert is_ip_blocked("127.255.255.255") is True
+
+ def test_ipv6_loopback_blocked_by_default(self):
+ """IPv6 loopback ::1 is blocked."""
+ assert is_ip_blocked("::1") is True
+
+ def test_127_0_0_1_allowed_with_allow_localhost(self):
+ """allow_localhost=True unblocks 127.0.0.1."""
+ assert is_ip_blocked("127.0.0.1", allow_localhost=True) is False
+
+ def test_127_range_allowed_with_allow_localhost(self):
+ """allow_localhost=True unblocks the whole 127/8 range."""
+ assert is_ip_blocked("127.0.0.2", allow_localhost=True) is False
+ assert is_ip_blocked("127.255.255.255", allow_localhost=True) is False
+
+ def test_ipv6_loopback_allowed_with_allow_localhost(self):
+ """allow_localhost=True unblocks ::1."""
+ assert is_ip_blocked("::1", allow_localhost=True) is False
+
+ def test_127_0_0_1_allowed_with_allow_private_ips(self):
+ """allow_private_ips=True also unblocks loopback."""
+ assert is_ip_blocked("127.0.0.1", allow_private_ips=True) is False
+
+ def test_ipv6_loopback_allowed_with_allow_private_ips(self):
+ """allow_private_ips=True also unblocks IPv6 loopback."""
+ assert is_ip_blocked("::1", allow_private_ips=True) is False
+
+
+# ---------------------------------------------------------------------------
+# is_ip_blocked -- RFC1918 private ranges
+# ---------------------------------------------------------------------------
+
+
+class TestIsIpBlockedRFC1918:
+ """RFC1918 private addresses blocked by default, allowed with allow_private_ips."""
+
+ # -- 10.0.0.0/8 --
+
+ def test_10_0_0_1_blocked(self):
+ assert is_ip_blocked("10.0.0.1") is True
+
+ def test_10_255_255_255_blocked(self):
+ assert is_ip_blocked("10.255.255.255") is True
+
+ def test_10_x_allowed_with_allow_private_ips(self):
+ assert is_ip_blocked("10.0.0.1", allow_private_ips=True) is False
+ assert is_ip_blocked("10.255.255.255", allow_private_ips=True) is False
+
+ def test_10_x_still_blocked_with_allow_localhost(self):
+ """allow_localhost does NOT unblock RFC1918."""
+ assert is_ip_blocked("10.0.0.1", allow_localhost=True) is True
+
+ # -- 172.16.0.0/12 --
+
+ def test_172_16_0_1_blocked(self):
+ assert is_ip_blocked("172.16.0.1") is True
+
+ def test_172_31_255_255_blocked(self):
+ assert is_ip_blocked("172.31.255.255") is True
+
+ def test_172_15_255_255_not_blocked(self):
+ """172.15.x.x is outside 172.16.0.0/12 and therefore public."""
+ assert is_ip_blocked("172.15.255.255") is False
+
+ def test_172_32_0_0_not_blocked(self):
+ """172.32.x.x is outside 172.16.0.0/12 and therefore public."""
+ assert is_ip_blocked("172.32.0.0") is False
+
+ def test_172_16_x_allowed_with_allow_private_ips(self):
+ assert is_ip_blocked("172.16.0.1", allow_private_ips=True) is False
+ assert is_ip_blocked("172.31.255.255", allow_private_ips=True) is False
+
+ def test_172_16_x_still_blocked_with_allow_localhost(self):
+ assert is_ip_blocked("172.16.0.1", allow_localhost=True) is True
+
+ # -- 192.168.0.0/16 --
+
+ def test_192_168_1_1_blocked(self):
+ assert is_ip_blocked("192.168.1.1") is True
+
+ def test_192_168_0_1_blocked(self):
+ assert is_ip_blocked("192.168.0.1") is True
+
+ def test_192_168_255_255_blocked(self):
+ assert is_ip_blocked("192.168.255.255") is True
+
+ def test_192_168_x_allowed_with_allow_private_ips(self):
+ assert is_ip_blocked("192.168.1.1", allow_private_ips=True) is False
+ assert is_ip_blocked("192.168.255.255", allow_private_ips=True) is False
+
+ def test_192_168_x_still_blocked_with_allow_localhost(self):
+ assert is_ip_blocked("192.168.1.1", allow_localhost=True) is True
+
+
+# ---------------------------------------------------------------------------
+# is_ip_blocked -- AWS metadata endpoint (ALWAYS blocked)
+# ---------------------------------------------------------------------------
+
+
+class TestIsIpBlockedAWSMetadata:
+ """169.254.169.254 must ALWAYS be blocked -- the #1 SSRF target."""
+
+ def test_aws_metadata_blocked_default(self):
+ assert is_ip_blocked("169.254.169.254") is True
+
+ def test_aws_metadata_blocked_with_allow_localhost(self):
+ assert is_ip_blocked("169.254.169.254", allow_localhost=True) is True
+
+ def test_aws_metadata_blocked_with_allow_private_ips(self):
+ """Critical: even when all private IPs are allowed, AWS metadata stays blocked."""
+ assert is_ip_blocked("169.254.169.254", allow_private_ips=True) is True
+
+ def test_aws_metadata_blocked_with_both_flags(self):
+ """Both flags together must not unblock AWS metadata."""
+ assert (
+ is_ip_blocked(
+ "169.254.169.254", allow_localhost=True, allow_private_ips=True
+ )
+ is True
+ )
+
+
+# ---------------------------------------------------------------------------
+# is_ip_blocked -- CGNAT (100.64.0.0/10)
+# ---------------------------------------------------------------------------
+
+
+class TestIsIpBlockedCGNAT:
+ """CGNAT range used by Podman/rootless containers."""
+
+ def test_cgnat_start_blocked(self):
+ assert is_ip_blocked("100.64.0.1") is True
+
+ def test_cgnat_middle_blocked(self):
+ assert is_ip_blocked("100.100.100.100") is True
+
+ def test_cgnat_end_blocked(self):
+ assert is_ip_blocked("100.127.255.255") is True
+
+ def test_cgnat_allowed_with_allow_private_ips(self):
+ assert is_ip_blocked("100.64.0.1", allow_private_ips=True) is False
+ assert is_ip_blocked("100.100.100.100", allow_private_ips=True) is False
+ assert is_ip_blocked("100.127.255.255", allow_private_ips=True) is False
+
+ def test_cgnat_blocked_with_allow_localhost_only(self):
+ """allow_localhost does NOT unblock CGNAT."""
+ assert is_ip_blocked("100.64.0.1", allow_localhost=True) is True
+
+ def test_just_outside_cgnat_not_blocked(self):
+ """100.128.0.0 is outside the 100.64.0.0/10 range and public."""
+ assert is_ip_blocked("100.128.0.0") is False
+
+
+# ---------------------------------------------------------------------------
+# is_ip_blocked -- link-local (169.254.0.0/16)
+# ---------------------------------------------------------------------------
+
+
+class TestIsIpBlockedLinkLocal:
+ """Link-local addresses (169.254.x.x) blocked by default."""
+
+ def test_link_local_blocked(self):
+ assert is_ip_blocked("169.254.1.1") is True
+ assert is_ip_blocked("169.254.100.100") is True
+
+ def test_link_local_beginning_blocked(self):
+ assert is_ip_blocked("169.254.0.1") is True
+
+ def test_link_local_end_blocked(self):
+ assert is_ip_blocked("169.254.255.255") is True
+
+ def test_non_aws_link_local_allowed_with_allow_private_ips(self):
+ """Non-AWS link-local addresses allowed with allow_private_ips."""
+ assert is_ip_blocked("169.254.1.1", allow_private_ips=True) is False
+ assert is_ip_blocked("169.254.100.100", allow_private_ips=True) is False
+ assert is_ip_blocked("169.254.0.1", allow_private_ips=True) is False
+
+ def test_aws_metadata_still_blocked_within_link_local(self):
+ """AWS metadata is a special case within link-local; always blocked."""
+ assert is_ip_blocked("169.254.169.254", allow_private_ips=True) is True
+
+ def test_link_local_blocked_with_allow_localhost_only(self):
+ """allow_localhost does NOT unblock link-local."""
+ assert is_ip_blocked("169.254.1.1", allow_localhost=True) is True
+
+
+# ---------------------------------------------------------------------------
+# is_ip_blocked -- IPv6 private ranges
+# ---------------------------------------------------------------------------
+
+
+class TestIsIpBlockedIPv6Private:
+ """IPv6 ULA (fc00::/7) and link-local (fe80::/10) blocked by default."""
+
+ # -- Unique Local Addresses (fc00::/7) --
+
+ def test_fc00_blocked(self):
+ assert is_ip_blocked("fc00::1") is True
+
+ def test_fd00_blocked(self):
+ assert is_ip_blocked("fd00::1") is True
+
+ def test_fd_range_blocked(self):
+ """fd12:3456:789a::1 is in fc00::/7."""
+ assert is_ip_blocked("fd12:3456:789a::1") is True
+
+ def test_fc00_allowed_with_allow_private_ips(self):
+ assert is_ip_blocked("fc00::1", allow_private_ips=True) is False
+
+ def test_fd00_allowed_with_allow_private_ips(self):
+ assert is_ip_blocked("fd00::1", allow_private_ips=True) is False
+
+ def test_fc00_blocked_with_allow_localhost_only(self):
+ assert is_ip_blocked("fc00::1", allow_localhost=True) is True
+
+ # -- Link-Local (fe80::/10) --
+
+ def test_fe80_blocked(self):
+ assert is_ip_blocked("fe80::1") is True
+
+ def test_fe80_with_interface_id_blocked(self):
+ assert is_ip_blocked("fe80::1234:5678") is True
+
+ def test_fe80_allowed_with_allow_private_ips(self):
+ assert is_ip_blocked("fe80::1", allow_private_ips=True) is False
+ assert is_ip_blocked("fe80::1234:5678", allow_private_ips=True) is False
+
+ def test_fe80_blocked_with_allow_localhost_only(self):
+ assert is_ip_blocked("fe80::1", allow_localhost=True) is True
+
+
+# ---------------------------------------------------------------------------
+# is_ip_blocked -- "this" network (0.0.0.0/8)
+# ---------------------------------------------------------------------------
+
+
+class TestIsIpBlockedZeroNetwork:
+ """The 0.0.0.0/8 'this' network is blocked."""
+
+ def test_0_0_0_0_blocked(self):
+ assert is_ip_blocked("0.0.0.0") is True
+
+ def test_0_x_x_x_blocked(self):
+ assert is_ip_blocked("0.1.2.3") is True
+
+ def test_0_255_255_255_blocked(self):
+ assert is_ip_blocked("0.255.255.255") is True
+
+
+# ---------------------------------------------------------------------------
+# is_ip_blocked -- invalid / edge-case inputs
+# ---------------------------------------------------------------------------
+
+
+class TestIsIpBlockedInvalidInputs:
+ """Invalid or non-IP inputs must return False (not blocked)."""
+
+ def test_invalid_ip_string_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
+
+ def test_hostname_returns_false(self):
+ assert is_ip_blocked("example.com") is False
+
+ def test_url_returns_false(self):
+ """A full URL is not a valid IP string."""
+ assert is_ip_blocked("http://127.0.0.1") is False
+
+ def test_ip_with_port_returns_false(self):
+ """IP:port is not a valid IP address."""
+ assert is_ip_blocked("127.0.0.1:8080") is False
+
+ def test_ip_with_trailing_space_returns_false(self):
+ """Whitespace around an IP makes it invalid."""
+ assert is_ip_blocked(" 127.0.0.1 ") is False
+
+ def test_ip_with_cidr_returns_false(self):
+ """CIDR notation is not a single IP address."""
+ assert is_ip_blocked("10.0.0.0/8") is False
+
+ def test_negative_numbers_returns_false(self):
+ assert is_ip_blocked("-1.0.0.0") is False
+
+ def test_oversized_octet_returns_false(self):
+ assert is_ip_blocked("256.256.256.256") is False
+
+
+# ---------------------------------------------------------------------------
+# is_ip_blocked -- combined flags
+# ---------------------------------------------------------------------------
+
+
+class TestIsIpBlockedCombinedFlags:
+ """Test behaviour when multiple flags are provided together."""
+
+ def test_both_flags_allows_loopback(self):
+ assert (
+ is_ip_blocked(
+ "127.0.0.1", allow_localhost=True, allow_private_ips=True
+ )
+ is False
+ )
+
+ def test_both_flags_allows_private(self):
+ assert (
+ is_ip_blocked(
+ "192.168.1.1", allow_localhost=True, allow_private_ips=True
+ )
+ is False
+ )
+
+ def test_both_flags_still_blocks_aws_metadata(self):
+ assert (
+ is_ip_blocked(
+ "169.254.169.254", allow_localhost=True, allow_private_ips=True
+ )
+ is True
+ )
+
+ def test_both_flags_does_not_block_public(self):
+ assert (
+ is_ip_blocked(
+ "8.8.8.8", allow_localhost=True, allow_private_ips=True
+ )
+ is False
+ )
+
+
+# ---------------------------------------------------------------------------
+# is_ip_blocked -- boundary IPs
+# ---------------------------------------------------------------------------
+
+
+class TestIsIpBlockedBoundaries:
+ """Test IPs at the exact boundaries of blocked ranges."""
+
+ def test_first_ip_of_10_range(self):
+ assert is_ip_blocked("10.0.0.0") is True
+
+ def test_last_ip_of_10_range(self):
+ assert is_ip_blocked("10.255.255.255") is True
+
+ def test_just_before_10_range_not_blocked(self):
+ """9.255.255.255 is just before 10.0.0.0/8."""
+ assert is_ip_blocked("9.255.255.255") is False
+
+ def test_just_after_10_range_not_blocked(self):
+ """11.0.0.0 is just after 10.0.0.0/8."""
+ assert is_ip_blocked("11.0.0.0") is False
+
+ def test_first_ip_of_172_16_range(self):
+ assert is_ip_blocked("172.16.0.0") is True
+
+ def test_last_ip_of_172_16_range(self):
+ assert is_ip_blocked("172.31.255.255") is True
+
+ def test_ip_172_15_255_255_not_blocked(self):
+ """Just below the 172.16.0.0/12 range."""
+ assert is_ip_blocked("172.15.255.255") is False
+
+ def test_ip_172_32_0_0_not_blocked(self):
+ """Just above the 172.16.0.0/12 range."""
+ assert is_ip_blocked("172.32.0.0") is False
+
+ def test_first_ip_of_192_168_range(self):
+ assert is_ip_blocked("192.168.0.0") is True
+
+ def test_last_ip_of_192_168_range(self):
+ assert is_ip_blocked("192.168.255.255") is True
+
+ def test_ip_192_167_255_255_not_blocked(self):
+ assert is_ip_blocked("192.167.255.255") is False
+
+ def test_ip_192_169_0_0_not_blocked(self):
+ assert is_ip_blocked("192.169.0.0") is False
+
+ def test_first_ip_of_cgnat(self):
+ assert is_ip_blocked("100.64.0.0") is True
+
+ def test_last_ip_of_cgnat(self):
+ assert is_ip_blocked("100.127.255.255") is True
+
+ def test_ip_100_63_255_255_not_blocked(self):
+ """Just below CGNAT range."""
+ assert is_ip_blocked("100.63.255.255") is False
+
+ def test_ip_100_128_0_0_not_blocked(self):
+ """Just above CGNAT range."""
+ assert is_ip_blocked("100.128.0.0") is False
+
+
+# ---------------------------------------------------------------------------
+# get_safe_url -- None / empty handling
+# ---------------------------------------------------------------------------
+
+
+class TestGetSafeUrlNoneAndEmpty:
+ """get_safe_url returns default for None or empty strings."""
+
+ def test_none_returns_default_none(self):
+ assert get_safe_url(None) is None
+
+ def test_none_returns_custom_default(self):
+ assert (
+ get_safe_url(None, default="https://fallback.com")
+ == "https://fallback.com"
+ )
+
+ def test_empty_string_returns_default_none(self):
+ assert get_safe_url("") is None
+
+ def test_empty_string_returns_custom_default(self):
+ assert (
+ get_safe_url("", default="https://fallback.com")
+ == "https://fallback.com"
+ )
+
+
+class TestGetSafeUrlPassthrough:
+ """In test mode (PYTEST_CURRENT_TEST set), validate_url returns True
+ so get_safe_url passes through non-empty URLs."""
+
+ def test_non_empty_url_returned(self):
+ result = get_safe_url("https://example.com")
+ assert result == "https://example.com"
+
+ def test_http_url_returned(self):
+ result = get_safe_url("http://example.com")
+ assert result == "http://example.com"
+
+ def test_url_with_path_returned(self):
+ result = get_safe_url("https://example.com/path?q=1")
+ assert result == "https://example.com/path?q=1"
+
+ def test_localhost_url_returned_in_test_mode(self):
+ """validate_url is bypassed in test mode, so even localhost passes."""
+ result = get_safe_url("http://127.0.0.1:8080")
+ assert result == "http://127.0.0.1:8080"
+
+ def test_default_not_used_for_valid_url(self):
+ result = get_safe_url(
+ "https://example.com", default="https://fallback.com"
+ )
+ assert result == "https://example.com"
+
+
+# ---------------------------------------------------------------------------
+# validate_url -- test mode bypass
+# ---------------------------------------------------------------------------
+
+
+class TestValidateUrlTestModeBypass:
+ """Confirm validate_url is bypassed in the test environment."""
+
+ def test_returns_true_for_public_url(self):
+ """Public URL returns True in test mode."""
+ assert validate_url("https://example.com") is True
+
+ def test_returns_true_for_private_ip_url(self):
+ """Private IP URL returns True in test mode (bypassed)."""
+ assert validate_url("http://192.168.1.1") is True
+
+ def test_returns_true_for_localhost_url(self):
+ """Localhost URL returns True in test mode (bypassed)."""
+ assert validate_url("http://127.0.0.1") is True
+
+ def test_returns_true_for_aws_metadata_url(self):
+ """AWS metadata URL returns True in test mode (bypassed).
+ This demonstrates why is_ip_blocked is the correct unit to test
+ for SSRF blocking behaviour."""
+ assert validate_url("http://169.254.169.254/latest/meta-data") is True
diff --git a/tests/security/test_url_builder_extended.py b/tests/security/test_url_builder_extended.py
new file mode 100644
index 0000000000..c09ec45cb4
--- /dev/null
+++ b/tests/security/test_url_builder_extended.py
@@ -0,0 +1,588 @@
+"""
+Extended tests for security/url_builder.py
+
+Covers additional edge cases, boundary conditions, and integration
+scenarios beyond the base test suite for all five public functions
+and the URLBuilderError exception.
+"""
+
+import pytest
+
+from local_deep_research.security.url_builder import (
+ URLBuilderError,
+ normalize_bind_address,
+ build_base_url_from_settings,
+ build_full_url,
+ validate_constructed_url,
+ mask_sensitive_url,
+)
+
+
+# ---------------------------------------------------------------------------
+# normalize_bind_address -- address normalization
+# ---------------------------------------------------------------------------
+class TestNormalizeBindAddressExtended:
+ """Extended tests for normalize_bind_address."""
+
+ def test_ipv4_bind_all_to_localhost(self):
+ """0.0.0.0 is converted to localhost."""
+ assert normalize_bind_address("0.0.0.0") == "localhost"
+
+ def test_ipv6_bind_all_to_localhost(self):
+ """:: is converted to localhost."""
+ assert normalize_bind_address("::") == "localhost"
+
+ def test_localhost_unchanged(self):
+ """localhost passes through without modification."""
+ assert normalize_bind_address("localhost") == "localhost"
+
+ def test_specific_ipv4_unchanged(self):
+ """A specific IPv4 address is returned as-is."""
+ assert normalize_bind_address("192.168.1.1") == "192.168.1.1"
+
+ def test_local_hostname_unchanged(self):
+ """A .local hostname is returned as-is."""
+ assert normalize_bind_address("myhost.local") == "myhost.local"
+
+ def test_loopback_127_unchanged(self):
+ """127.0.0.1 is not converted (only 0.0.0.0 and :: are)."""
+ assert normalize_bind_address("127.0.0.1") == "127.0.0.1"
+
+ def test_fqdn_unchanged(self):
+ """A fully-qualified domain name passes through unchanged."""
+ assert normalize_bind_address("app.example.com") == "app.example.com"
+
+ def test_ipv6_loopback_unchanged(self):
+ """::1 (IPv6 loopback) is not treated as bind-all."""
+ assert normalize_bind_address("::1") == "::1"
+
+ def test_empty_string_unchanged(self):
+ """Empty string is returned as-is (caller is responsible for validation)."""
+ assert normalize_bind_address("") == ""
+
+ def test_10_network_address_unchanged(self):
+ """Private 10.x.x.x address is returned unchanged."""
+ assert normalize_bind_address("10.0.0.1") == "10.0.0.1"
+
+ def test_172_network_address_unchanged(self):
+ """Private 172.16.x.x address is returned unchanged."""
+ assert normalize_bind_address("172.16.0.1") == "172.16.0.1"
+
+
+# ---------------------------------------------------------------------------
+# build_base_url_from_settings -- URL construction from config
+# ---------------------------------------------------------------------------
+class TestBuildBaseUrlFromSettingsExtended:
+ """Extended tests for build_base_url_from_settings."""
+
+ def test_external_url_priority_over_host_port(self):
+ """external_url takes priority even when host and port are provided."""
+ result = build_base_url_from_settings(
+ external_url="https://public.example.com",
+ host="192.168.1.50",
+ port=8080,
+ )
+ assert result == "https://public.example.com"
+
+ def test_external_url_stripped_and_trailing_slash_removed(self):
+ """external_url is stripped of whitespace and trailing slash."""
+ result = build_base_url_from_settings(
+ external_url=" https://app.example.com/ "
+ )
+ assert result == "https://app.example.com"
+
+ def test_host_port_constructs_http_url(self):
+ """host + port constructs an http:// URL."""
+ result = build_base_url_from_settings(
+ external_url=None,
+ host="myserver.local",
+ port=3000,
+ )
+ assert result == "http://myserver.local:3000"
+
+ def test_bind_all_host_normalized_to_localhost(self):
+ """0.0.0.0 host is normalized to localhost in the URL."""
+ result = build_base_url_from_settings(
+ external_url=None,
+ host="0.0.0.0",
+ port=5000,
+ )
+ assert result == "http://localhost:5000"
+
+ def test_fallback_used_when_no_external_or_host_port(self):
+ """fallback_base is used when external_url and host/port are absent."""
+ result = build_base_url_from_settings(
+ external_url=None,
+ host=None,
+ port=None,
+ fallback_base="http://custom-fallback:9090",
+ )
+ assert result == "http://custom-fallback:9090"
+
+ def test_fallback_trailing_slash_stripped(self):
+ """Trailing slash on fallback_base is removed."""
+ result = build_base_url_from_settings(
+ external_url=None,
+ host=None,
+ port=None,
+ fallback_base="http://fallback.local:9090/",
+ )
+ assert result == "http://fallback.local:9090"
+
+ def test_empty_external_url_treated_as_not_provided(self):
+ """Empty string external_url falls through to host/port or fallback."""
+ result = build_base_url_from_settings(
+ external_url="",
+ host=None,
+ port=None,
+ )
+ assert result == "http://localhost:5000"
+
+ def test_whitespace_only_external_url_treated_as_not_provided(self):
+ """Whitespace-only external_url falls through."""
+ result = build_base_url_from_settings(
+ external_url=" ",
+ host=None,
+ port=None,
+ )
+ assert result == "http://localhost:5000"
+
+ def test_port_as_string_is_accepted(self):
+ """Port provided as string is converted to int."""
+ result = build_base_url_from_settings(
+ external_url=None,
+ host="localhost",
+ port="8080",
+ )
+ assert result == "http://localhost:8080"
+
+ def test_invalid_port_raises_url_builder_error(self):
+ """Non-numeric port string raises URLBuilderError."""
+ with pytest.raises(URLBuilderError, match="Failed to build base URL"):
+ build_base_url_from_settings(
+ external_url=None,
+ host="localhost",
+ port="abc",
+ )
+
+ def test_ipv6_bind_all_host_normalized(self):
+ """:: host is normalized to localhost in the URL."""
+ result = build_base_url_from_settings(
+ external_url=None,
+ host="::",
+ port=5000,
+ )
+ assert result == "http://localhost:5000"
+
+ def test_external_url_with_multiple_trailing_slashes(self):
+ """Multiple trailing slashes are stripped from external_url."""
+ result = build_base_url_from_settings(
+ external_url="https://example.com///"
+ )
+ assert result == "https://example.com"
+
+ def test_external_url_with_path(self):
+ """external_url that includes a path keeps the path (minus trailing /)."""
+ result = build_base_url_from_settings(
+ external_url="https://example.com/app/"
+ )
+ assert result == "https://example.com/app"
+
+ def test_default_fallback_value(self):
+ """Default fallback_base is http://localhost:5000."""
+ result = build_base_url_from_settings()
+ assert result == "http://localhost:5000"
+
+ def test_host_without_port_uses_fallback(self):
+ """If host is given but port is None, fallback is used."""
+ result = build_base_url_from_settings(
+ external_url=None,
+ host="somehost",
+ port=None,
+ fallback_base="http://default:7777",
+ )
+ assert result == "http://default:7777"
+
+ def test_port_without_host_uses_fallback(self):
+ """If port is given but host is None, fallback is used."""
+ result = build_base_url_from_settings(
+ external_url=None,
+ host=None,
+ port=5000,
+ fallback_base="http://default:7777",
+ )
+ assert result == "http://default:7777"
+
+
+# ---------------------------------------------------------------------------
+# build_full_url -- base + path combination
+# ---------------------------------------------------------------------------
+class TestBuildFullUrlExtended:
+ """Extended tests for build_full_url."""
+
+ def test_combines_base_and_path(self):
+ """Base URL and path are joined correctly."""
+ result = build_full_url("https://example.com", "/api/v1", validate=True)
+ assert result == "https://example.com/api/v1"
+
+ def test_trailing_slash_removed_from_base(self):
+ """Trailing slash on base_url is stripped before joining."""
+ result = build_full_url(
+ "https://example.com/", "/endpoint", validate=True
+ )
+ assert result == "https://example.com/endpoint"
+
+ def test_leading_slash_added_to_path(self):
+ """Path without leading slash gets one prepended."""
+ result = build_full_url(
+ "https://example.com", "path/here", validate=True
+ )
+ assert result == "https://example.com/path/here"
+
+ def test_validate_true_raises_on_invalid_url(self):
+ """validate=True raises URLBuilderError for a schemeless base."""
+ with pytest.raises(URLBuilderError):
+ build_full_url("not-a-url", "/path", validate=True)
+
+ def test_validate_false_skips_validation(self):
+ """validate=False allows any string combination through."""
+ result = build_full_url("no-scheme", "/path", validate=False)
+ assert result == "no-scheme/path"
+
+ def test_allowed_schemes_rejects_wrong_scheme(self):
+ """URL with disallowed scheme raises URLBuilderError."""
+ with pytest.raises(URLBuilderError, match="not in allowed schemes"):
+ build_full_url(
+ "ftp://files.example.com",
+ "/data",
+ validate=True,
+ allowed_schemes=["http", "https"],
+ )
+
+ def test_allowed_schemes_accepts_correct_scheme(self):
+ """URL with allowed scheme passes validation."""
+ result = build_full_url(
+ "https://example.com",
+ "/secure",
+ validate=True,
+ allowed_schemes=["https"],
+ )
+ assert result == "https://example.com/secure"
+
+ def test_path_already_has_leading_slash(self):
+ """Path that already starts with / is not double-slashed."""
+ result = build_full_url(
+ "https://example.com", "/already/slashed", validate=True
+ )
+ assert "//already" not in result
+ assert result == "https://example.com/already/slashed"
+
+ def test_base_url_with_path_component(self):
+ """Base URL that includes a path appends new path correctly."""
+ result = build_full_url(
+ "https://example.com/app", "/api/test", validate=False
+ )
+ assert result == "https://example.com/app/api/test"
+
+ def test_empty_path_gets_leading_slash(self):
+ """Empty path results in trailing slash after base."""
+ result = build_full_url("https://example.com", "", validate=False)
+ assert result == "https://example.com/"
+
+ def test_path_with_query_string(self):
+ """Path containing query string is appended as-is."""
+ result = build_full_url(
+ "https://example.com", "/search?q=test", validate=True
+ )
+ assert result == "https://example.com/search?q=test"
+
+ def test_path_with_fragment(self):
+ """Path containing fragment is appended as-is."""
+ result = build_full_url(
+ "https://example.com", "/page#section", validate=True
+ )
+ assert result == "https://example.com/page#section"
+
+
+# ---------------------------------------------------------------------------
+# validate_constructed_url -- URL validation
+# ---------------------------------------------------------------------------
+class TestValidateConstructedUrlExtended:
+ """Extended tests for validate_constructed_url."""
+
+ def test_empty_string_raises(self):
+ """Empty string raises URLBuilderError."""
+ with pytest.raises(URLBuilderError, match="non-empty string"):
+ validate_constructed_url("")
+
+ def test_none_raises(self):
+ """None raises URLBuilderError."""
+ with pytest.raises(URLBuilderError, match="non-empty string"):
+ validate_constructed_url(None)
+
+ def test_no_scheme_raises(self):
+ """URL without scheme raises URLBuilderError."""
+ with pytest.raises(URLBuilderError, match="scheme"):
+ validate_constructed_url("example.com/path")
+
+ def test_no_hostname_raises(self):
+ """URL without hostname (empty netloc) raises URLBuilderError."""
+ with pytest.raises(URLBuilderError, match="hostname"):
+ validate_constructed_url("http:///path/only")
+
+ def test_valid_http_url_returns_true(self):
+ """Valid HTTP URL returns True."""
+ assert validate_constructed_url("http://example.com/api") is True
+
+ def test_valid_https_url_returns_true(self):
+ """Valid HTTPS URL returns True."""
+ assert validate_constructed_url("https://secure.example.com") is True
+
+ def test_wrong_scheme_with_allowed_schemes_raises(self):
+ """Scheme not in allowed_schemes list raises URLBuilderError."""
+ with pytest.raises(URLBuilderError, match="not in allowed schemes"):
+ validate_constructed_url(
+ "http://example.com", allowed_schemes=["https"]
+ )
+
+ def test_correct_scheme_with_allowed_schemes_passes(self):
+ """Scheme in allowed_schemes list passes."""
+ assert (
+ validate_constructed_url(
+ "https://example.com", allowed_schemes=["https"]
+ )
+ is True
+ )
+
+ def test_none_allowed_schemes_accepts_any(self):
+ """None for allowed_schemes accepts any scheme."""
+ assert (
+ validate_constructed_url(
+ "custom://something.local", allowed_schemes=None
+ )
+ is True
+ )
+
+ def test_ftp_scheme_with_ftp_allowed(self):
+ """ftp:// passes when ftp is in allowed_schemes."""
+ assert (
+ validate_constructed_url(
+ "ftp://files.example.com/data",
+ allowed_schemes=["ftp", "sftp"],
+ )
+ is True
+ )
+
+ def test_url_with_port(self):
+ """URL with port validates successfully."""
+ assert validate_constructed_url("https://example.com:8443/api") is True
+
+ def test_url_with_auth_info(self):
+ """URL containing user:pass@host validates (netloc is present)."""
+ assert (
+ validate_constructed_url("https://user:[email protected]/path")
+ is True
+ )
+
+ def test_integer_input_raises(self):
+ """Non-string input raises URLBuilderError."""
+ with pytest.raises(URLBuilderError, match="non-empty string"):
+ validate_constructed_url(42)
+
+ def test_url_with_query_and_fragment(self):
+ """URL with query string and fragment validates."""
+ assert (
+ validate_constructed_url("https://example.com/path?key=val#section")
+ is True
+ )
+
+
+# ---------------------------------------------------------------------------
+# mask_sensitive_url -- sensitive data masking for logging
+# ---------------------------------------------------------------------------
+class TestMaskSensitiveUrlExtended:
+ """Extended tests for mask_sensitive_url."""
+
+ def test_password_masked(self):
+ """Password in user:pass@host URL is replaced with ***."""
+ result = mask_sensitive_url("https://admin:[email protected]/api")
+ assert "s3cret" not in result
+ assert "admin" in result
+ assert "***" in result
+ assert "example.com" in result
+
+ def test_long_path_token_masked(self):
+ """Path segments >= 20 alphanumeric chars are masked."""
+ token = "a" * 20 # exactly 20 chars
+ result = mask_sensitive_url(f"https://hooks.slack.com/services/{token}")
+ assert token not in result
+ assert "/***" in result
+
+ def test_query_string_masked(self):
+ """Query string is replaced with ?***."""
+ result = mask_sensitive_url(
+ "https://api.example.com/data?api_key=supersecret&format=json"
+ )
+ assert "api_key" not in result
+ assert "supersecret" not in result
+ assert "?***" in result
+
+ def test_url_without_sensitive_parts_unchanged(self):
+ """URL with no password, long tokens, or query is mostly preserved."""
+ url = "https://example.com/api/users"
+ result = mask_sensitive_url(url)
+ assert "example.com" in result
+ assert "/api/users" in result
+ assert "https://" in result
+
+ def test_short_path_segments_not_masked(self):
+ """Path segments shorter than 20 chars are NOT masked."""
+ result = mask_sensitive_url("https://example.com/short/path/here")
+ assert "/short/path/here" in result
+
+ def test_invalid_url_returns_partial_mask(self):
+ """Malformed URL without netloc does not crash and returns a string.
+
+ urlparse handles most strings without raising, so the function
+ reconstructs from whatever components it can extract. The except
+ branch (returning 'scheme://***') only fires for truly exceptional
+ inputs. Here we verify graceful handling rather than the exact
+ fallback format.
+ """
+ result = mask_sensitive_url("http:not-valid-at-all")
+ assert result is not None
+ assert isinstance(result, str)
+ assert "http" in result
+
+ def test_webhook_url_with_long_token_masked(self):
+ """Webhook URL with a long token in the path gets the token masked."""
+ token = "T0123456789abcdefghij" # 21 chars
+ result = mask_sensitive_url(
+ f"https://hooks.slack.com/services/{token}/more"
+ )
+ assert token not in result
+ assert "/***" in result
+ assert "hooks.slack.com" in result
+
+ def test_url_with_port_preserved(self):
+ """Port number in URL is preserved after masking."""
+ result = mask_sensitive_url("https://example.com:8443/api/short")
+ assert ":8443" in result
+
+ def test_multiple_long_path_segments_masked(self):
+ """Multiple long path segments are each masked independently."""
+ token1 = "abcdefghijklmnopqrstu" # 21 chars
+ token2 = "12345678901234567890XX" # 22 chars
+ result = mask_sensitive_url(
+ f"https://hooks.example.com/{token1}/{token2}"
+ )
+ assert token1 not in result
+ assert token2 not in result
+
+ def test_combined_password_token_and_query(self):
+ """URL with password, long token, and query gets all masked."""
+ token = "aabbccddee1122334455ff" # 22 chars
+ result = mask_sensitive_url(
+ f"https://user:[email protected]/hook/{token}?secret=yes"
+ )
+ assert "password" not in result
+ assert token not in result
+ assert "secret=yes" not in result
+ assert "?***" in result
+ assert "user" in result
+
+ def test_scheme_preserved(self):
+ """The URL scheme is always preserved."""
+ result = mask_sensitive_url("http://user:[email protected]/path")
+ assert result.startswith("http://")
+
+ def test_path_segment_exactly_19_chars_not_masked(self):
+ """A path segment of exactly 19 chars is NOT masked (threshold is 20)."""
+ segment = "a" * 19
+ result = mask_sensitive_url(f"https://example.com/{segment}")
+ assert segment in result
+
+ def test_path_segment_exactly_20_chars_masked(self):
+ """A path segment of exactly 20 chars IS masked."""
+ segment = "b" * 20
+ result = mask_sensitive_url(f"https://example.com/{segment}")
+ assert segment not in result
+ assert "/***" in result
+
+ def test_url_with_only_query_no_password(self):
+ """URL with query but no password masks only the query."""
+ result = mask_sensitive_url("https://example.com/api?token=abc123")
+ assert "token=abc123" not in result
+ assert "?***" in result
+ assert "example.com" in result
+ assert "/api" in result
+
+ def test_url_with_hyphen_underscore_token_masked(self):
+ """Long tokens containing hyphens and underscores are masked."""
+ token = "abc-def_ghi-jkl_mno-pqrs" # 24 chars with hyphens/underscores
+ result = mask_sensitive_url(f"https://example.com/hook/{token}")
+ assert token not in result
+
+ def test_empty_path_no_crash(self):
+ """URL with empty path does not crash."""
+ result = mask_sensitive_url("https://example.com")
+ assert "example.com" in result
+
+
+# ---------------------------------------------------------------------------
+# Integration -- combining multiple functions
+# ---------------------------------------------------------------------------
+class TestURLBuilderIntegrationExtended:
+ """Integration scenarios combining multiple url_builder functions."""
+
+ def test_settings_to_full_url_to_mask_workflow(self):
+ """Full workflow: settings -> base URL -> full URL -> masked for logging."""
+ base = build_base_url_from_settings(
+ external_url="https://app.example.com/"
+ )
+ full = build_full_url(base, "/api/v1/research/42")
+ assert validate_constructed_url(full) is True
+ masked = mask_sensitive_url(full)
+ assert "app.example.com" in masked
+
+ def test_host_port_to_full_url_normalized(self):
+ """Build from 0.0.0.0 host, construct full URL, validate."""
+ base = build_base_url_from_settings(host="0.0.0.0", port=8080)
+ assert "localhost" in base
+ full = build_full_url(base, "health/check")
+ assert full == "http://localhost:8080/health/check"
+ assert validate_constructed_url(full) is True
+
+ def test_fallback_to_full_url(self):
+ """Fallback base URL + path produces valid URL."""
+ base = build_base_url_from_settings(
+ external_url="",
+ host=None,
+ port=None,
+ fallback_base="http://fallback:7000/",
+ )
+ full = build_full_url(base, "/status")
+ assert full == "http://fallback:7000/status"
+ assert validate_constructed_url(full) is True
+
+ def test_mask_url_with_credentials_from_build(self):
+ """Masking a URL built with embedded credentials hides the password."""
+ full = build_full_url(
+ "https://admin:[email protected]",
+ "/api/data",
+ validate=False,
+ )
+ masked = mask_sensitive_url(full)
+ assert "topsecret" not in masked
+ assert "admin" in masked
+ assert "***" in masked
+
+ def test_validate_rejects_then_build_without_validate(self):
+ """Demonstrate that validate=False allows construction that would fail."""
+ # This should fail with validation
+ with pytest.raises(URLBuilderError):
+ build_full_url("noscheme", "/path", validate=True)
+
+ # But succeeds without validation
+ result = build_full_url("noscheme", "/path", validate=False)
+ assert result == "noscheme/path"
diff --git a/tests/security/test_url_validator_extended.py b/tests/security/test_url_validator_extended.py
new file mode 100644
index 0000000000..43bd3f244c
--- /dev/null
+++ b/tests/security/test_url_validator_extended.py
@@ -0,0 +1,856 @@
+"""
+Extended security-focused tests for URLValidator.
+
+Covers edge cases and attack vectors beyond the base test suite,
+with particular emphasis on is_safe_redirect_url bypass attempts
+and subtle encoding tricks.
+"""
+
+import pytest
+
+from local_deep_research.security.url_validator import (
+ URLValidator,
+ URLValidationError,
+)
+
+
+# ---------------------------------------------------------------------------
+# is_unsafe_scheme -- case & whitespace edge cases
+# ---------------------------------------------------------------------------
+class TestIsUnsafeSchemeExtended:
+ """Extended edge-case tests for is_unsafe_scheme."""
+
+ @pytest.mark.parametrize(
+ "url",
+ [
+ "JaVaScRiPt:void(0)",
+ "JAVASCRIPT:alert(1)",
+ "Javascript:alert(document.cookie)",
+ "jAvAsCrIpT:alert('XSS')",
+ ],
+ )
+ def test_javascript_case_variations(self, url):
+ """All mixed-case variants of javascript: are detected."""
+ assert URLValidator.is_unsafe_scheme(url) is True
+
+ @pytest.mark.parametrize(
+ "url",
+ [
+ "DATA:text/html,<h1>hi</h1>",
+ "Data:text/html;base64,PHNjcmlwdD4=",
+ "VBSCRIPT:MsgBox",
+ "VbScript:Execute",
+ "ABOUT:blank",
+ "About:config",
+ "BLOB:https://evil.com/id",
+ "Blob:http://evil.com/id",
+ "FILE:///etc/shadow",
+ "File:///C:/Windows/System32",
+ ],
+ )
+ def test_all_unsafe_schemes_case_insensitive(self, url):
+ """Every unsafe scheme is caught regardless of casing."""
+ assert URLValidator.is_unsafe_scheme(url) is True
+
+ def test_tab_inside_scheme_not_detected(self):
+ """Tab character inside scheme string is not stripped (raw input)."""
+ # "java\tscript:" does not match "javascript:" after strip+lower
+ assert URLValidator.is_unsafe_scheme("java\tscript:alert(1)") is False
+
+ def test_scheme_with_leading_whitespace(self):
+ """Leading spaces are stripped before checking."""
+ assert URLValidator.is_unsafe_scheme(" data:text/html,hi") is True
+
+ def test_scheme_with_trailing_whitespace(self):
+ """Trailing spaces are stripped before checking."""
+ assert URLValidator.is_unsafe_scheme("file:///etc/passwd ") is True
+
+ @pytest.mark.parametrize(
+ "safe_url",
+ [
+ "http://example.com",
+ "https://example.com",
+ "ftp://ftp.example.com/file",
+ "ftps://secure.example.com/file",
+ "mailto:[email protected]",
+ ],
+ )
+ def test_safe_schemes_not_flagged(self, safe_url):
+ """Known-safe schemes are never reported as unsafe."""
+ assert URLValidator.is_unsafe_scheme(safe_url) is False
+
+ def test_empty_string(self):
+ """Empty string returns False."""
+ assert URLValidator.is_unsafe_scheme("") is False
+
+ def test_none_input(self):
+ """None returns False."""
+ assert URLValidator.is_unsafe_scheme(None) is False
+
+ def test_plain_text_no_colon(self):
+ """Plain text without colon is not unsafe."""
+ assert URLValidator.is_unsafe_scheme("just some text") is False
+
+
+# ---------------------------------------------------------------------------
+# is_safe_url -- comprehensive scheme / option / pattern tests
+# ---------------------------------------------------------------------------
+class TestIsSafeUrlExtended:
+ """Extended tests for is_safe_url covering all parameter combos."""
+
+ # -- unsafe scheme rejection via is_safe_url --------
+ @pytest.mark.parametrize(
+ "url",
+ [
+ "javascript:void(0)",
+ "data:image/png;base64,iVBOR",
+ "vbscript:Run",
+ "about:blank",
+ "blob:null/abc",
+ "file:///etc/hosts",
+ ],
+ )
+ def test_all_unsafe_schemes_rejected(self, url):
+ """Every unsafe scheme is rejected by is_safe_url."""
+ assert URLValidator.is_safe_url(url) is False
+
+ # -- fragment-only URLs --------
+ def test_fragment_only_allowed_by_default(self):
+ assert URLValidator.is_safe_url("#top") is True
+
+ def test_fragment_only_disallowed(self):
+ assert URLValidator.is_safe_url("#top", allow_fragments=False) is False
+
+ def test_fragment_with_complex_id(self):
+ """Fragment with complex anchor name is allowed when fragments on."""
+ assert URLValidator.is_safe_url("#section-2.3_foo") is True
+
+ # -- mailto handling --------
+ def test_mailto_default_rejected(self):
+ assert URLValidator.is_safe_url("mailto:[email protected]") is False
+
+ def test_mailto_allowed_flag(self):
+ assert (
+ URLValidator.is_safe_url("mailto:[email protected]", allow_mailto=True)
+ is True
+ )
+
+ def test_mailto_with_subject(self):
+ assert (
+ URLValidator.is_safe_url(
+ "mailto:[email protected]?subject=Hi", allow_mailto=True
+ )
+ is True
+ )
+
+ # -- require_scheme --------
+ def test_no_scheme_rejected_by_default(self):
+ assert URLValidator.is_safe_url("example.com/page") is False
+
+ def test_no_scheme_allowed_when_disabled(self):
+ assert (
+ URLValidator.is_safe_url("example.com/page", require_scheme=False)
+ is True
+ )
+
+ # -- trusted_domains filtering --------
+ def test_trusted_domain_exact(self):
+ assert (
+ URLValidator.is_safe_url(
+ "https://example.com/p", trusted_domains=["example.com"]
+ )
+ is True
+ )
+
+ def test_trusted_domain_subdomain(self):
+ assert (
+ URLValidator.is_safe_url(
+ "https://sub.example.com/p", trusted_domains=["example.com"]
+ )
+ is True
+ )
+
+ def test_untrusted_domain_blocked(self):
+ assert (
+ URLValidator.is_safe_url(
+ "https://evil.com/p", trusted_domains=["example.com"]
+ )
+ is False
+ )
+
+ def test_partial_domain_match_rejected(self):
+ """notexample.com should NOT match trusted domain example.com."""
+ assert (
+ URLValidator.is_safe_url(
+ "https://notexample.com/p", trusted_domains=["example.com"]
+ )
+ is False
+ )
+
+ def test_trusted_domains_case_insensitive(self):
+ """Domain matching is case-insensitive."""
+ assert (
+ URLValidator.is_safe_url(
+ "https://EXAMPLE.COM/p", trusted_domains=["example.com"]
+ )
+ is True
+ )
+
+ # -- suspicious patterns blocked --------
+ def test_double_encoded_slash(self):
+ assert URLValidator.is_safe_url("https://x.com/%252F..") is False
+
+ def test_null_byte_in_path(self):
+ assert URLValidator.is_safe_url("https://x.com/f%00.txt") is False
+
+ def test_html_entity_amp(self):
+ assert URLValidator.is_safe_url("https://x.com/path&amp;extra") is False
+
+ def test_html_entity_hex(self):
+ assert (
+ URLValidator.is_safe_url("https://x.com/path&#x41;extra") is False
+ )
+
+ def test_normal_percent_encoding_ok(self):
+ """Standard percent-encoding (%20 for space) is NOT suspicious."""
+ assert URLValidator.is_safe_url("https://x.com/hello%20world") is True
+
+ # -- non-string input --------
+ def test_integer_input(self):
+ assert URLValidator.is_safe_url(12345) is False
+
+ def test_list_input(self):
+ assert URLValidator.is_safe_url(["https://x.com"]) is False
+
+ # -- unknown scheme --------
+ def test_gopher_scheme_rejected(self):
+ assert URLValidator.is_safe_url("gopher://gopher.example.com") is False
+
+ def test_telnet_scheme_rejected(self):
+ assert URLValidator.is_safe_url("telnet://192.168.1.1") is False
+
+
+# ---------------------------------------------------------------------------
+# _has_suspicious_patterns -- direct tests on the private helper
+# ---------------------------------------------------------------------------
+class TestHasSuspiciousPatternsExtended:
+ """Direct tests on _has_suspicious_patterns for attack payloads."""
+
+ def test_double_encoding_percent_25_hex(self):
+ """%2500 is double-encoded null byte."""
+ assert (
+ URLValidator._has_suspicious_patterns("https://x.com/%2500") is True
+ )
+
+ def test_double_encoding_percent_25_generic(self):
+ """%25XX matches double encoding."""
+ assert (
+ URLValidator._has_suspicious_patterns("https://x.com/%252F") is True
+ )
+
+ def test_null_byte_percent_00(self):
+ """%00 null byte detected."""
+ assert (
+ URLValidator._has_suspicious_patterns("https://x.com/%00") is True
+ )
+
+ def test_null_byte_mid_path(self):
+ assert (
+ URLValidator._has_suspicious_patterns("https://x.com/a%00b") is True
+ )
+
+ def test_unicode_escape_lowercase(self):
+ """\\u0041 unicode escape detected."""
+ assert (
+ URLValidator._has_suspicious_patterns("https://x.com/path\\u0041")
+ is True
+ )
+
+ def test_unicode_escape_uppercase(self):
+ assert (
+ URLValidator._has_suspicious_patterns("https://x.com/path\\u004F")
+ is True
+ )
+
+ def test_html_entity_named(self):
+ """Named HTML entities like &amp; detected."""
+ assert (
+ URLValidator._has_suspicious_patterns("https://x.com/&amp;") is True
+ )
+
+ def test_html_entity_decimal(self):
+ """Decimal HTML entities like &#65; detected."""
+ assert (
+ URLValidator._has_suspicious_patterns("https://x.com/&#65;") is True
+ )
+
+ def test_html_entity_hex_entity(self):
+ """Hex HTML entities like &#x41; detected."""
+ assert (
+ URLValidator._has_suspicious_patterns("https://x.com/&#x41;")
+ is True
+ )
+
+ def test_html_entity_lt_gt(self):
+ assert (
+ URLValidator._has_suspicious_patterns(
+ "https://x.com/&lt;script&gt;"
+ )
+ is True
+ )
+
+ def test_clean_url_not_flagged(self):
+ """Ordinary HTTPS URL is not suspicious."""
+ assert (
+ URLValidator._has_suspicious_patterns(
+ "https://example.com/path?q=hello&page=2"
+ )
+ is False
+ )
+
+ def test_clean_percent_encoding_not_flagged(self):
+ """Standard percent encoding is clean."""
+ assert (
+ URLValidator._has_suspicious_patterns(
+ "https://example.com/hello%20world"
+ )
+ is False
+ )
+
+
+# ---------------------------------------------------------------------------
+# sanitize_url
+# ---------------------------------------------------------------------------
+class TestSanitizeUrlExtended:
+ """Extended tests for sanitize_url."""
+
+ def test_empty_returns_none(self):
+ assert URLValidator.sanitize_url("") is None
+
+ def test_none_returns_none(self):
+ assert URLValidator.sanitize_url(None) is None
+
+ def test_unsafe_javascript_returns_none(self):
+ assert URLValidator.sanitize_url("javascript:void(0)") is None
+
+ def test_unsafe_data_returns_none(self):
+ assert URLValidator.sanitize_url("data:text/html,hi") is None
+
+ def test_unsafe_file_returns_none(self):
+ assert URLValidator.sanitize_url("file:///etc/passwd") is None
+
+ def test_adds_default_https(self):
+ result = URLValidator.sanitize_url("example.com/page")
+ assert result == "https://example.com/page"
+
+ def test_adds_custom_http_scheme(self):
+ result = URLValidator.sanitize_url("example.com", default_scheme="http")
+ assert result == "http://example.com"
+
+ def test_preserves_existing_https(self):
+ result = URLValidator.sanitize_url("https://example.com/p")
+ assert result == "https://example.com/p"
+
+ def test_preserves_existing_http(self):
+ result = URLValidator.sanitize_url("http://example.com/p")
+ assert result == "http://example.com/p"
+
+ def test_strips_whitespace_then_adds_scheme(self):
+ result = URLValidator.sanitize_url(" example.com ")
+ assert result == "https://example.com"
+
+ def test_url_with_suspicious_pattern_returns_none(self):
+ """URL with double encoding is rejected after scheme addition."""
+ result = URLValidator.sanitize_url("example.com/%2500")
+ assert result is None
+
+ def test_url_with_null_byte_returns_none(self):
+ result = URLValidator.sanitize_url("example.com/path%00")
+ assert result is None
+
+ def test_url_with_existing_scheme_and_port(self):
+ """URL that already has a scheme and port is preserved."""
+ result = URLValidator.sanitize_url("https://example.com:8080/api")
+ assert result == "https://example.com:8080/api"
+
+ def test_bare_host_with_port_returns_none(self):
+ """Bare host:port without scheme is ambiguous for urlparse.
+
+ urlparse treats 'example.com' as the scheme and '8080/api' as
+ the path, so the resulting URL is invalid and returns None.
+ """
+ result = URLValidator.sanitize_url("example.com:8080/api")
+ assert result is None
+
+
+# ---------------------------------------------------------------------------
+# is_academic_url -- every trusted domain + subdomains + negatives
+# ---------------------------------------------------------------------------
+class TestIsAcademicUrlExtended:
+ """Extended tests for is_academic_url covering all TRUSTED_ACADEMIC_DOMAINS."""
+
+ @pytest.mark.parametrize(
+ "domain",
+ [
+ "arxiv.org",
+ "pubmed.ncbi.nlm.nih.gov",
+ "ncbi.nlm.nih.gov",
+ "biorxiv.org",
+ "medrxiv.org",
+ "doi.org",
+ "nature.com",
+ "science.org",
+ "sciencedirect.com",
+ "springer.com",
+ "wiley.com",
+ "plos.org",
+ "pnas.org",
+ "ieee.org",
+ "acm.org",
+ ],
+ )
+ def test_each_trusted_domain_recognized(self, domain):
+ """Each trusted academic domain is recognized."""
+ assert URLValidator.is_academic_url(f"https://{domain}/article") is True
+
+ @pytest.mark.parametrize(
+ "domain",
+ [
+ "arxiv.org",
+ "nature.com",
+ "springer.com",
+ "ieee.org",
+ "acm.org",
+ ],
+ )
+ def test_www_subdomain_recognized(self, domain):
+ """www. subdomain of each trusted domain is recognized."""
+ assert (
+ URLValidator.is_academic_url(f"https://www.{domain}/page") is True
+ )
+
+ def test_deep_subdomain_recognized(self):
+ """Deep subdomain of trusted domain is recognized."""
+ assert (
+ URLValidator.is_academic_url("https://deep.sub.nature.com/paper")
+ is True
+ )
+
+ def test_non_academic_domain(self):
+ assert (
+ URLValidator.is_academic_url("https://example.com/paper") is False
+ )
+
+ def test_empty_url(self):
+ assert URLValidator.is_academic_url("") is False
+
+ def test_no_hostname(self):
+ """URL with no parseable hostname returns False."""
+ assert URLValidator.is_academic_url("not-a-url") is False
+
+ def test_partial_domain_name_not_matched(self):
+ """fakearxiv.org should NOT match arxiv.org."""
+ assert (
+ URLValidator.is_academic_url("https://fakearxiv.org/abs/123")
+ is False
+ )
+
+ def test_domain_as_path_not_matched(self):
+ """arxiv.org appearing only in path (not hostname) is not academic."""
+ assert (
+ URLValidator.is_academic_url("https://evil.com/arxiv.org/abs/123")
+ is False
+ )
+
+
+# ---------------------------------------------------------------------------
+# extract_doi
+# ---------------------------------------------------------------------------
+class TestExtractDoiExtended:
+ """Extended DOI extraction tests."""
+
+ def test_doi_org_standard(self):
+ result = URLValidator.extract_doi("https://doi.org/10.1038/nature12373")
+ assert result == "10.1038/nature12373"
+
+ def test_direct_doi_pattern(self):
+ result = URLValidator.extract_doi("10.1234/test.paper.v2")
+ assert result is not None
+ assert result.startswith("10.1234/")
+
+ def test_doi_with_parentheses(self):
+ result = URLValidator.extract_doi("https://doi.org/10.1002/(SICI)1234")
+ assert result is not None
+ assert "10.1002" in result
+
+ def test_doi_with_semicolons_underscores(self):
+ result = URLValidator.extract_doi("10.1000/journal_name;v2")
+ assert result is not None
+
+ def test_no_doi_returns_none(self):
+ assert URLValidator.extract_doi("https://example.com/page") is None
+
+ def test_empty_string_returns_none(self):
+ assert URLValidator.extract_doi("") is None
+
+ def test_doi_embedded_in_text(self):
+ """DOI embedded in longer text is extracted."""
+ result = URLValidator.extract_doi(
+ "See paper at doi.org/10.5555/some-article for details"
+ )
+ assert result is not None
+ assert "10.5555" in result
+
+ def test_five_digit_registrant(self):
+ """DOI with 5-digit registrant code is extracted."""
+ result = URLValidator.extract_doi("10.12345/long-registrant")
+ assert result is not None
+ assert result.startswith("10.12345/")
+
+
+# ---------------------------------------------------------------------------
+# validate_http_url
+# ---------------------------------------------------------------------------
+class TestValidateHttpUrlExtended:
+ """Extended tests for validate_http_url strict validation."""
+
+ def test_empty_string_raises(self):
+ with pytest.raises(URLValidationError):
+ URLValidator.validate_http_url("")
+
+ def test_none_raises(self):
+ with pytest.raises(URLValidationError):
+ URLValidator.validate_http_url(None)
+
+ def test_no_scheme_raises(self):
+ with pytest.raises(URLValidationError, match="(?i)scheme"):
+ URLValidator.validate_http_url("example.com/callback")
+
+ def test_ftp_scheme_raises(self):
+ with pytest.raises(URLValidationError, match="(?i)http"):
+ URLValidator.validate_http_url("ftp://example.com/file")
+
+ def test_javascript_scheme_raises(self):
+ with pytest.raises(URLValidationError):
+ URLValidator.validate_http_url("javascript:alert(1)")
+
+ def test_data_scheme_raises(self):
+ with pytest.raises(URLValidationError):
+ URLValidator.validate_http_url("data:text/html,hi")
+
+ def test_valid_https_passes(self):
+ assert URLValidator.validate_http_url("https://example.com/cb") is True
+
+ def test_valid_http_passes(self):
+ assert (
+ URLValidator.validate_http_url("http://localhost:5000/cb") is True
+ )
+
+ def test_missing_netloc_raises(self):
+ with pytest.raises(URLValidationError, match="(?i)hostname"):
+ URLValidator.validate_http_url("http:///path/only")
+
+ def test_leading_dot_in_netloc_raises(self):
+ with pytest.raises(URLValidationError):
+ URLValidator.validate_http_url("https://.example.com/p")
+
+ def test_trailing_dot_in_netloc_raises(self):
+ with pytest.raises(URLValidationError):
+ URLValidator.validate_http_url("https://example.com./p")
+
+ def test_url_with_suspicious_pattern_raises(self):
+ """URL that passes scheme/netloc but has suspicious patterns raises."""
+ with pytest.raises(URLValidationError):
+ URLValidator.validate_http_url("https://example.com/%2500")
+
+ def test_integer_input_raises(self):
+ with pytest.raises(URLValidationError):
+ URLValidator.validate_http_url(12345)
+
+ def test_valid_url_with_path_query_fragment(self):
+ assert (
+ URLValidator.validate_http_url(
+ "https://example.com/api/v1?key=val#sec"
+ )
+ is True
+ )
+
+ def test_valid_url_with_port(self):
+ assert (
+ URLValidator.validate_http_url("https://example.com:443/path")
+ is True
+ )
+
+
+# ---------------------------------------------------------------------------
+# is_safe_redirect_url -- CRITICAL SECURITY
+# ---------------------------------------------------------------------------
+class TestIsSafeRedirectUrlExtended:
+ """
+ Exhaustive security tests for is_safe_redirect_url.
+
+ This is the most security-critical method because it prevents
+ open-redirect attacks which can be chained with phishing and
+ OAuth token theft.
+ """
+
+ HOST = "http://example.com/"
+
+ # -- empty / None target --
+ def test_empty_target_returns_false(self):
+ assert URLValidator.is_safe_redirect_url("", self.HOST) is False
+
+ def test_none_target_returns_false(self):
+ """None target should return False (caught by 'if not target')."""
+ assert URLValidator.is_safe_redirect_url(None, self.HOST) is False
+
+ # -- CRLF injection --
+ def test_crlf_rn(self):
+ assert (
+ URLValidator.is_safe_redirect_url(
+ "/path\r\nSet-Cookie: evil=1", self.HOST
+ )
+ is False
+ )
+
+ def test_cr_only(self):
+ assert (
+ URLValidator.is_safe_redirect_url(
+ "/path\rX-Injected: yes", self.HOST
+ )
+ is False
+ )
+
+ def test_lf_only(self):
+ assert (
+ URLValidator.is_safe_redirect_url(
+ "/path\nX-Injected: yes", self.HOST
+ )
+ is False
+ )
+
+ def test_crlf_at_start(self):
+ assert (
+ URLValidator.is_safe_redirect_url("\r\n/path", self.HOST) is False
+ )
+
+ # -- protocol-relative URL bypass --
+ def test_double_slash_evil(self):
+ """//evil.com is protocol-relative -- must be blocked."""
+ assert (
+ URLValidator.is_safe_redirect_url("//evil.com/path", self.HOST)
+ is False
+ )
+
+ def test_triple_slash_evil(self):
+ """///evil.com is another bypass variant."""
+ assert (
+ URLValidator.is_safe_redirect_url("///evil.com", self.HOST) is False
+ )
+
+ def test_double_slash_with_user_info(self):
+ """//[email protected] bypass attempt."""
+ assert (
+ URLValidator.is_safe_redirect_url("//[email protected]/path", self.HOST)
+ is False
+ )
+
+ # -- backslash bypass --
+ def test_backslash_evil(self):
+ """\\evil.com treated as /evil.com by some browsers."""
+ assert (
+ URLValidator.is_safe_redirect_url("\\evil.com", self.HOST) is False
+ )
+
+ def test_double_backslash_evil(self):
+ """\\\\evil.com bypass."""
+ assert (
+ URLValidator.is_safe_redirect_url("\\\\evil.com", self.HOST)
+ is False
+ )
+
+ def test_backslash_forward_mix(self):
+ """\\/evil.com bypass."""
+ assert (
+ URLValidator.is_safe_redirect_url("\\/evil.com", self.HOST) is False
+ )
+
+ # -- path traversal --
+ def test_path_traversal_etc_passwd(self):
+ assert (
+ URLValidator.is_safe_redirect_url("/../../../etc/passwd", self.HOST)
+ is False
+ )
+
+ def test_relative_path_traversal(self):
+ assert URLValidator.is_safe_redirect_url("../admin", self.HOST) is False
+
+ def test_mid_path_traversal(self):
+ assert (
+ URLValidator.is_safe_redirect_url("/foo/../bar", self.HOST) is False
+ )
+
+ # -- URL-encoded bypass attempts --
+ def test_encoded_double_slash(self):
+ """%2f%2f should decode to // and be blocked."""
+ assert (
+ URLValidator.is_safe_redirect_url("%2f%2fevil.com", self.HOST)
+ is False
+ )
+
+ def test_encoded_backslash(self):
+ """%5c is backslash -- blocked after decoding."""
+ assert (
+ URLValidator.is_safe_redirect_url("%5cevil.com", self.HOST) is False
+ )
+
+ def test_encoded_path_traversal(self):
+ """%2e%2e is '..' -- blocked after decoding."""
+ assert (
+ URLValidator.is_safe_redirect_url("%2e%2e/admin", self.HOST)
+ is False
+ )
+
+ def test_encoded_crlf(self):
+ """%0d%0a is \\r\\n -- but literal \\r\\n check happens first."""
+ # The unquote will decode this, then backslash/protocol checks run.
+ # Even if CRLF check on raw string misses it, the decoded form
+ # should still fail at some check.
+ result = URLValidator.is_safe_redirect_url("%0d%0a/path", self.HOST)
+ # Implementation decodes first then checks -- might pass CRLF check
+ # on raw but path traversal or other checks might catch it. Either way,
+ # a safe implementation should block it. If it doesn't, this documents
+ # the behavior.
+ assert isinstance(result, bool)
+
+ # -- same host redirect (SAFE) --
+ def test_relative_path_safe(self):
+ assert (
+ URLValidator.is_safe_redirect_url("/dashboard", self.HOST) is True
+ )
+
+ def test_relative_path_with_query(self):
+ assert (
+ URLValidator.is_safe_redirect_url("/search?q=hello", self.HOST)
+ is True
+ )
+
+ def test_same_host_absolute_safe(self):
+ assert (
+ URLValidator.is_safe_redirect_url(
+ "http://example.com/page", self.HOST
+ )
+ is True
+ )
+
+ def test_same_host_https_absolute_safe(self):
+ host = "https://example.com/"
+ assert (
+ URLValidator.is_safe_redirect_url("https://example.com/page", host)
+ is True
+ )
+
+ def test_relative_nested_path(self):
+ assert URLValidator.is_safe_redirect_url("/a/b/c/d", self.HOST) is True
+
+ def test_relative_path_with_fragment(self):
+ assert (
+ URLValidator.is_safe_redirect_url("/page#section", self.HOST)
+ is True
+ )
+
+ # -- different host redirect (BLOCKED) --
+ def test_different_host_blocked(self):
+ assert (
+ URLValidator.is_safe_redirect_url(
+ "http://evil.com/steal", self.HOST
+ )
+ is False
+ )
+
+ def test_different_host_similar_name_blocked(self):
+ """example.com.evil.com is NOT the same as example.com."""
+ assert (
+ URLValidator.is_safe_redirect_url(
+ "http://example.com.evil.com/path", self.HOST
+ )
+ is False
+ )
+
+ def test_subdomain_of_host_blocked(self):
+ """sub.example.com is different netloc from example.com."""
+ assert (
+ URLValidator.is_safe_redirect_url(
+ "http://sub.example.com/path", self.HOST
+ )
+ is False
+ )
+
+ # -- edge cases for dotdot in non-path components --
+ def test_dotdot_in_query_param_not_blocked(self):
+ """Double dots in query string should NOT trigger path traversal."""
+ assert (
+ URLValidator.is_safe_redirect_url("/search?q=foo..bar", self.HOST)
+ is True
+ )
+
+ def test_dotdot_in_fragment_not_blocked(self):
+ """Double dots in fragment should NOT trigger path traversal."""
+ assert (
+ URLValidator.is_safe_redirect_url("/page#section..2", self.HOST)
+ is True
+ )
+
+ # -- protocol scheme injection --
+ def test_javascript_redirect_blocked(self):
+ """javascript: redirect is not http/https so blocked by scheme check."""
+ assert (
+ URLValidator.is_safe_redirect_url("javascript:alert(1)", self.HOST)
+ is False
+ )
+
+ def test_data_redirect_blocked(self):
+ assert (
+ URLValidator.is_safe_redirect_url(
+ "data:text/html,<h1>pwned</h1>", self.HOST
+ )
+ is False
+ )
+
+ # -- special characters in safe paths --
+ def test_path_with_spaces_encoded(self):
+ assert (
+ URLValidator.is_safe_redirect_url(
+ "/path%20with%20spaces", self.HOST
+ )
+ is True
+ )
+
+ def test_path_with_tilde(self):
+ assert (
+ URLValidator.is_safe_redirect_url("/~user/page", self.HOST) is True
+ )
+
+ def test_root_path(self):
+ assert URLValidator.is_safe_redirect_url("/", self.HOST) is True
+
+ # -- HTTPS host URL variations --
+ def test_https_host_with_http_relative(self):
+ """Relative path from HTTPS host stays on same host."""
+ host = "https://secure.example.com/"
+ assert URLValidator.is_safe_redirect_url("/login", host) is True
+
+ def test_host_with_port(self):
+ """Host URL with port -- redirect must match same host:port."""
+ host = "http://example.com:8080/"
+ assert URLValidator.is_safe_redirect_url("/dashboard", host) is True
+
+ def test_host_with_port_different_port_blocked(self):
+ """Redirect to different port on same hostname is blocked."""
+ host = "http://example.com:8080/"
+ assert (
+ URLValidator.is_safe_redirect_url(
+ "http://example.com:9090/path", host
+ )
+ is False
+ )
diff --git a/tests/storage/test_database_with_file_backup.py b/tests/storage/test_database_with_file_backup.py
new file mode 100644
index 0000000000..8f1001c8a3
--- /dev/null
+++ b/tests/storage/test_database_with_file_backup.py
@@ -0,0 +1,321 @@
+"""Comprehensive tests for DatabaseWithFileBackupStorage."""
+
+from unittest.mock import MagicMock, patch
+
+
+from local_deep_research.storage.database_with_file_backup import (
+ DatabaseWithFileBackupStorage,
+)
+
+MODULE = "local_deep_research.storage.database_with_file_backup"
+
+
+# ---------------------------------------------------------------------------
+# __init__
+# ---------------------------------------------------------------------------
+
+
+class TestInit:
+ """Tests for __init__."""
+
+ @patch(f"{MODULE}.DatabaseReportStorage")
+ def test_without_file_storage_file_storage_is_none(
+ self, mock_db_cls, mock_session
+ ):
+ """file_storage should be None when enable_file_storage is False."""
+ storage = DatabaseWithFileBackupStorage(mock_session)
+
+ assert storage.file_storage is None
+ assert storage.enable_file_storage is False
+
+ @patch(f"{MODULE}.FileReportStorage")
+ @patch(f"{MODULE}.DatabaseReportStorage")
+ def test_with_file_storage_creates_file_report_storage(
+ self, mock_db_cls, mock_file_cls, mock_session
+ ):
+ """file_storage should be a FileReportStorage when enabled."""
+ storage = DatabaseWithFileBackupStorage(
+ mock_session, enable_file_storage=True
+ )
+
+ assert storage.enable_file_storage is True
+ mock_file_cls.assert_called_once_with()
+ assert storage.file_storage is mock_file_cls.return_value
+
+ @patch(f"{MODULE}.DatabaseReportStorage")
+ def test_db_storage_created_with_session(self, mock_db_cls, mock_session):
+ """db_storage should be created by passing session to DatabaseReportStorage."""
+ storage = DatabaseWithFileBackupStorage(mock_session)
+
+ mock_db_cls.assert_called_once_with(mock_session)
+ assert storage.db_storage is mock_db_cls.return_value
+
+
+# ---------------------------------------------------------------------------
+# save_report
+# ---------------------------------------------------------------------------
+
+
+class TestSaveReport:
+ """Tests for save_report."""
+
+ def test_db_success_no_file_storage_returns_true(
+ self, mock_session, sample_report_content
+ ):
+ """Should return True and only call db_storage when file storage disabled."""
+ storage = DatabaseWithFileBackupStorage(mock_session)
+ storage.db_storage = MagicMock()
+ storage.db_storage.save_report.return_value = True
+
+ result = storage.save_report("r1", sample_report_content)
+
+ assert result is True
+ storage.db_storage.save_report.assert_called_once()
+ # file_storage is None, nothing else should happen
+
+ def test_db_fails_returns_false_immediately(
+ self, mock_session, sample_report_content
+ ):
+ """Should return False immediately when db save fails; no file attempt."""
+ storage = DatabaseWithFileBackupStorage(
+ mock_session, enable_file_storage=True
+ )
+ storage.db_storage = MagicMock()
+ storage.db_storage.save_report.return_value = False
+ storage.file_storage = MagicMock()
+
+ result = storage.save_report("r1", sample_report_content)
+
+ assert result is False
+ storage.file_storage.save_report.assert_not_called()
+
+ def test_db_success_file_success_returns_true(
+ self, mock_session, sample_report_content
+ ):
+ """Should return True when both db and file saves succeed."""
+ storage = DatabaseWithFileBackupStorage(
+ mock_session, enable_file_storage=True
+ )
+ storage.db_storage = MagicMock()
+ storage.db_storage.save_report.return_value = True
+ storage.file_storage = MagicMock()
+ storage.file_storage.save_report.return_value = True
+
+ result = storage.save_report("r1", sample_report_content)
+
+ assert result is True
+ storage.file_storage.save_report.assert_called_once()
+
+ def test_db_success_file_returns_false_still_returns_true(
+ self, mock_session, sample_report_content
+ ):
+ """Should return True even when file save returns False (db succeeded)."""
+ storage = DatabaseWithFileBackupStorage(
+ mock_session, enable_file_storage=True
+ )
+ storage.db_storage = MagicMock()
+ storage.db_storage.save_report.return_value = True
+ storage.file_storage = MagicMock()
+ storage.file_storage.save_report.return_value = False
+
+ result = storage.save_report("r1", sample_report_content)
+
+ assert result is True
+
+ def test_db_success_file_raises_exception_still_returns_true(
+ self, mock_session, sample_report_content
+ ):
+ """Should return True even when file save raises an exception."""
+ storage = DatabaseWithFileBackupStorage(
+ mock_session, enable_file_storage=True
+ )
+ storage.db_storage = MagicMock()
+ storage.db_storage.save_report.return_value = True
+ storage.file_storage = MagicMock()
+ storage.file_storage.save_report.side_effect = OSError("disk full")
+
+ result = storage.save_report("r1", sample_report_content)
+
+ assert result is True
+
+ def test_passes_all_arguments_to_db_storage(
+ self, mock_session, sample_report_content, sample_metadata
+ ):
+ """Should forward research_id, content, metadata, username to db_storage."""
+ storage = DatabaseWithFileBackupStorage(mock_session)
+ storage.db_storage = MagicMock()
+ storage.db_storage.save_report.return_value = True
+
+ storage.save_report(
+ "r1", sample_report_content, sample_metadata, "alice"
+ )
+
+ storage.db_storage.save_report.assert_called_once_with(
+ "r1", sample_report_content, sample_metadata, "alice"
+ )
+
+
+# ---------------------------------------------------------------------------
+# get_report
+# ---------------------------------------------------------------------------
+
+
+class TestGetReport:
+ """Tests for get_report."""
+
+ def test_delegates_to_db_storage(self, mock_session, sample_report_content):
+ """Should delegate to db_storage.get_report and return its result."""
+ storage = DatabaseWithFileBackupStorage(mock_session)
+ storage.db_storage = MagicMock()
+ storage.db_storage.get_report.return_value = sample_report_content
+
+ result = storage.get_report("r1", username="bob")
+
+ assert result == sample_report_content
+ storage.db_storage.get_report.assert_called_once_with("r1", "bob")
+
+ def test_never_calls_file_storage_even_when_enabled(
+ self, mock_session, sample_report_content
+ ):
+ """Should never read from file storage, even when it is enabled."""
+ storage = DatabaseWithFileBackupStorage(
+ mock_session, enable_file_storage=True
+ )
+ storage.db_storage = MagicMock()
+ storage.db_storage.get_report.return_value = sample_report_content
+ storage.file_storage = MagicMock()
+
+ storage.get_report("r1")
+
+ storage.file_storage.get_report.assert_not_called()
+
+
+# ---------------------------------------------------------------------------
+# delete_report
+# ---------------------------------------------------------------------------
+
+
+class TestDeleteReport:
+ """Tests for delete_report."""
+
+ def test_db_success_no_file_storage_returns_true(self, mock_session):
+ """Should return True when db delete succeeds and no file storage."""
+ storage = DatabaseWithFileBackupStorage(mock_session)
+ storage.db_storage = MagicMock()
+ storage.db_storage.delete_report.return_value = True
+
+ result = storage.delete_report("r1")
+
+ assert result is True
+ storage.db_storage.delete_report.assert_called_once()
+
+ def test_db_success_file_storage_calls_file_delete(self, mock_session):
+ """Should call file_storage.delete_report when db delete succeeds."""
+ storage = DatabaseWithFileBackupStorage(
+ mock_session, enable_file_storage=True
+ )
+ storage.db_storage = MagicMock()
+ storage.db_storage.delete_report.return_value = True
+ storage.file_storage = MagicMock()
+
+ storage.delete_report("r1", username="carol")
+
+ storage.file_storage.delete_report.assert_called_once_with(
+ "r1", "carol"
+ )
+
+ def test_db_fails_returns_false_file_not_called(self, mock_session):
+ """Should return False and skip file delete when db delete fails."""
+ storage = DatabaseWithFileBackupStorage(
+ mock_session, enable_file_storage=True
+ )
+ storage.db_storage = MagicMock()
+ storage.db_storage.delete_report.return_value = False
+ storage.file_storage = MagicMock()
+
+ result = storage.delete_report("r1")
+
+ assert result is False
+ storage.file_storage.delete_report.assert_not_called()
+
+ def test_db_success_file_raises_exception_still_returns_true(
+ self, mock_session
+ ):
+ """Should return True even when file delete raises an exception."""
+ storage = DatabaseWithFileBackupStorage(
+ mock_session, enable_file_storage=True
+ )
+ storage.db_storage = MagicMock()
+ storage.db_storage.delete_report.return_value = True
+ storage.file_storage = MagicMock()
+ storage.file_storage.delete_report.side_effect = OSError(
+ "permission denied"
+ )
+
+ result = storage.delete_report("r1")
+
+ assert result is True
+
+
+# ---------------------------------------------------------------------------
+# list_reports
+# ---------------------------------------------------------------------------
+
+
+class TestListReports:
+ """Tests for list_reports."""
+
+ def test_delegates_to_db_storage(self, mock_session):
+ """Should delegate to db_storage.list_reports and return its result."""
+ storage = DatabaseWithFileBackupStorage(mock_session)
+ storage.db_storage = MagicMock()
+ expected = [{"id": "r1"}, {"id": "r2"}]
+ storage.db_storage.list_reports.return_value = expected
+
+ result = storage.list_reports(username="dave")
+
+ assert result == expected
+ storage.db_storage.list_reports.assert_called_once_with("dave")
+
+
+# ---------------------------------------------------------------------------
+# get_report_with_metadata
+# ---------------------------------------------------------------------------
+
+
+class TestGetReportWithMetadata:
+ """Tests for get_report_with_metadata."""
+
+ def test_delegates_to_db_storage(self, mock_session):
+ """Should delegate to db_storage.get_report_with_metadata."""
+ storage = DatabaseWithFileBackupStorage(mock_session)
+ storage.db_storage = MagicMock()
+ expected = {"content": "report text", "metadata": {"key": "value"}}
+ storage.db_storage.get_report_with_metadata.return_value = expected
+
+ result = storage.get_report_with_metadata("r1", username="eve")
+
+ assert result == expected
+ storage.db_storage.get_report_with_metadata.assert_called_once_with(
+ "r1", "eve"
+ )
+
+
+# ---------------------------------------------------------------------------
+# report_exists
+# ---------------------------------------------------------------------------
+
+
+class TestReportExists:
+ """Tests for report_exists."""
+
+ def test_delegates_to_db_storage(self, mock_session):
+ """Should delegate to db_storage.report_exists and return its result."""
+ storage = DatabaseWithFileBackupStorage(mock_session)
+ storage.db_storage = MagicMock()
+ storage.db_storage.report_exists.return_value = True
+
+ result = storage.report_exists("r1", username="frank")
+
+ assert result is True
+ storage.db_storage.report_exists.assert_called_once_with("r1", "frank")
diff --git a/tests/utilities/test_thread_context_extended.py b/tests/utilities/test_thread_context_extended.py
new file mode 100644
index 0000000000..8244e9008f
--- /dev/null
+++ b/tests/utilities/test_thread_context_extended.py
@@ -0,0 +1,435 @@
+"""Extended tests for thread_context module.
+
+Focuses on thread-local context propagation correctness,
+thread isolation guarantees, and shallow-copy edge cases.
+"""
+
+import threading
+from unittest.mock import patch
+
+import pytest
+
+from local_deep_research.utilities.thread_context import (
+ _g_thread_data,
+ clear_search_context,
+ get_search_context,
+ preserve_research_context,
+ search_context,
+ set_search_context,
+)
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _cleanup():
+ """Remove any leftover context on the current thread."""
+ if hasattr(_g_thread_data, "context"):
+ del _g_thread_data.context
+
+
+# ---------------------------------------------------------------------------
+# set_search_context
+# ---------------------------------------------------------------------------
+
+
+class TestSetSearchContextExtended:
+ """Extended tests for set_search_context."""
+
+ def setup_method(self):
+ _cleanup()
+
+ def teardown_method(self):
+ _cleanup()
+
+ def test_sets_context_in_thread_local_storage(self):
+ """Setting context stores it on the thread-local object."""
+ ctx = {"research_id": "abc", "query": "test query"}
+ set_search_context(ctx)
+ stored = getattr(_g_thread_data, "context", None)
+ assert stored is not None
+ assert stored == {"research_id": "abc", "query": "test query"}
+
+ def test_copies_context_so_original_mutation_has_no_effect(self):
+ """set_search_context copies the dict -- mutating the original after
+ the call must not change the stored value."""
+ original = {"key": "original_value"}
+ set_search_context(original)
+
+ # Mutate the original
+ original["key"] = "mutated"
+ original["extra"] = "added"
+
+ stored = _g_thread_data.context
+ assert stored["key"] == "original_value"
+ assert "extra" not in stored
+
+ def test_overwrites_existing_context_and_logs_debug(self):
+ """When context already exists the old value is replaced and a
+ debug message is emitted."""
+ set_search_context({"round": 1})
+
+ with patch(
+ "local_deep_research.utilities.thread_context.logger"
+ ) as mock_logger:
+ set_search_context({"round": 2})
+ mock_logger.debug.assert_called_once()
+ assert (
+ "overwritten" in mock_logger.debug.call_args[0][0].lower()
+ or "already set" in mock_logger.debug.call_args[0][0].lower()
+ )
+
+ assert _g_thread_data.context == {"round": 2}
+
+
+# ---------------------------------------------------------------------------
+# clear_search_context
+# ---------------------------------------------------------------------------
+
+
+class TestClearSearchContextExtended:
+ """Extended tests for clear_search_context."""
+
+ def setup_method(self):
+ _cleanup()
+
+ def teardown_method(self):
+ _cleanup()
+
+ def test_removes_context_from_thread_local_storage(self):
+ """After clearing, hasattr reports no context attribute."""
+ set_search_context({"id": "will-be-cleared"})
+ assert hasattr(_g_thread_data, "context")
+
+ clear_search_context()
+ assert not hasattr(_g_thread_data, "context")
+
+ def test_noop_when_no_context_set(self):
+ """Calling clear when there is nothing stored must not raise."""
+ assert not hasattr(_g_thread_data, "context")
+ clear_search_context() # should not raise
+ assert not hasattr(_g_thread_data, "context")
+
+
+# ---------------------------------------------------------------------------
+# get_search_context
+# ---------------------------------------------------------------------------
+
+
+class TestGetSearchContextExtended:
+ """Extended tests for get_search_context."""
+
+ def setup_method(self):
+ _cleanup()
+
+ def teardown_method(self):
+ _cleanup()
+
+ def test_returns_none_when_no_context_set(self):
+ """Without prior set_search_context the return value is None."""
+ assert get_search_context() is None
+
+ def test_returns_copy_so_mutation_does_not_affect_stored(self):
+ """Modifying the returned dict must not alter the stored context."""
+ set_search_context({"research_id": "immutable-check"})
+
+ returned = get_search_context()
+ returned["research_id"] = "mutated"
+ returned["injected"] = True
+
+ # The stored context must remain untouched
+ assert _g_thread_data.context["research_id"] == "immutable-check"
+ assert "injected" not in _g_thread_data.context
+
+ def test_returns_correct_context_values(self):
+ """The returned dict contains exactly the same key-value pairs that
+ were originally stored."""
+ ctx = {
+ "research_id": "r-42",
+ "user": "alice",
+ "max_depth": 3,
+ "tags": ["science", "ai"],
+ }
+ set_search_context(ctx)
+ result = get_search_context()
+ assert result == ctx
+
+
+# ---------------------------------------------------------------------------
+# search_context (context manager)
+# ---------------------------------------------------------------------------
+
+
+class TestSearchContextManagerExtended:
+ """Extended tests for the search_context context manager."""
+
+ def setup_method(self):
+ _cleanup()
+
+ def teardown_method(self):
+ _cleanup()
+
+ def test_sets_context_within_the_block(self):
+ """Inside the with-block the context must be available."""
+ with search_context({"research_id": "inside-check"}):
+ ctx = get_search_context()
+ assert ctx is not None
+ assert ctx["research_id"] == "inside-check"
+
+ def test_clears_context_after_normal_exit(self):
+ """After the with-block exits normally the context is cleared."""
+ with search_context({"research_id": "will-clear"}):
+ pass # normal exit
+ assert get_search_context() is None
+
+ def test_clears_context_when_exception_occurs(self):
+ """Context is cleared even when an exception propagates out of the
+ with-block."""
+ with pytest.raises(RuntimeError, match="boom"):
+ with search_context({"research_id": "exception-path"}):
+ assert get_search_context() is not None
+ raise RuntimeError("boom")
+
+ assert get_search_context() is None
+
+ def test_re_raises_exception_from_inside_block(self):
+ """The context manager does not swallow exceptions."""
+ with pytest.raises(TypeError, match="bad type"):
+ with search_context({"research_id": "re-raise"}):
+ raise TypeError("bad type")
+
+
+# ---------------------------------------------------------------------------
+# preserve_research_context (decorator)
+# ---------------------------------------------------------------------------
+
+
+class TestPreserveResearchContextExtended:
+ """Extended tests for the preserve_research_context decorator."""
+
+ def setup_method(self):
+ _cleanup()
+
+ def teardown_method(self):
+ _cleanup()
+
+ def test_no_context_function_runs_normally(self):
+ """When no context exists at decoration time the wrapped function
+ executes without setting or clearing any context."""
+ # Ensure no context is set
+ assert get_search_context() is None
+
+ @preserve_research_context
+ def plain_task(x, y):
+ """Add two numbers."""
+ # Context should remain unset inside the function
+ assert get_search_context() is None
+ return x + y
+
+ result = plain_task(3, 7)
+ assert result == 10
+ # Still no context after the call
+ assert get_search_context() is None
+
+ def test_with_context_sets_before_and_clears_after(self):
+ """When context is set at decoration time the decorator sets it
+ before the function body and clears it in the finally block."""
+ set_search_context({"research_id": "decorator-lifecycle"})
+
+ observed_inside = []
+
+ @preserve_research_context
+ def worker():
+ observed_inside.append(get_search_context())
+
+ # Clear the main-thread context so we can verify the decorator
+ # independently restores it inside the wrapper.
+ clear_search_context()
+
+ worker()
+
+ # During execution the context was set
+ assert observed_inside[0] is not None
+ assert observed_inside[0]["research_id"] == "decorator-lifecycle"
+
+ # After execution the context is cleared
+ assert get_search_context() is None
+
+ def test_preserves_function_name_and_docstring(self):
+ """functools.wraps should keep __name__ and __doc__ intact."""
+ set_search_context({"research_id": "wraps-test"})
+
+ @preserve_research_context
+ def documented_function(a, b):
+ """This is my docstring."""
+ return a * b
+
+ assert documented_function.__name__ == "documented_function"
+ assert documented_function.__doc__ == "This is my docstring."
+
+ def test_clears_context_when_decorated_function_raises(self):
+ """If the wrapped function raises, context is still cleaned up via
+ the finally clause."""
+ set_search_context({"research_id": "error-cleanup"})
+
+ @preserve_research_context
+ def failing():
+ raise ValueError("intentional failure")
+
+ clear_search_context()
+
+ with pytest.raises(ValueError, match="intentional failure"):
+ failing()
+
+ assert get_search_context() is None
+
+
+# ---------------------------------------------------------------------------
+# Thread isolation
+# ---------------------------------------------------------------------------
+
+
+class TestThreadIsolationExtended:
+ """Thread isolation guarantees for thread-local storage."""
+
+ def setup_method(self):
+ _cleanup()
+
+ def teardown_method(self):
+ _cleanup()
+
+ def test_context_set_in_one_thread_not_visible_in_another(self):
+ """A context set on the main thread must not be visible in a freshly
+ spawned thread."""
+ set_search_context({"owner": "main-thread"})
+
+ child_result = [None]
+ error_holder = [None]
+
+ def child():
+ try:
+ child_result[0] = get_search_context()
+ except Exception as exc:
+ error_holder[0] = exc
+
+ t = threading.Thread(target=child)
+ t.start()
+ t.join()
+
+ assert error_holder[0] is None, (
+ f"Child thread raised: {error_holder[0]}"
+ )
+ assert child_result[0] is None, (
+ "Child thread should not see main thread context"
+ )
+
+ def test_clearing_in_one_thread_does_not_affect_another(self):
+ """Clearing context on the main thread must not affect a context
+ set independently in a child thread."""
+ barrier = threading.Barrier(2, timeout=5)
+ child_context_after_main_clear = [None]
+ error_holder = [None]
+
+ def child():
+ try:
+ set_search_context({"owner": "child-thread"})
+ # Signal that child has set its context
+ barrier.wait()
+ # Wait for main thread to clear its context
+ barrier.wait()
+ child_context_after_main_clear[0] = get_search_context()
+ except Exception as exc:
+ error_holder[0] = exc
+
+ set_search_context({"owner": "main-thread"})
+ t = threading.Thread(target=child)
+ t.start()
+
+ # Wait until child has set its context
+ barrier.wait()
+ # Main clears its own context
+ clear_search_context()
+ # Signal child to read its context
+ barrier.wait()
+
+ t.join()
+
+ assert error_holder[0] is None, (
+ f"Child thread raised: {error_holder[0]}"
+ )
+ assert child_context_after_main_clear[0] is not None
+ assert child_context_after_main_clear[0]["owner"] == "child-thread"
+
+ def test_search_context_manager_isolates_across_threads(self):
+ """Using the search_context context manager in two threads
+ concurrently must not cause cross-thread leakage."""
+ barrier = threading.Barrier(2, timeout=5)
+ results = {}
+ errors = []
+
+ def worker(name, ctx_value):
+ try:
+ with search_context({"worker": ctx_value}):
+ # Synchronise so both threads are inside their
+ # context managers at the same time.
+ barrier.wait()
+ observed = get_search_context()
+ results[name] = observed["worker"] if observed else None
+ except Exception as exc:
+ errors.append(exc)
+
+ t1 = threading.Thread(target=worker, args=("t1", "value-from-t1"))
+ t2 = threading.Thread(target=worker, args=("t2", "value-from-t2"))
+
+ t1.start()
+ t2.start()
+ t1.join()
+ t2.join()
+
+ assert not errors, f"Threads raised errors: {errors}"
+ assert results["t1"] == "value-from-t1"
+ assert results["t2"] == "value-from-t2"
+
+
+# ---------------------------------------------------------------------------
+# Edge cases
+# ---------------------------------------------------------------------------
+
+
+class TestEdgeCasesExtended:
+ """Edge-case scenarios for thread_context."""
+
+ def setup_method(self):
+ _cleanup()
+
+ def teardown_method(self):
+ _cleanup()
+
+ def test_empty_dict_context_is_valid(self):
+ """An empty dict is a legitimate context -- it should be stored and
+ retrieved without being confused with None."""
+ set_search_context({})
+ result = get_search_context()
+ assert result is not None
+ assert result == {}
+
+ def test_shallow_copy_semantics_for_nested_dicts(self):
+ """set_search_context and get_search_context use dict.copy() which is
+ a shallow copy. Nested mutable objects are shared references.
+
+ This test documents the expected (but potentially surprising)
+ behaviour: mutating a nested dict through a retrieved copy *does*
+ affect the stored context because dict.copy() is shallow."""
+ nested = {"inner_key": "original"}
+ set_search_context({"nested": nested})
+
+ retrieved = get_search_context()
+ # Top-level key mutation does NOT leak back
+ retrieved["top_new"] = "added"
+ assert "top_new" not in _g_thread_data.context
+
+ # Nested mutation DOES leak back (shallow copy)
+ retrieved["nested"]["inner_key"] = "mutated"
+ assert _g_thread_data.context["nested"]["inner_key"] == "mutated"
diff --git a/tests/web/auth/test_middleware_optimizer.py b/tests/web/auth/test_middleware_optimizer.py
index d338c51813..f3c3ea91ab 100644
--- a/tests/web/auth/test_middleware_optimizer.py
+++ b/tests/web/auth/test_middleware_optimizer.py
@@ -2,7 +2,7 @@
Tests for web/auth/middleware_optimizer.py
Tests cover:
-- should_skip_database_middleware - path-based skip logic
+- should_skip_database_middleware - path-based and method-based skip logic
- should_skip_queue_checks - method/path skip logic
- should_skip_session_cleanup - probabilistic skip logic
"""
@@ -11,375 +11,275 @@ import pytest
from flask import Flask
from unittest.mock import patch
+from local_deep_research.web.auth.middleware_optimizer import (
+ should_skip_database_middleware,
+ should_skip_queue_checks,
+ should_skip_session_cleanup,
+)
+
@pytest.fixture
def app():
- """Create a Flask test app."""
+ """Create a minimal Flask test app."""
app = Flask(__name__)
app.config["TESTING"] = True
return app
+# ===================================================================
+# should_skip_database_middleware
+# ===================================================================
class TestShouldSkipDatabaseMiddleware:
"""Tests for should_skip_database_middleware function."""
- def test_skip_static_files(self, app):
- """Test that static file paths are skipped."""
- from local_deep_research.web.auth.middleware_optimizer import (
- should_skip_database_middleware,
- )
+ # -- static file paths ------------------------------------------------
+ def test_skip_static_js(self, app):
+ """Should skip static JS file paths."""
with app.test_request_context("/static/js/app.js", method="GET"):
- result = should_skip_database_middleware()
- assert result is True
+ assert should_skip_database_middleware() is True
def test_skip_static_css(self, app):
- """Test that static CSS files are skipped."""
- from local_deep_research.web.auth.middleware_optimizer import (
- should_skip_database_middleware,
- )
-
+ """Should skip static CSS file paths."""
with app.test_request_context("/static/css/style.css", method="GET"):
- result = should_skip_database_middleware()
- assert result is True
+ assert should_skip_database_middleware() is True
def test_skip_static_images(self, app):
- """Test that static image files are skipped."""
- from local_deep_research.web.auth.middleware_optimizer import (
- should_skip_database_middleware,
- )
-
+ """Should skip static image file paths."""
with app.test_request_context("/static/images/logo.png", method="GET"):
- result = should_skip_database_middleware()
- assert result is True
+ assert should_skip_database_middleware() is True
- def test_skip_favicon(self, app):
- """Test that favicon.ico is skipped."""
- from local_deep_research.web.auth.middleware_optimizer import (
- should_skip_database_middleware,
- )
+ def test_skip_static_nested(self, app):
+ """Should skip deeply nested static paths."""
+ with app.test_request_context(
+ "/static/assets/vendor/lib.min.js", method="GET"
+ ):
+ assert should_skip_database_middleware() is True
+
+ # -- well-known files -------------------------------------------------
+ def test_skip_favicon(self, app):
+ """Should skip /favicon.ico."""
with app.test_request_context("/favicon.ico", method="GET"):
- result = should_skip_database_middleware()
- assert result is True
+ assert should_skip_database_middleware() is True
def test_skip_robots_txt(self, app):
- """Test that robots.txt is skipped."""
- from local_deep_research.web.auth.middleware_optimizer import (
- should_skip_database_middleware,
- )
-
+ """Should skip /robots.txt."""
with app.test_request_context("/robots.txt", method="GET"):
- result = should_skip_database_middleware()
- assert result is True
-
- def test_skip_health_endpoint(self, app):
- """Test that health endpoint is skipped."""
- from local_deep_research.web.auth.middleware_optimizer import (
- should_skip_database_middleware,
- )
+ assert should_skip_database_middleware() is True
+ def test_skip_health(self, app):
+ """Should skip /health endpoint."""
with app.test_request_context("/health", method="GET"):
- result = should_skip_database_middleware()
- assert result is True
+ assert should_skip_database_middleware() is True
- def test_skip_socket_io_polling(self, app):
- """Test that Socket.IO polling paths are skipped."""
- from local_deep_research.web.auth.middleware_optimizer import (
- should_skip_database_middleware,
- )
+ # -- Socket.IO paths --------------------------------------------------
+ def test_skip_socket_io_polling(self, app):
+ """Should skip Socket.IO polling paths."""
with app.test_request_context(
"/socket.io/?EIO=4&transport=polling", method="GET"
):
- result = should_skip_database_middleware()
- assert result is True
+ assert should_skip_database_middleware() is True
def test_skip_socket_io_websocket(self, app):
- """Test that Socket.IO websocket paths are skipped."""
- from local_deep_research.web.auth.middleware_optimizer import (
- should_skip_database_middleware,
- )
-
+ """Should skip Socket.IO websocket paths."""
with app.test_request_context(
"/socket.io/?EIO=4&transport=websocket", method="GET"
):
- result = should_skip_database_middleware()
- assert result is True
+ assert should_skip_database_middleware() is True
- def test_skip_auth_login(self, app):
- """Test that auth/login path is skipped."""
- from local_deep_research.web.auth.middleware_optimizer import (
- should_skip_database_middleware,
- )
+ # -- auth routes ------------------------------------------------------
+ def test_skip_auth_login(self, app):
+ """Should skip /auth/login."""
with app.test_request_context("/auth/login", method="POST"):
- result = should_skip_database_middleware()
- assert result is True
+ assert should_skip_database_middleware() is True
def test_skip_auth_register(self, app):
- """Test that auth/register path is skipped."""
- from local_deep_research.web.auth.middleware_optimizer import (
- should_skip_database_middleware,
- )
-
+ """Should skip /auth/register."""
with app.test_request_context("/auth/register", method="POST"):
- result = should_skip_database_middleware()
- assert result is True
+ assert should_skip_database_middleware() is True
def test_skip_auth_logout(self, app):
- """Test that auth/logout path is skipped."""
- from local_deep_research.web.auth.middleware_optimizer import (
- should_skip_database_middleware,
- )
-
+ """Should skip /auth/logout."""
with app.test_request_context("/auth/logout", method="POST"):
- result = should_skip_database_middleware()
- assert result is True
+ assert should_skip_database_middleware() is True
- def test_skip_options_preflight(self, app):
- """Test that OPTIONS preflight requests are skipped."""
- from local_deep_research.web.auth.middleware_optimizer import (
- should_skip_database_middleware,
- )
+ # -- OPTIONS preflight ------------------------------------------------
+ def test_skip_options_preflight(self, app):
+ """Should skip OPTIONS requests regardless of path."""
with app.test_request_context("/api/research", method="OPTIONS"):
- result = should_skip_database_middleware()
- assert result is True
+ assert should_skip_database_middleware() is True
- def test_no_skip_api_endpoint(self, app):
- """Test that API endpoints are not skipped."""
- from local_deep_research.web.auth.middleware_optimizer import (
- should_skip_database_middleware,
- )
+ def test_skip_options_on_any_path(self, app):
+ """Should skip OPTIONS on arbitrary paths."""
+ with app.test_request_context("/settings", method="OPTIONS"):
+ assert should_skip_database_middleware() is True
+ # -- paths that should NOT be skipped ---------------------------------
+
+ def test_no_skip_api_research(self, app):
+ """Should NOT skip /api/research."""
with app.test_request_context("/api/research", method="GET"):
- result = should_skip_database_middleware()
- assert result is False
+ assert should_skip_database_middleware() is False
def test_no_skip_api_post(self, app):
- """Test that API POST requests are not skipped."""
- from local_deep_research.web.auth.middleware_optimizer import (
- should_skip_database_middleware,
- )
-
+ """Should NOT skip POST to /api/research."""
with app.test_request_context("/api/research", method="POST"):
- result = should_skip_database_middleware()
- assert result is False
+ assert should_skip_database_middleware() is False
- def test_no_skip_root_path(self, app):
- """Test that root path is not skipped."""
- from local_deep_research.web.auth.middleware_optimizer import (
- should_skip_database_middleware,
- )
+ def test_no_skip_settings(self, app):
+ """Should NOT skip /settings."""
+ with app.test_request_context("/settings", method="GET"):
+ assert should_skip_database_middleware() is False
+ def test_no_skip_root(self, app):
+ """Should NOT skip root path /."""
with app.test_request_context("/", method="GET"):
- result = should_skip_database_middleware()
- assert result is False
+ assert should_skip_database_middleware() is False
def test_no_skip_dashboard(self, app):
- """Test that dashboard path is not skipped."""
- from local_deep_research.web.auth.middleware_optimizer import (
- should_skip_database_middleware,
- )
-
+ """Should NOT skip /dashboard."""
with app.test_request_context("/dashboard", method="GET"):
- result = should_skip_database_middleware()
- assert result is False
+ assert should_skip_database_middleware() is False
+# ===================================================================
+# should_skip_queue_checks
+# ===================================================================
class TestShouldSkipQueueChecks:
"""Tests for should_skip_queue_checks function."""
- def test_skip_get_requests(self, app):
- """Test that GET requests are skipped."""
- from local_deep_research.web.auth.middleware_optimizer import (
- should_skip_queue_checks,
- )
+ # -- GET requests always skipped --------------------------------------
+ def test_skip_get_requests(self, app):
+ """GET requests should be skipped (they don't create new work)."""
with app.test_request_context("/api/research", method="GET"):
- result = should_skip_queue_checks()
- assert result is True
-
- def test_no_skip_post_requests(self, app):
- """Test that POST requests to API are not skipped."""
- from local_deep_research.web.auth.middleware_optimizer import (
- should_skip_queue_checks,
- )
+ assert should_skip_queue_checks() is True
- with app.test_request_context("/api/research", method="POST"):
- result = should_skip_queue_checks()
- assert result is False
-
- def test_no_skip_put_requests(self, app):
- """Test that PUT requests to API are not skipped."""
- from local_deep_research.web.auth.middleware_optimizer import (
- should_skip_queue_checks,
- )
-
- with app.test_request_context("/api/research/123", method="PUT"):
- result = should_skip_queue_checks()
- assert result is False
-
- def test_no_skip_delete_requests(self, app):
- """Test that DELETE requests to API are not skipped."""
- from local_deep_research.web.auth.middleware_optimizer import (
- should_skip_queue_checks,
- )
+ def test_skip_get_on_any_path(self, app):
+ """GET requests should be skipped regardless of path."""
+ with app.test_request_context("/settings", method="GET"):
+ assert should_skip_queue_checks() is True
- with app.test_request_context("/api/research/123", method="DELETE"):
- result = should_skip_queue_checks()
- assert result is False
+ # -- inherits database middleware skip paths --------------------------
def test_skip_static_files_post(self, app):
- """Test that static files are skipped even with POST."""
- from local_deep_research.web.auth.middleware_optimizer import (
- should_skip_queue_checks,
- )
-
+ """Static files are skipped even for POST."""
with app.test_request_context("/static/js/app.js", method="POST"):
- result = should_skip_queue_checks()
- assert result is True
+ assert should_skip_queue_checks() is True
def test_skip_health_post(self, app):
- """Test that health endpoint is skipped even with POST."""
- from local_deep_research.web.auth.middleware_optimizer import (
- should_skip_queue_checks,
- )
-
+ """Health endpoint is skipped even for POST."""
with app.test_request_context("/health", method="POST"):
- result = should_skip_queue_checks()
- assert result is True
+ assert should_skip_queue_checks() is True
def test_skip_socket_io_post(self, app):
- """Test that socket.io is skipped even with POST."""
- from local_deep_research.web.auth.middleware_optimizer import (
- should_skip_queue_checks,
- )
-
+ """Socket.IO paths are skipped even for POST."""
with app.test_request_context(
"/socket.io/?EIO=4&transport=polling", method="POST"
):
- result = should_skip_queue_checks()
- assert result is True
+ assert should_skip_queue_checks() is True
def test_skip_options_always(self, app):
- """Test that OPTIONS requests are always skipped."""
- from local_deep_research.web.auth.middleware_optimizer import (
- should_skip_queue_checks,
- )
-
+ """OPTIONS requests are always skipped."""
with app.test_request_context("/api/research", method="OPTIONS"):
- result = should_skip_queue_checks()
- assert result is True
+ assert should_skip_queue_checks() is True
+
+ # -- POST to API should NOT be skipped --------------------------------
+ def test_no_skip_post_api_research(self, app):
+ """POST to /api/research should NOT be skipped."""
+ with app.test_request_context("/api/research", method="POST"):
+ assert should_skip_queue_checks() is False
+
+ def test_no_skip_put_requests(self, app):
+ """PUT requests to non-skip paths should NOT be skipped."""
+ with app.test_request_context("/api/research/123", method="PUT"):
+ assert should_skip_queue_checks() is False
+ def test_no_skip_delete_requests(self, app):
+ """DELETE requests to non-skip paths should NOT be skipped."""
+ with app.test_request_context("/api/research/123", method="DELETE"):
+ assert should_skip_queue_checks() is False
+
+
+# ===================================================================
+# should_skip_session_cleanup
+# ===================================================================
class TestShouldSkipSessionCleanup:
"""Tests for should_skip_session_cleanup function."""
- def test_skip_static_files(self, app):
- """Test that static files always skip session cleanup."""
- from local_deep_research.web.auth.middleware_optimizer import (
- should_skip_session_cleanup,
- )
+ # -- probabilistic: random > 1 always skips (99%) --------------------
- with app.test_request_context("/static/js/app.js", method="GET"):
- with patch("random.randint", return_value=1): # Would normally run
- result = should_skip_session_cleanup()
- # Static files always skip, regardless of random
- assert result is True
+ def test_skip_when_random_returns_2(self, app):
+ """When random returns > 1, should always skip."""
+ with app.test_request_context("/api/research", method="GET"):
+ with patch("random.randint", return_value=2):
+ assert should_skip_session_cleanup() is True
- def test_skip_health_endpoint(self, app):
- """Test that health endpoint always skips session cleanup."""
- from local_deep_research.web.auth.middleware_optimizer import (
- should_skip_session_cleanup,
- )
+ def test_skip_when_random_returns_50(self, app):
+ """When random returns 50, should skip."""
+ with app.test_request_context("/api/research", method="GET"):
+ with patch("random.randint", return_value=50):
+ assert should_skip_session_cleanup() is True
- with app.test_request_context("/health", method="GET"):
- with patch("random.randint", return_value=1): # Would normally run
- result = should_skip_session_cleanup()
- assert result is True
+ def test_skip_when_random_returns_100(self, app):
+ """When random returns 100, should skip."""
+ with app.test_request_context("/api/research", method="GET"):
+ with patch("random.randint", return_value=100):
+ assert should_skip_session_cleanup() is True
- def test_skip_99_percent_of_time(self, app):
- """Test that cleanup is skipped 99% of the time (random > 1)."""
- from local_deep_research.web.auth.middleware_optimizer import (
- should_skip_session_cleanup,
- )
+ # -- probabilistic: random == 1 defers to database middleware ---------
+ def test_run_cleanup_when_random_returns_1_and_normal_path(self, app):
+ """When random returns 1 on a non-skip path, should NOT skip (cleanup runs)."""
with app.test_request_context("/api/research", method="GET"):
- # Test with random values > 1 (should skip)
- for rand_val in [2, 50, 100]:
- with patch("random.randint", return_value=rand_val):
- result = should_skip_session_cleanup()
- assert result is True, (
- f"Expected skip for random={rand_val}"
- )
-
- def test_run_cleanup_1_percent(self, app):
- """Test that cleanup runs when random returns 1."""
- from local_deep_research.web.auth.middleware_optimizer import (
- should_skip_session_cleanup,
- )
+ with patch("random.randint", return_value=1):
+ assert should_skip_session_cleanup() is False
- with app.test_request_context("/api/research", method="GET"):
+ def test_skip_static_even_when_random_returns_1(self, app):
+ """Static files should skip cleanup even when random returns 1."""
+ with app.test_request_context("/static/js/app.js", method="GET"):
with patch("random.randint", return_value=1):
- result = should_skip_session_cleanup()
- # When random returns 1, we should NOT skip (run cleanup)
- assert result is False
+ assert should_skip_session_cleanup() is True
- def test_skip_auth_routes(self, app):
- """Test that auth routes skip cleanup."""
- from local_deep_research.web.auth.middleware_optimizer import (
- should_skip_session_cleanup,
- )
+ def test_skip_health_even_when_random_returns_1(self, app):
+ """Health endpoint should skip cleanup even when random returns 1."""
+ with app.test_request_context("/health", method="GET"):
+ with patch("random.randint", return_value=1):
+ assert should_skip_session_cleanup() is True
+ def test_skip_auth_routes_even_when_random_returns_1(self, app):
+ """Auth routes should skip cleanup even when random returns 1."""
with app.test_request_context("/auth/login", method="POST"):
- with patch("random.randint", return_value=1): # Would normally run
- result = should_skip_session_cleanup()
- assert result is True
-
- def test_skip_favicon(self, app):
- """Test that favicon skips cleanup."""
- from local_deep_research.web.auth.middleware_optimizer import (
- should_skip_session_cleanup,
- )
+ with patch("random.randint", return_value=1):
+ assert should_skip_session_cleanup() is True
+ def test_skip_favicon_even_when_random_returns_1(self, app):
+ """Favicon should skip cleanup even when random returns 1."""
with app.test_request_context("/favicon.ico", method="GET"):
- with patch("random.randint", return_value=1): # Would normally run
- result = should_skip_session_cleanup()
- assert result is True
-
- def test_skip_socket_io(self, app):
- """Test that socket.io paths skip cleanup."""
- from local_deep_research.web.auth.middleware_optimizer import (
- should_skip_session_cleanup,
- )
+ with patch("random.randint", return_value=1):
+ assert should_skip_session_cleanup() is True
+ def test_skip_socket_io_even_when_random_returns_1(self, app):
+ """Socket.IO paths should skip cleanup even when random returns 1."""
with app.test_request_context(
"/socket.io/?EIO=4&transport=polling", method="GET"
):
- with patch("random.randint", return_value=1): # Would normally run
- result = should_skip_session_cleanup()
- assert result is True
-
- def test_skip_robots_txt(self, app):
- """Test that robots.txt skips cleanup."""
- from local_deep_research.web.auth.middleware_optimizer import (
- should_skip_session_cleanup,
- )
+ with patch("random.randint", return_value=1):
+ assert should_skip_session_cleanup() is True
+ def test_skip_robots_txt_even_when_random_returns_1(self, app):
+ """robots.txt should skip cleanup even when random returns 1."""
with app.test_request_context("/robots.txt", method="GET"):
with patch("random.randint", return_value=1):
- result = should_skip_session_cleanup()
- assert result is True
-
- def test_skip_options_preflight(self, app):
- """Test that OPTIONS preflight requests skip cleanup."""
- from local_deep_research.web.auth.middleware_optimizer import (
- should_skip_session_cleanup,
- )
+ assert should_skip_session_cleanup() is True
+ def test_skip_options_even_when_random_returns_1(self, app):
+ """OPTIONS requests should skip cleanup even when random returns 1."""
with app.test_request_context("/api/research", method="OPTIONS"):
with patch("random.randint", return_value=1):
- result = should_skip_session_cleanup()
- assert result is True
+ assert should_skip_session_cleanup() is True
diff --git a/tests/web/test_server_config.py b/tests/web/test_server_config.py
index b222d5ad0e..d381f77b71 100644
--- a/tests/web/test_server_config.py
+++ b/tests/web/test_server_config.py
@@ -9,84 +9,153 @@ import json
from pathlib import Path
from unittest.mock import patch
+import pytest
+
+from local_deep_research.web.server_config import (
+ get_server_config_path,
+ load_server_config,
+ save_server_config,
+ sync_from_settings,
+)
+
+
+# ---------------------------------------------------------------------------
+# Shared fixture: redirect get_data_dir to a tmp directory
+# ---------------------------------------------------------------------------
[email protected](autouse=True)
+def _mock_data_dir(tmp_path):
+ """Redirect get_data_dir to tmp_path for every test."""
+ with patch(
+ "local_deep_research.web.server_config.get_data_dir",
+ return_value=str(tmp_path),
+ ):
+ yield
+
-from tests.test_utils import add_src_to_path
+def _passthrough_typed_setting():
+ """Mock get_typed_setting_value to return val if not None, else default."""
+ with patch(
+ "local_deep_research.web.server_config.get_typed_setting_value",
+ side_effect=lambda key, val, typ, default: (
+ val if val is not None else default
+ ),
+ ):
+ yield
-add_src_to_path()
+
+def _default_typed_setting():
+ """Mock get_typed_setting_value to always return default."""
+ with patch(
+ "local_deep_research.web.server_config.get_typed_setting_value",
+ side_effect=lambda key, val, typ, default: default,
+ ):
+ yield
+# ===================================================================
+# get_server_config_path
+# ===================================================================
class TestGetServerConfigPath:
"""Tests for get_server_config_path function."""
- def test_returns_path_object(self, tmp_path):
+ def test_returns_path_object(self):
"""Should return a Path object."""
- with patch(
- "local_deep_research.web.server_config.get_data_dir",
- return_value=str(tmp_path),
- ):
- from local_deep_research.web.server_config import (
- get_server_config_path,
- )
+ result = get_server_config_path()
+ assert isinstance(result, Path)
- result = get_server_config_path()
-
- assert isinstance(result, Path)
-
- def test_correct_filename(self, tmp_path):
- """Should use correct filename."""
- with patch(
- "local_deep_research.web.server_config.get_data_dir",
- return_value=str(tmp_path),
- ):
- from local_deep_research.web.server_config import (
- get_server_config_path,
- )
-
- result = get_server_config_path()
-
- assert result.name == "server_config.json"
+ def test_ends_with_server_config_json(self):
+ """Should end with 'server_config.json'."""
+ result = get_server_config_path()
+ assert result.name == "server_config.json"
def test_path_under_data_dir(self, tmp_path):
- """Should be under the data directory."""
- with patch(
- "local_deep_research.web.server_config.get_data_dir",
- return_value=str(tmp_path),
- ):
- from local_deep_research.web.server_config import (
- get_server_config_path,
- )
-
- result = get_server_config_path()
-
- assert result.parent == tmp_path
+ """Should be directly under the data directory."""
+ result = get_server_config_path()
+ assert result.parent == tmp_path
+# ===================================================================
+# load_server_config
+# ===================================================================
class TestLoadServerConfig:
"""Tests for load_server_config function."""
- def test_returns_defaults_when_no_file(self, tmp_path):
- """Should return default config when file doesn't exist."""
- with patch(
- "local_deep_research.web.server_config.get_data_dir",
- return_value=str(tmp_path),
- ):
- with patch(
- "local_deep_research.web.server_config.get_typed_setting_value",
- side_effect=lambda key, val, typ, default: default,
- ):
- from local_deep_research.web.server_config import (
- load_server_config,
- )
-
- result = load_server_config()
-
- assert result["host"] == "0.0.0.0"
- assert result["port"] == 5000
- assert result["debug"] is False
- assert result["use_https"] is True
-
+ # -- keys and types -------------------------------------------------
+
+ @pytest.mark.usefixtures("_default_typed_setting")
+ def test_returns_dict(self):
+ """Should return a dict."""
+ result = load_server_config()
+ assert isinstance(result, dict)
+
+ @pytest.mark.usefixtures("_default_typed_setting")
+ def test_contains_expected_keys(self):
+ """Should contain all expected configuration keys."""
+ result = load_server_config()
+ expected_keys = {
+ "host",
+ "port",
+ "debug",
+ "use_https",
+ "allow_registrations",
+ "rate_limit_default",
+ "rate_limit_login",
+ "rate_limit_registration",
+ }
+ assert expected_keys.issubset(result.keys())
+
+ # -- defaults -------------------------------------------------------
+
+ @pytest.mark.usefixtures("_default_typed_setting")
+ def test_default_host(self):
+ """Default host should be 0.0.0.0."""
+ assert load_server_config()["host"] == "0.0.0.0"
+
+ @pytest.mark.usefixtures("_default_typed_setting")
+ def test_default_port(self):
+ """Default port should be 5000."""
+ assert load_server_config()["port"] == 5000
+
+ @pytest.mark.usefixtures("_default_typed_setting")
+ def test_default_debug(self):
+ """Default debug should be False."""
+ assert load_server_config()["debug"] is False
+
+ @pytest.mark.usefixtures("_default_typed_setting")
+ def test_default_use_https(self):
+ """Default use_https should be True."""
+ assert load_server_config()["use_https"] is True
+
+ @pytest.mark.usefixtures("_default_typed_setting")
+ def test_default_allow_registrations(self):
+ """Default allow_registrations should be True."""
+ assert load_server_config()["allow_registrations"] is True
+
+ @pytest.mark.usefixtures("_default_typed_setting")
+ def test_default_rate_limit_default(self):
+ """Default rate_limit_default value."""
+ assert (
+ load_server_config()["rate_limit_default"]
+ == "5000 per hour;50000 per day"
+ )
+
+ @pytest.mark.usefixtures("_default_typed_setting")
+ def test_default_rate_limit_login(self):
+ """Default rate_limit_login value."""
+ assert load_server_config()["rate_limit_login"] == "5 per 15 minutes"
+
+ @pytest.mark.usefixtures("_default_typed_setting")
+ def test_default_rate_limit_registration(self):
+ """Default rate_limit_registration value."""
+ assert load_server_config()["rate_limit_registration"] == "3 per hour"
+
+ # -- loading from file ---------------------------------------------
+
+ @pytest.mark.usefixtures("_passthrough_typed_setting")
def test_loads_from_existing_file(self, tmp_path):
- """Should load config from existing file."""
+ """Should load config values from existing JSON file."""
config_file = tmp_path / "server_config.json"
config_data = {
"host": "127.0.0.1",
@@ -96,184 +165,141 @@ class TestLoadServerConfig:
}
config_file.write_text(json.dumps(config_data))
- with patch(
- "local_deep_research.web.server_config.get_data_dir",
- return_value=str(tmp_path),
- ):
- with patch(
- "local_deep_research.web.server_config.get_typed_setting_value",
- side_effect=lambda key, val, typ, default: val
- if val is not None
- else default,
- ):
- from local_deep_research.web.server_config import (
- load_server_config,
- )
-
- result = load_server_config()
-
- assert result["host"] == "127.0.0.1"
- assert result["port"] == 8080
- assert result["debug"] is True
- assert result["use_https"] is False
+ result = load_server_config()
+ assert result["host"] == "127.0.0.1"
+ assert result["port"] == 8080
+ assert result["debug"] is True
+ assert result["use_https"] is False
+
+ @pytest.mark.usefixtures("_default_typed_setting")
+ def test_returns_defaults_when_no_file(self, tmp_path):
+ """Should return default config when file does not exist."""
+ assert not (tmp_path / "server_config.json").exists()
+
+ result = load_server_config()
+
+ assert result["host"] == "0.0.0.0"
+ assert result["port"] == 5000
+ assert result["debug"] is False
+ assert result["use_https"] is True
+
+ # -- corrupt JSON ---------------------------------------------------
+
+ @pytest.mark.usefixtures("_default_typed_setting")
def test_handles_corrupt_json(self, tmp_path):
- """Should handle corrupt JSON gracefully."""
+ """Should fall back to defaults on corrupt JSON."""
config_file = tmp_path / "server_config.json"
config_file.write_text("{ invalid json }")
- with patch(
- "local_deep_research.web.server_config.get_data_dir",
- return_value=str(tmp_path),
- ):
- with patch(
- "local_deep_research.web.server_config.get_typed_setting_value",
- side_effect=lambda key, val, typ, default: default,
- ):
- with patch(
- "local_deep_research.web.server_config.logger"
- ) as mock_logger:
- from local_deep_research.web.server_config import (
- load_server_config,
- )
-
- result = load_server_config()
-
- # Should log warning
- mock_logger.warning.assert_called_once()
- # Should return defaults
- assert result["host"] == "0.0.0.0"
- assert result["port"] == 5000
-
- def test_includes_rate_limit_settings(self, tmp_path):
- """Should include rate limit settings."""
- with patch(
- "local_deep_research.web.server_config.get_data_dir",
- return_value=str(tmp_path),
- ):
- with patch(
- "local_deep_research.web.server_config.get_typed_setting_value",
- side_effect=lambda key, val, typ, default: default,
- ):
- from local_deep_research.web.server_config import (
- load_server_config,
- )
+ result = load_server_config()
- result = load_server_config()
+ assert result["host"] == "0.0.0.0"
+ assert result["port"] == 5000
- assert "rate_limit_default" in result
- assert "rate_limit_login" in result
- assert "rate_limit_registration" in result
+ @pytest.mark.usefixtures("_default_typed_setting")
+ def test_corrupt_json_logs_warning(self, tmp_path):
+ """Should log a warning when config file is corrupt."""
+ config_file = tmp_path / "server_config.json"
+ config_file.write_text("not-json")
- def test_includes_allow_registrations(self, tmp_path):
- """Should include allow_registrations setting."""
with patch(
- "local_deep_research.web.server_config.get_data_dir",
- return_value=str(tmp_path),
- ):
- with patch(
- "local_deep_research.web.server_config.get_typed_setting_value",
- side_effect=lambda key, val, typ, default: default,
- ):
- from local_deep_research.web.server_config import (
- load_server_config,
- )
+ "local_deep_research.web.server_config.logger"
+ ) as mock_logger:
+ load_server_config()
+ mock_logger.warning.assert_called_once()
- result = load_server_config()
+ # -- LDR_APP_ALLOW_REGISTRATIONS env var ----------------------------
- assert "allow_registrations" in result
- assert result["allow_registrations"] is True
+ @pytest.mark.usefixtures("_default_typed_setting")
+ @pytest.mark.parametrize(
+ "value", ["true", "false", "1", "0", "yes", "no", "on", "off"]
+ )
+ def test_recognized_allow_registrations_values(self, value, monkeypatch):
+ """Recognized boolean env-var values should NOT trigger fail-closed override."""
+ monkeypatch.setenv("LDR_APP_ALLOW_REGISTRATIONS", value)
+ with patch(
+ "local_deep_research.web.server_config.logger"
+ ) as mock_logger:
+ load_server_config()
+
+ warning_calls = [str(c) for c in mock_logger.warning.call_args_list]
+ assert not any("recognized" in call for call in warning_calls), (
+ f"Unexpected warning for recognized value '{value}': {warning_calls}"
+ )
+
+ @pytest.mark.usefixtures("_default_typed_setting")
+ @pytest.mark.parametrize(
+ "value", ["disabled", "nein", "flase", "MAYBE", "2"]
+ )
def test_unrecognized_allow_registrations_defaults_to_false(
- self, tmp_path, monkeypatch
+ self, value, monkeypatch
):
- """Unrecognized LDR_APP_ALLOW_REGISTRATIONS value should default to False (fail closed)."""
- monkeypatch.setenv("LDR_APP_ALLOW_REGISTRATIONS", "disabled")
+ """Unrecognized env-var value should force allow_registrations=False."""
+ monkeypatch.setenv("LDR_APP_ALLOW_REGISTRATIONS", value)
+
+ result = load_server_config()
+
+ assert result["allow_registrations"] is False
+
+ @pytest.mark.usefixtures("_default_typed_setting")
+ def test_unrecognized_allow_registrations_logs_warning(self, monkeypatch):
+ """Should log a warning for unrecognized env-var value."""
+ monkeypatch.setenv("LDR_APP_ALLOW_REGISTRATIONS", "nein")
with patch(
- "local_deep_research.web.server_config.get_data_dir",
- return_value=str(tmp_path),
- ):
- with patch(
- "local_deep_research.web.server_config.get_typed_setting_value",
- side_effect=lambda key, val, typ, default: default,
- ):
- with patch(
- "local_deep_research.web.server_config.logger"
- ) as mock_logger:
- from local_deep_research.web.server_config import (
- load_server_config,
- )
-
- result = load_server_config()
-
- # Should have warned about unrecognized value
- warning_calls = [
- str(c) for c in mock_logger.warning.call_args_list
- ]
- assert any(
- "disabled" in call and "recognized" in call
- for call in warning_calls
- ), (
- f"Expected warning about 'disabled', got: {warning_calls}"
- )
-
- # Should default to False (fail closed) for security
- assert result["allow_registrations"] is False
-
- def test_no_warning_on_recognized_allow_registrations_value(
+ "local_deep_research.web.server_config.logger"
+ ) as mock_logger:
+ load_server_config()
+
+ warning_calls = [str(c) for c in mock_logger.warning.call_args_list]
+ assert any(
+ "nein" in call and "recognized" in call
+ for call in warning_calls
+ ), f"Expected warning about 'nein', got: {warning_calls}"
+
+ @pytest.mark.usefixtures("_default_typed_setting")
+ def test_allow_registrations_env_not_set_uses_default(self, monkeypatch):
+ """When env var is not set, allow_registrations should use saved/default value."""
+ monkeypatch.delenv("LDR_APP_ALLOW_REGISTRATIONS", raising=False)
+
+ result = load_server_config()
+
+ # Default is True
+ assert result["allow_registrations"] is True
+
+ @pytest.mark.usefixtures("_passthrough_typed_setting")
+ def test_allow_registrations_env_not_set_uses_saved_value(
self, tmp_path, monkeypatch
):
- """Should NOT warn when LDR_APP_ALLOW_REGISTRATIONS is a recognized boolean value."""
- monkeypatch.setenv("LDR_APP_ALLOW_REGISTRATIONS", "false")
+ """When env var is not set and config file has a saved value, uses saved value."""
+ monkeypatch.delenv("LDR_APP_ALLOW_REGISTRATIONS", raising=False)
- with patch(
- "local_deep_research.web.server_config.get_data_dir",
- return_value=str(tmp_path),
- ):
- with patch(
- "local_deep_research.web.server_config.get_typed_setting_value",
- side_effect=lambda key, val, typ, default: default,
- ):
- with patch(
- "local_deep_research.web.server_config.logger"
- ) as mock_logger:
- from local_deep_research.web.server_config import (
- load_server_config,
- )
-
- load_server_config()
-
- # No warning should contain "recognized"
- warning_calls = [
- str(c) for c in mock_logger.warning.call_args_list
- ]
- assert not any(
- "recognized" in call for call in warning_calls
- ), (
- f"Unexpected warning about recognized value: {warning_calls}"
- )
+ config_file = tmp_path / "server_config.json"
+ config_file.write_text(json.dumps({"allow_registrations": False}))
+
+ result = load_server_config()
+
+ assert result["allow_registrations"] is False
+# ===================================================================
+# save_server_config
+# ===================================================================
class TestSaveServerConfig:
"""Tests for save_server_config function."""
- def test_saves_to_file(self, tmp_path):
- """Should save config to file."""
- with patch(
- "local_deep_research.web.server_config.get_data_dir",
- return_value=str(tmp_path),
- ):
- from local_deep_research.web.server_config import save_server_config
-
- config = {"host": "localhost", "port": 3000}
- save_server_config(config)
+ def test_saves_config_to_file(self, tmp_path):
+ """Should save config as JSON to config path."""
+ config = {"host": "localhost", "port": 3000}
+ save_server_config(config)
- config_file = tmp_path / "server_config.json"
- assert config_file.exists()
- saved_data = json.loads(config_file.read_text())
- assert saved_data["host"] == "localhost"
- assert saved_data["port"] == 3000
+ config_file = tmp_path / "server_config.json"
+ assert config_file.exists()
+ saved_data = json.loads(config_file.read_text())
+ assert saved_data["host"] == "localhost"
+ assert saved_data["port"] == 3000
def test_creates_parent_directory(self, tmp_path):
"""Should create parent directory if it doesn't exist."""
@@ -283,190 +309,148 @@ class TestSaveServerConfig:
"local_deep_research.web.server_config.get_data_dir",
return_value=str(nested_path),
):
- from local_deep_research.web.server_config import save_server_config
-
- config = {"host": "localhost"}
- save_server_config(config)
+ save_server_config({"host": "localhost"})
config_file = nested_path / "server_config.json"
assert config_file.exists()
- def test_handles_write_errors(self, tmp_path):
- """Should handle write errors gracefully."""
- with patch(
- "local_deep_research.web.server_config.get_data_dir",
- return_value=str(tmp_path),
- ):
- with patch(
- "builtins.open", side_effect=PermissionError("No write access")
- ):
- with patch(
- "local_deep_research.web.server_config.logger"
- ) as mock_logger:
- from local_deep_research.web.server_config import (
- save_server_config,
- )
+ @pytest.mark.usefixtures("_passthrough_typed_setting")
+ def test_saved_config_can_be_loaded_back(self, tmp_path):
+ """Saved config should be loadable via load_server_config."""
+ config = {
+ "host": "10.0.0.1",
+ "port": 9999,
+ "debug": True,
+ "use_https": False,
+ "allow_registrations": False,
+ "rate_limit_default": "100 per hour",
+ "rate_limit_login": "10 per minute",
+ "rate_limit_registration": "1 per hour",
+ }
+ save_server_config(config)
- # Should not raise, but log exception
- save_server_config({"host": "localhost"})
+ loaded = load_server_config()
- mock_logger.exception.assert_called_once()
+ assert loaded["host"] == "10.0.0.1"
+ assert loaded["port"] == 9999
+ assert loaded["debug"] is True
+ assert loaded["use_https"] is False
- def test_logs_success(self, tmp_path):
- """Should log success when saved."""
+ def test_handles_write_errors_gracefully(self, tmp_path):
+ """Should not raise on write errors, but log exception."""
with patch(
- "local_deep_research.web.server_config.get_data_dir",
- return_value=str(tmp_path),
+ "builtins.open", side_effect=PermissionError("No write access")
):
with patch(
"local_deep_research.web.server_config.logger"
) as mock_logger:
- from local_deep_research.web.server_config import (
- save_server_config,
- )
-
+ # Should not raise
save_server_config({"host": "localhost"})
- mock_logger.info.assert_called_once()
- call_args = mock_logger.info.call_args[0][0]
- assert "saved" in call_args.lower()
+ mock_logger.exception.assert_called_once()
def test_formats_json_with_indent(self, tmp_path):
- """Should format JSON with indentation."""
- with patch(
- "local_deep_research.web.server_config.get_data_dir",
- return_value=str(tmp_path),
- ):
- from local_deep_research.web.server_config import save_server_config
+ """Should format JSON with indentation for readability."""
+ save_server_config({"host": "localhost", "port": 3000})
+
+ config_file = tmp_path / "server_config.json"
+ content = config_file.read_text()
+ # Indented JSON has newlines
+ assert "\n" in content
- config = {"host": "localhost", "port": 3000}
- save_server_config(config)
+ def test_logs_success(self, tmp_path):
+ """Should log a success message after saving."""
+ with patch(
+ "local_deep_research.web.server_config.logger"
+ ) as mock_logger:
+ save_server_config({"host": "localhost"})
- config_file = tmp_path / "server_config.json"
- content = config_file.read_text()
- # Indented JSON has newlines
- assert "\n" in content
+ mock_logger.info.assert_called_once()
+ call_args = mock_logger.info.call_args[0][0]
+ assert "saved" in call_args.lower()
+# ===================================================================
+# sync_from_settings
+# ===================================================================
class TestSyncFromSettings:
"""Tests for sync_from_settings function."""
- def test_updates_host_from_settings(self, tmp_path):
+ @pytest.mark.usefixtures("_passthrough_typed_setting")
+ def test_updates_host_from_snapshot(self, tmp_path):
"""Should update host from settings snapshot."""
- with patch(
- "local_deep_research.web.server_config.get_data_dir",
- return_value=str(tmp_path),
- ):
- with patch(
- "local_deep_research.web.server_config.get_typed_setting_value",
- side_effect=lambda key, val, typ, default: val
- if val is not None
- else default,
- ):
- from local_deep_research.web.server_config import (
- sync_from_settings,
- )
-
- sync_from_settings({"web.host": "192.168.1.1"})
-
- config_file = tmp_path / "server_config.json"
- saved_data = json.loads(config_file.read_text())
- assert saved_data["host"] == "192.168.1.1"
-
- def test_updates_port_from_settings(self, tmp_path):
+ sync_from_settings({"web.host": "192.168.1.1"})
+
+ config_file = tmp_path / "server_config.json"
+ saved_data = json.loads(config_file.read_text())
+ assert saved_data["host"] == "192.168.1.1"
+
+ @pytest.mark.usefixtures("_passthrough_typed_setting")
+ def test_updates_port_from_snapshot(self, tmp_path):
"""Should update port from settings snapshot."""
- with patch(
- "local_deep_research.web.server_config.get_data_dir",
- return_value=str(tmp_path),
- ):
- with patch(
- "local_deep_research.web.server_config.get_typed_setting_value",
- side_effect=lambda key, val, typ, default: val
- if val is not None
- else default,
- ):
- from local_deep_research.web.server_config import (
- sync_from_settings,
- )
-
- sync_from_settings({"web.port": 9000})
-
- config_file = tmp_path / "server_config.json"
- saved_data = json.loads(config_file.read_text())
- assert saved_data["port"] == 9000
-
- def test_updates_all_supported_settings(self, tmp_path):
- """Should update all supported settings."""
- with patch(
- "local_deep_research.web.server_config.get_data_dir",
- return_value=str(tmp_path),
- ):
- with patch(
- "local_deep_research.web.server_config.get_typed_setting_value",
- side_effect=lambda key, val, typ, default: val
- if val is not None
- else default,
- ):
- from local_deep_research.web.server_config import (
- sync_from_settings,
- )
-
- settings = {
- "web.host": "10.0.0.1",
- "web.port": 4000,
- "app.debug": True,
- "web.use_https": False,
- "app.allow_registrations": False,
- "security.rate_limit_default": "100 per hour",
- "security.rate_limit_login": "10 per minute",
- "security.rate_limit_registration": "1 per hour",
- }
- sync_from_settings(settings)
-
- config_file = tmp_path / "server_config.json"
- saved_data = json.loads(config_file.read_text())
-
- assert saved_data["host"] == "10.0.0.1"
- assert saved_data["port"] == 4000
- assert saved_data["debug"] is True
- assert saved_data["use_https"] is False
- assert saved_data["allow_registrations"] is False
- assert saved_data["rate_limit_default"] == "100 per hour"
- assert saved_data["rate_limit_login"] == "10 per minute"
- assert saved_data["rate_limit_registration"] == "1 per hour"
-
- def test_ignores_unknown_settings(self, tmp_path):
- """Should ignore settings not in the known list."""
- with patch(
- "local_deep_research.web.server_config.get_data_dir",
- return_value=str(tmp_path),
- ):
- with patch(
- "local_deep_research.web.server_config.get_typed_setting_value",
- side_effect=lambda key, val, typ, default: val
- if val is not None
- else default,
- ):
- from local_deep_research.web.server_config import (
- sync_from_settings,
- )
-
- sync_from_settings(
- {
- "web.host": "localhost",
- "unknown.setting": "should be ignored",
- }
- )
-
- config_file = tmp_path / "server_config.json"
- saved_data = json.loads(config_file.read_text())
-
- assert saved_data["host"] == "localhost"
- assert "unknown.setting" not in saved_data
- assert "unknown" not in saved_data
+ sync_from_settings({"web.port": 9000})
+
+ config_file = tmp_path / "server_config.json"
+ saved_data = json.loads(config_file.read_text())
+ assert saved_data["port"] == 9000
+
+ @pytest.mark.usefixtures("_passthrough_typed_setting")
+ def test_updates_multiple_settings_at_once(self, tmp_path):
+ """Should update all supported settings in a single call."""
+ settings = {
+ "web.host": "10.0.0.1",
+ "web.port": 4000,
+ "app.debug": True,
+ "web.use_https": False,
+ "app.allow_registrations": False,
+ "security.rate_limit_default": "100 per hour",
+ "security.rate_limit_login": "10 per minute",
+ "security.rate_limit_registration": "1 per hour",
+ }
+ sync_from_settings(settings)
+
+ config_file = tmp_path / "server_config.json"
+ saved_data = json.loads(config_file.read_text())
+
+ assert saved_data["host"] == "10.0.0.1"
+ assert saved_data["port"] == 4000
+ assert saved_data["debug"] is True
+ assert saved_data["use_https"] is False
+ assert saved_data["allow_registrations"] is False
+ assert saved_data["rate_limit_default"] == "100 per hour"
+ assert saved_data["rate_limit_login"] == "10 per minute"
+ assert saved_data["rate_limit_registration"] == "1 per hour"
+
+ @pytest.mark.usefixtures("_passthrough_typed_setting")
+ def test_ignores_keys_not_in_snapshot(self, tmp_path):
+ """Settings not present in snapshot should not appear as extra keys."""
+ sync_from_settings(
+ {
+ "web.host": "localhost",
+ "unknown.setting": "should be ignored",
+ }
+ )
+ config_file = tmp_path / "server_config.json"
+ saved_data = json.loads(config_file.read_text())
+
+ assert saved_data["host"] == "localhost"
+ assert "unknown.setting" not in saved_data
+ assert "unknown" not in saved_data
+
+ @pytest.mark.usefixtures("_passthrough_typed_setting")
+ def test_saves_the_merged_config(self, tmp_path):
+ """sync_from_settings should persist the merged config to disk."""
+ sync_from_settings({"web.host": "saved-host"})
+
+ config_file = tmp_path / "server_config.json"
+ assert config_file.exists()
+ saved_data = json.loads(config_file.read_text())
+ assert saved_data["host"] == "saved-host"
+
+ @pytest.mark.usefixtures("_passthrough_typed_setting")
def test_preserves_existing_values(self, tmp_path):
- """Should preserve values not in the settings snapshot."""
+ """Values not in the snapshot should be preserved from the existing config."""
# Create initial config
config_file = tmp_path / "server_config.json"
initial_config = {
@@ -477,46 +461,21 @@ class TestSyncFromSettings:
}
config_file.write_text(json.dumps(initial_config))
- with patch(
- "local_deep_research.web.server_config.get_data_dir",
- return_value=str(tmp_path),
- ):
- with patch(
- "local_deep_research.web.server_config.get_typed_setting_value",
- side_effect=lambda key, val, typ, default: val
- if val is not None
- else default,
- ):
- from local_deep_research.web.server_config import (
- sync_from_settings,
- )
-
- # Only update host
- sync_from_settings({"web.host": "new-host"})
+ # Only update host
+ sync_from_settings({"web.host": "new-host"})
- saved_data = json.loads(config_file.read_text())
+ saved_data = json.loads(config_file.read_text())
- assert saved_data["host"] == "new-host"
- assert saved_data["port"] == 1234 # Preserved
- assert saved_data["debug"] is False # Preserved
- assert saved_data["use_https"] is True # Preserved
+ assert saved_data["host"] == "new-host"
+ assert saved_data["port"] == 1234 # Preserved
+ assert saved_data["debug"] is False # Preserved
+ assert saved_data["use_https"] is True # Preserved
+ @pytest.mark.usefixtures("_default_typed_setting")
def test_empty_settings_snapshot(self, tmp_path):
- """Should handle empty settings snapshot."""
- with patch(
- "local_deep_research.web.server_config.get_data_dir",
- return_value=str(tmp_path),
- ):
- with patch(
- "local_deep_research.web.server_config.get_typed_setting_value",
- side_effect=lambda key, val, typ, default: default,
- ):
- from local_deep_research.web.server_config import (
- sync_from_settings,
- )
-
- # Should not raise
- sync_from_settings({})
+ """Should handle empty settings snapshot without error."""
+ # Should not raise
+ sync_from_settings({})
- config_file = tmp_path / "server_config.json"
- assert config_file.exists()
+ config_file = tmp_path / "server_config.json"
+ assert config_file.exists()