~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
security: fix multiple authentication and redirect vulnerabilities (#2168)
LearningCircuit4b34561798c9
diff --git a/src/local_deep_research/database/encrypted_db.py b/src/local_deep_research/database/encrypted_db.pyindex 2d37af9ef3..1c723035b2 100644--- a/src/local_deep_research/database/encrypted_db.py+++ b/src/local_deep_research/database/encrypted_db.py@@ -732,6 +732,15 @@ class DatabaseManager:"""db_path = self._get_user_db_path(username)+ # Prevent timing attacks: always derive key before checking file existence+ # This ensures both existing and non-existent users take the same amount of time,+ # preventing username enumeration via timing analysis.+ # Pre-derive key before closures to avoid capturing plaintext password+ hex_key = get_key_from_password(password, db_path=db_path).hex()++ if not db_path.exists():+ raise ValueError(f"No database found for user {username}")+# Warn if this is a legacy database without per-database saltif self.has_encryption and not has_per_database_salt(db_path):logger.warning(@@ -741,15 +750,6 @@ class DatabaseManager:f"fully functional but are less resistant to multi-target attacks.")- # Prevent timing attacks: always derive key before checking file existence- # This ensures both existing and non-existent users take the same amount of time,- # preventing username enumeration via timing analysis.- # Pre-derive key before closures- hex_key = get_key_from_password(password, db_path=db_path).hex()-- if not db_path.exists():- raise ValueError(f"No database found for user {username}")-# Create thread-specific key for engine reuse (tuple is cleaner than string)thread_id = threading.get_ident()engine_key = (username, thread_id)diff --git a/src/local_deep_research/security/url_validator.py b/src/local_deep_research/security/url_validator.pyindex fc14559ba1..7a066d1448 100644--- a/src/local_deep_research/security/url_validator.py+++ b/src/local_deep_research/security/url_validator.py@@ -7,7 +7,7 @@ data exfiltration, and other URL-based security vulnerabilities.import refrom typing import Optional, List-from urllib.parse import urlparse, urljoin+from urllib.parse import urlparse, urljoin, unquotefrom loguru import logger@@ -361,7 +361,7 @@ class URLValidator:- Triple-slash bypass (///evil.com)- URL-encoded bypass attempts- Backslash bypass (treated as forward slash by some browsers)- - Path traversal blocking+ - Path traversal detectionArgs:target: The redirect URL to validate (can be relative or absolute)@@ -380,12 +380,14 @@ class URLValidator:# Normalize and decode URL to detect encoded bypass attempts# This catches %2f%2f (encoded //) and similar tricks- try:- from urllib.parse import unquote+ decoded_target = unquote(target)- decoded_target = unquote(target)- except Exception:- decoded_target = target+ # Check for encoded CRLF injection (e.g. %0d%0a)+ if "\r" in decoded_target or "\n" in decoded_target:+ logger.warning(+ "Encoded CRLF injection attempt detected in redirect URL"+ )+ return False# Check for backslash (treated as forward slash by some browsers)# Prevents \evil.com and \\evil.com bypasses@@ -399,11 +401,13 @@ class URLValidator:logger.warning("Protocol-relative URL detected in redirect")return False- # Block path traversal patterns in redirect URL path- # Check both original and decoded to catch single-encoded traversal (%2e%2e)- original_path = urlparse(target).path- decoded_path = urlparse(decoded_target).path- if ".." in original_path or ".." in decoded_path:+ # Block null bytes (truncation attacks in some URL processors)+ if "\x00" in decoded_target:+ logger.warning("Null byte detected in redirect URL")+ return False++ # Block path traversal patterns (/../, /.. at end, ../ at start)+ if re.search(r"(^|/)\.\.(/|$|\?|#)", decoded_target):logger.warning("Path traversal detected in redirect URL: %s", target)@@ -411,9 +415,11 @@ class URLValidator:ref_url = urlparse(host_url)test_url = urlparse(urljoin(host_url, target))+if test_url.path.startswith("//"):logger.warning("Double-slash path in redirect URL: %s", target)return False+return (test_url.scheme in ("http", "https")and ref_url.netloc == test_url.netlocdiff --git a/src/local_deep_research/web/auth/routes.py b/src/local_deep_research/web/auth/routes.pyindex f62007ad0a..e6eed08d85 100644--- a/src/local_deep_research/web/auth/routes.py+++ b/src/local_deep_research/web/auth/routes.py@@ -348,7 +348,6 @@ def register():except Exception:logger.exception(f"Registration failed for {username}")auth_db.rollback()- auth_db.close()flash("Registration failed. Please try again.", "error")return render_template("auth/register.html", has_encryption=db_manager.has_encryptiondiff --git a/tests/database/test_encrypted_db_manager.py b/tests/database/test_encrypted_db_manager.pyindex 8e4a5b1585..288b291a43 100644--- a/tests/database/test_encrypted_db_manager.py+++ b/tests/database/test_encrypted_db_manager.py@@ -1317,3 +1317,134 @@ class TestMakeSqlcipherConnectionCursorCloseLogging:# No warning should be logged when cursor.close() succeedsmock_logger.warning.assert_not_called()+++class TestTimingAttackPrevention:+ """Tests for timing attack prevention in open_user_database and+ create_thread_safe_session_for_metrics (PR #2168).++ Key derivation (get_key_from_password) must happen BEFORE the+ db_path.exists() check so that both existing and non-existing users+ take the same amount of time, preventing username enumeration.+ """++ @patch("local_deep_research.database.encrypted_db.get_data_directory")+ def test_open_user_database_derives_key_before_file_check(+ self, mock_data_dir, tmp_path+ ):+ """open_user_database derives key before checking if user db exists."""+ from local_deep_research.database.encrypted_db import DatabaseManager++ mock_data_dir.return_value = tmp_path++ with patch.object(+ DatabaseManager, "_check_encryption_available", return_value=True+ ):+ manager = DatabaseManager()++ with patch(+ "local_deep_research.database.encrypted_db.get_key_from_password"+ ) as mock_derive:+ mock_derive.return_value = b"\x00" * 32++ # Non-existent user — no database file exists+ result = manager.open_user_database(+ "nonexistent_user", "password123"+ )++ # Should return None+ assert result is None+ # Key derivation must have been called+ mock_derive.assert_called_once()++ @patch("local_deep_research.database.encrypted_db.get_data_directory")+ def test_open_user_database_derives_key_for_existing_user(+ self, mock_data_dir, tmp_path+ ):+ """Key derivation called for existing users too (timing consistency)."""+ from local_deep_research.config.paths import get_user_database_filename+ from local_deep_research.database.encrypted_db import DatabaseManager++ mock_data_dir.return_value = tmp_path++ with patch.object(+ DatabaseManager, "_check_encryption_available", return_value=False+ ):+ manager = DatabaseManager()++ # Create database at the correct path+ username = "test_user"+ db_path = tmp_path / get_user_database_filename(username)+ db_path.parent.mkdir(parents=True, exist_ok=True)+ db_path.touch()++ with patch.object(manager, "_get_user_db_path", return_value=db_path):+ with patch(+ "local_deep_research.database.encrypted_db.get_key_from_password"+ ) as mock_derive:+ mock_derive.return_value = b"\x00" * 32++ try:+ manager.open_user_database(username, "password123")+ except Exception:+ pass # May fail later; we verify key derivation happened++ mock_derive.assert_called_once()++ @patch("local_deep_research.database.encrypted_db.get_data_directory")+ def test_metrics_session_derives_key_before_file_check(+ self, mock_data_dir, tmp_path+ ):+ """create_thread_safe_session_for_metrics derives key before db check."""+ from local_deep_research.database.encrypted_db import DatabaseManager++ mock_data_dir.return_value = tmp_path++ with patch.object(+ DatabaseManager, "_check_encryption_available", return_value=True+ ):+ manager = DatabaseManager()++ with patch(+ "local_deep_research.database.encrypted_db.get_key_from_password"+ ) as mock_derive:+ mock_derive.return_value = b"\x00" * 32++ with pytest.raises(ValueError, match="No database found"):+ manager.create_thread_safe_session_for_metrics(+ "nonexistent_user", "password123"+ )++ mock_derive.assert_called_once()++ @patch("local_deep_research.database.encrypted_db.get_data_directory")+ def test_salt_warning_not_called_for_nonexistent_db(+ self, mock_data_dir, tmp_path+ ):+ """has_per_database_salt not called when db doesn't exist."""+ from local_deep_research.database.encrypted_db import DatabaseManager++ mock_data_dir.return_value = tmp_path++ with patch.object(+ DatabaseManager, "_check_encryption_available", return_value=True+ ):+ manager = DatabaseManager()++ with (+ patch(+ "local_deep_research.database.encrypted_db.get_key_from_password"+ ) as mock_derive,+ patch(+ "local_deep_research.database.encrypted_db.has_per_database_salt"+ ) as mock_salt,+ ):+ mock_derive.return_value = b"\x00" * 32++ with pytest.raises(ValueError, match="No database found"):+ manager.create_thread_safe_session_for_metrics(+ "nonexistent_user", "password123"+ )++ # has_per_database_salt must NOT be called for non-existent db+ mock_salt.assert_not_called()diff --git a/tests/security/test_url_validator_behavior.py b/tests/security/test_url_validator_behavior.pyindex a32e0ffec1..ba5e638cef 100644--- a/tests/security/test_url_validator_behavior.py+++ b/tests/security/test_url_validator_behavior.py@@ -658,6 +658,188 @@ class TestIsSafeRedirectUrl:)+class TestIsSafeRedirectUrlBypassVectors:+ """Tests for bypass vectors in redirect URL validation."""++ def test_triple_slash_bypass_blocked(self):+ """Triple-slash bypass (///evil.com) is blocked."""+ from local_deep_research.security.url_validator import URLValidator++ assert (+ URLValidator.is_safe_redirect_url(+ "///evil.com", "http://example.com/"+ )+ is False+ )++ def test_protocol_relative_bypass_blocked(self):+ """Protocol-relative URL (//evil.com) is blocked."""+ from local_deep_research.security.url_validator import URLValidator++ assert (+ URLValidator.is_safe_redirect_url(+ "//evil.com", "http://example.com/"+ )+ is False+ )++ def test_encoded_protocol_relative_bypass_blocked(self):+ """URL-encoded protocol-relative URL is blocked."""+ from local_deep_research.security.url_validator import URLValidator++ assert (+ URLValidator.is_safe_redirect_url(+ "%2f%2fevil.com", "http://example.com/"+ )+ is False+ )++ def test_backslash_bypass_blocked(self):+ """Backslash bypass is blocked."""+ from local_deep_research.security.url_validator import URLValidator++ assert (+ URLValidator.is_safe_redirect_url(+ "\\\\evil.com", "http://example.com/"+ )+ is False+ )++ def test_single_backslash_blocked(self):+ """Single backslash bypass is blocked."""+ from local_deep_research.security.url_validator import URLValidator++ assert (+ URLValidator.is_safe_redirect_url(+ "\\evil.com", "http://example.com/"+ )+ is False+ )++ def test_encoded_backslash_blocked(self):+ """URL-encoded backslash is blocked."""+ from local_deep_research.security.url_validator import URLValidator++ # %5c is encoded backslash+ assert (+ URLValidator.is_safe_redirect_url(+ "%5cevil.com", "http://example.com/"+ )+ is False+ )++ def test_valid_relative_path_still_works(self):+ """Valid relative paths still work after security fixes."""+ from local_deep_research.security.url_validator import URLValidator++ assert (+ URLValidator.is_safe_redirect_url(+ "/dashboard", "http://example.com/"+ )+ is True+ )++ def test_valid_relative_path_with_query(self):+ """Valid relative paths with query params still work."""+ from local_deep_research.security.url_validator import URLValidator++ assert (+ URLValidator.is_safe_redirect_url(+ "/search?q=test", "http://example.com/"+ )+ is True+ )++ def test_valid_same_host_absolute_url(self):+ """Valid same-host absolute URL still works."""+ from local_deep_research.security.url_validator import URLValidator++ assert (+ URLValidator.is_safe_redirect_url(+ "http://example.com/page", "http://example.com/"+ )+ is True+ )++ def test_different_host_blocked(self):+ """Different host is still blocked."""+ from local_deep_research.security.url_validator import URLValidator++ assert (+ URLValidator.is_safe_redirect_url(+ "http://evil.com/page", "http://example.com/"+ )+ is False+ )++ def test_https_different_host_blocked(self):+ """HTTPS to different host is blocked."""+ from local_deep_research.security.url_validator import URLValidator++ assert (+ URLValidator.is_safe_redirect_url(+ "https://evil.com/page", "http://example.com/"+ )+ is False+ )++ def test_path_traversal_blocked(self):+ """Path traversal attempt with /../admin is blocked."""+ from local_deep_research.security.url_validator import URLValidator++ assert (+ URLValidator.is_safe_redirect_url(+ "/../admin", "http://example.com/"+ )+ is False+ )++ def test_encoded_crlf_blocked(self):+ """Encoded CRLF injection (%0d%0a) is blocked after URL decoding."""+ from local_deep_research.security.url_validator import URLValidator++ assert (+ URLValidator.is_safe_redirect_url(+ "/path%0d%0aSet-Cookie:evil", "http://example.com/"+ )+ is False+ )++ def test_double_dot_in_filename_allowed(self):+ """Legitimate filenames containing '..' are not treated as path traversal."""+ from local_deep_research.security.url_validator import URLValidator++ # '..' in a filename is not a traversal pattern+ assert (+ URLValidator.is_safe_redirect_url(+ "/my..page", "http://example.com/"+ )+ is True+ )++ def test_double_dot_in_query_string_allowed(self):+ """Query strings containing '..' are not treated as path traversal."""+ from local_deep_research.security.url_validator import URLValidator++ assert (+ URLValidator.is_safe_redirect_url(+ "/search?q=range..10", "http://example.com/"+ )+ is True+ )++ def test_null_byte_blocked(self):+ """Null bytes in redirect URLs are blocked."""+ from local_deep_research.security.url_validator import URLValidator++ assert (+ URLValidator.is_safe_redirect_url(+ "/path%00evil", "http://example.com/"+ )+ is False+ )++class TestURLValidationErrorClass:"""Tests for URLValidationError exception."""diff --git a/tests/web/auth/test_auth_routes.py b/tests/web/auth/test_auth_routes.pyindex ff5206d1fb..cd543afeab 100644--- a/tests/web/auth/test_auth_routes.py+++ b/tests/web/auth/test_auth_routes.py@@ -1045,3 +1045,115 @@ class TestRedirectPathExtraction:)assert response.status_code == 302assert response.location.endswith("/")+++class TestRegistrationTimingAttackPrevention:+ """Tests for registration timing attack prevention.++ These tests verify that the registration flow follows OWASP best practices:+ - Generic error messages (prevent content-based enumeration)+ - IntegrityError handling (catches race conditions with generic error + rollback)+ """++ def test_generic_error_message_for_duplicate_username(self):+ """Verify duplicate username returns generic error message (OWASP requirement)."""+ from unittest.mock import patch++ app = Flask(__name__)+ app.secret_key = "test"+ app.config["WTF_CSRF_ENABLED"] = False++ with (+ patch(+ "local_deep_research.web.auth.routes.load_server_config"+ ) as mock_config,+ patch("local_deep_research.web.auth.routes.db_manager") as mock_db,+ patch(+ "local_deep_research.web.auth.routes.render_template"+ ) as mock_render,+ patch("local_deep_research.web.auth.routes.flash") as mock_flash,+ ):+ mock_config.return_value = {"allow_registrations": True}+ mock_db.user_exists.return_value = True # User already exists+ mock_db.has_encryption = True+ mock_render.return_value = "Register Page"++ from local_deep_research.web.auth.routes import auth_bp++ app.register_blueprint(auth_bp)++ with app.test_client() as client:+ response = client.post(+ "/auth/register",+ data={+ "username": "existinguser",+ "password": "TestPassword123!",+ "confirm_password": "TestPassword123!",+ "acknowledge": "true",+ },+ )++ assert response.status_code == 400+ mock_flash.assert_any_call(+ "Registration failed. Please try a different username.",+ "error",+ )++ def test_integrity_error_returns_generic_message(self):+ """Verify IntegrityError (race condition) returns generic error (400 not 500)."""+ from unittest.mock import MagicMock, patch+ from sqlalchemy.exc import IntegrityError++ app = Flask(__name__)+ app.secret_key = "test"+ app.config["WTF_CSRF_ENABLED"] = False++ with (+ patch(+ "local_deep_research.web.auth.routes.load_server_config"+ ) as mock_config,+ patch("local_deep_research.web.auth.routes.db_manager") as mock_db,+ patch(+ "local_deep_research.web.auth.routes.get_auth_db_session"+ ) as mock_auth_db,+ patch(+ "local_deep_research.web.auth.routes.render_template"+ ) as mock_render,+ patch("local_deep_research.web.auth.routes.flash") as mock_flash,+ ):+ mock_config.return_value = {"allow_registrations": True}+ mock_db.user_exists.return_value = False # Passes pre-check+ mock_db.has_encryption = True+ mock_render.return_value = "Register Page"++ # Simulate IntegrityError on commit+ mock_session = MagicMock()+ mock_session.add = MagicMock()+ mock_session.commit = MagicMock(+ side_effect=IntegrityError("statement", "params", "orig")+ )+ mock_session.rollback = MagicMock()+ mock_session.close = MagicMock()+ mock_auth_db.return_value = mock_session++ from local_deep_research.web.auth.routes import auth_bp++ app.register_blueprint(auth_bp)++ with app.test_client() as client:+ response = client.post(+ "/auth/register",+ data={+ "username": "racecondition_user",+ "password": "TestPassword123!",+ "confirm_password": "TestPassword123!",+ "acknowledge": "true",+ },+ )++ assert response.status_code == 400+ mock_flash.assert_any_call(+ "Registration failed. Please try a different username.",+ "error",+ )+ mock_session.rollback.assert_called_once()diff --git a/tests/web/auth/test_decorators.py b/tests/web/auth/test_decorators.pyindex 83288a99f4..44e01e32b8 100644--- a/tests/web/auth/test_decorators.py+++ b/tests/web/auth/test_decorators.py@@ -391,3 +391,43 @@ class TestSafeRedirectToLogin:response = _safe_redirect_to_login()assert response.status_code == 302assert "next=" not in response.location++ def test_safe_url_includes_next_param(self):+ """Safe URLs should include the next parameter."""+ app = self._setup_app_with_login_required_route()++ with patch("local_deep_research.web.auth.decorators.db_manager"):+ from local_deep_research.web.auth.decorators import (+ _safe_redirect_to_login,+ )++ with app.test_request_context(+ "/dashboard",+ base_url="http://localhost:5000",+ ):+ response = _safe_redirect_to_login()+ assert response.status_code == 302+ assert "next=" in response.location++ def test_stale_session_redirect_uses_safe_redirect(self):+ """When DB connection is lost, redirect should use _safe_redirect_to_login."""+ app = self._setup_app_with_login_required_route()++ with patch(+ "local_deep_research.web.auth.decorators.db_manager"+ ) as mock_db_manager:+ mock_db_manager.is_user_connected.return_value = False++ from local_deep_research.web.auth.decorators import login_required++ @app.route("/protected")+ @login_required+ def protected():+ return "Protected"++ with app.test_client() as client:+ with client.session_transaction() as sess:+ sess["username"] = "testuser"+ response = client.get("/protected")+ assert response.status_code == 302+ assert "/auth/login" in response.location