~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(security): block path traversal in redirects and harden auth flow (#2213)
LearningCircuitf7af822253b6
diff --git a/src/local_deep_research/database/encrypted_db.py b/src/local_deep_research/database/encrypted_db.pyindex fe98f91204..2d37af9ef3 100644--- a/src/local_deep_research/database/encrypted_db.py+++ b/src/local_deep_research/database/encrypted_db.py@@ -450,6 +450,12 @@ 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():logger.error(f"No database found for user {username}")return None@@ -463,9 +469,6 @@ class DatabaseManager:f"fully functional but are less resistant to multi-target attacks.")- # Pre-derive key before closures to avoid capturing plaintext password- hex_key = get_key_from_password(password, db_path=db_path).hex()-# Create connection string - use regular SQLite when SQLCipher not availableif self.has_encryption:@@ -729,12 +732,24 @@ class DatabaseManager:"""db_path = self._get_user_db_path(username)- if not db_path.exists():- raise ValueError(f"No database found for user {username}")+ # Warn if this is a legacy database without per-database salt+ if self.has_encryption and not has_per_database_salt(db_path):+ logger.warning(+ f"Database for user '{username}' uses a legacy shared salt "+ f"(deprecated). For improved security, consider creating a new "+ f"account to get a per-database salt. Legacy databases remain "+ 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 closureshex_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 ba2507de59..ec46b9078b 100644--- a/src/local_deep_research/security/url_validator.py+++ b/src/local_deep_research/security/url_validator.py@@ -355,6 +355,14 @@ class URLValidator:Uses the standard Flask pattern from:https://github.com/fengsp/flask-snippets/blob/master/security/redirect_back.py+ Security protections implemented:+ - CRLF injection prevention+ - Protocol-relative URL bypass (//evil.com)+ - Triple-slash bypass (///evil.com)+ - URL-encoded bypass attempts+ - Backslash bypass (treated as forward slash by some browsers)+ - Path traversal blocking+Args:target: The redirect URL to validate (can be relative or absolute)host_url: The application's host URL (e.g., request.host_url)@@ -370,6 +378,37 @@ class URLValidator:logger.warning("CRLF injection attempt detected in redirect URL")return False+ # 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)+ except Exception:+ decoded_target = target++ # Check for backslash (treated as forward slash by some browsers)+ # Prevents \evil.com and \\evil.com bypasses+ if "\\" in decoded_target:+ logger.warning("Backslash detected in redirect URL")+ return False++ # Check for protocol-relative URLs before stripping slashes+ # //evil.com would be treated as absolute URL by urljoin()+ if decoded_target.startswith("//"):+ 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:+ logger.warning(+ "Path traversal detected in redirect URL: %s", target+ )+ return False+ref_url = urlparse(host_url)test_url = urlparse(urljoin(host_url, target))return (diff --git a/src/local_deep_research/web/auth/decorators.py b/src/local_deep_research/web/auth/decorators.pyindex 04bb0462c0..b47086ee5f 100644--- a/src/local_deep_research/web/auth/decorators.py+++ b/src/local_deep_research/web/auth/decorators.py@@ -8,6 +8,25 @@ from flask import g, jsonify, redirect, request, session, url_forfrom loguru import loggerfrom ...database.encrypted_db import db_manager+from ...security.url_validator import URLValidator+++def _safe_redirect_to_login():+ """+ Redirect to login with validated next parameter.++ Uses request.url as next parameter only if it passes+ security validation to prevent open redirect vulnerabilities.++ Returns:+ Flask redirect response+ """+ next_url = request.url+ # Validate that next URL is safe before using it+ if URLValidator.is_safe_redirect_url(next_url, request.host_url):+ return redirect(url_for("auth.login", next=next_url))+ # Fall back to login without next parameter if validation fails+ return redirect(url_for("auth.login"))def login_required(f):@@ -27,7 +46,7 @@ def login_required(f):"/settings/api/"):return jsonify({"error": "Authentication required"}), 401- return redirect(url_for("auth.login", next=request.url))+ return _safe_redirect_to_login()# Check if we have an active database connectionusername = session["username"]@@ -42,7 +61,7 @@ def login_required(f):):return jsonify({"error": "Database connection required"}), 401session.clear()- return redirect(url_for("auth.login", next=request.url))+ return _safe_redirect_to_login()return f(*args, **kwargs)diff --git a/src/local_deep_research/web/auth/routes.py b/src/local_deep_research/web/auth/routes.pyindex 14f81eb60f..7248315d14 100644--- a/src/local_deep_research/web/auth/routes.py+++ b/src/local_deep_research/web/auth/routes.py@@ -21,6 +21,7 @@ from loguru import loggerfrom ...database.auth_db import get_auth_db_sessionfrom ...database.encrypted_db import db_managerfrom ...database.models.auth import User+from sqlalchemy.exc import IntegrityErrorfrom ...utilities.threading_utils import thread_context, thread_with_app_contextfrom .session_manager import SessionManagerfrom ..server_config import load_server_config@@ -308,6 +309,12 @@ def register():# Check if user already exists# Use generic error message to prevent account enumeration+ # Note: While this creates a minor timing difference, it's acceptable because:+ # 1. Rate limiting prevents automated timing analysis+ # 2. Generic error message prevents content-based enumeration+ # 3. Local database query timing is minimal (no network calls)+ # 4. Better UX with immediate feedback outweighs minor timing risk+ # See: https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.htmlif username and db_manager.user_exists(username):errors.append("Registration failed. Please try a different username.")@@ -324,6 +331,17 @@ def register():new_user = User(username=username)auth_db.add(new_user)auth_db.commit()+ except IntegrityError:+ # Catch duplicate username specifically (race condition case)+ # This handles the edge case where two requests for the same username+ # pass the user_exists() check simultaneously+ logger.warning(f"Duplicate username attempted: {username}")+ auth_db.rollback()+ auth_db.close()+ flash("Registration failed. Please try a different username.", "error")+ return render_template(+ "auth/register.html", has_encryption=db_manager.has_encryption+ ), 400except Exception:logger.exception(f"Registration failed for {username}")auth_db.rollback()diff --git a/tests/security/test_url_validator_behavior.py b/tests/security/test_url_validator_behavior.pyindex 83f2a1d8da..a32e0ffec1 100644--- a/tests/security/test_url_validator_behavior.py+++ b/tests/security/test_url_validator_behavior.py@@ -604,6 +604,59 @@ class TestIsSafeRedirectUrl:is False)+ def test_path_traversal_blocked(self):+ """Path traversal in redirect URL path is blocked."""+ from local_deep_research.security.url_validator import URLValidator++ assert (+ URLValidator.is_safe_redirect_url(+ "/../../../etc/passwd", "http://example.com/"+ )+ is False+ )++ def test_relative_path_traversal_blocked(self):+ """Relative path traversal 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_path_traversal_blocked(self):+ """URL-encoded path traversal (%2e%2e) is blocked."""+ from local_deep_research.security.url_validator import URLValidator++ assert (+ URLValidator.is_safe_redirect_url(+ "%2e%2e/admin", "http://example.com/"+ )+ is False+ )++ def test_mid_path_traversal_blocked(self):+ """Mid-path traversal (/foo/../bar) is blocked."""+ from local_deep_research.security.url_validator import URLValidator++ assert (+ URLValidator.is_safe_redirect_url(+ "/foo/../bar", "http://example.com/"+ )+ is False+ )++ def test_dotdot_in_query_param_not_blocked(self):+ """Double dots in query parameters should NOT trigger path traversal blocking."""+ from local_deep_research.security.url_validator import URLValidator++ assert (+ URLValidator.is_safe_redirect_url(+ "/search?q=foo..bar", "http://example.com/"+ )+ is True+ )+class TestURLValidationErrorClass:"""Tests for URLValidationError exception."""diff --git a/tests/web/auth/test_auth_routes.py b/tests/web/auth/test_auth_routes.pyindex 1285b0384c..6bb915f13f 100644--- a/tests/web/auth/test_auth_routes.py+++ b/tests/web/auth/test_auth_routes.py@@ -731,13 +731,12 @@ class TestOpenRedirectPrevention:assert response.status_code == 302assert "/dashboard" in response.location- def test_path_traversal_stays_same_host(self):- """Path traversal in next param is treated as same-host redirect.+ def test_path_traversal_blocked(self):+ """Path traversal in next param is blocked by is_safe_redirect_url.- The is_safe_redirect_url validator uses urljoin which resolves- path traversal (e.g. /../../../etc/passwd -> /etc/passwd) to a- same-host path. Since it remains same-host, the redirect is- considered safe by the current implementation.+ The validator detects '..' in the URL path component and rejects+ it, so login falls back to the index page instead of redirecting+ to the traversal target."""app = Flask(__name__)app.secret_key = "test"@@ -800,6 +799,74 @@ class TestOpenRedirectPrevention:data={"username": "testuser", "password": "password123"},)- # Path traversal resolves to same-host via urljoin,- # so is_safe_redirect_url considers it safe and allows redirect+ # Path traversal is blocked by is_safe_redirect_url,+ # so login succeeds but redirects to index (fallback)assert response.status_code == 302+ assert "etc/passwd" not in response.location++ def test_encoded_path_traversal_blocked(self):+ """URL-encoded path traversal (%2e%2e) in next param is blocked."""+ app = Flask(__name__)+ app.secret_key = "test"+ app.config["WTF_CSRF_ENABLED"] = False++ @app.route("/")+ def index():+ return "Index"++ mock_engine = MagicMock()+ mock_session = MagicMock()+ mock_settings_manager = MagicMock()+ mock_settings_manager.db_version_matches_package.return_value = True++ 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_manager,+ patch(+ "local_deep_research.web.auth.routes.session_manager"+ ) as mock_session_manager,+ patch(+ "local_deep_research.web.auth.routes.get_auth_db_session"+ ) as mock_auth_db,+ patch(+ "local_deep_research.database.temp_auth.temp_auth_store"+ ) as mock_temp_auth,+ patch(+ "local_deep_research.database.session_passwords.session_password_store"+ ),+ patch(+ "local_deep_research.settings.manager.SettingsManager"+ ) as mock_settings_cls,+ patch(+ "local_deep_research.database.library_init.initialize_library_for_user"+ ),+ patch(+ "local_deep_research.news.subscription_manager.scheduler.get_news_scheduler"+ ),+ patch("local_deep_research.database.models.ProviderModel"),+ ):+ mock_config.return_value = {"allow_registrations": True}+ mock_db_manager.open_user_database.return_value = mock_engine+ mock_db_manager.get_session.return_value = mock_session+ mock_session_manager.create_session.return_value = "session_123"+ mock_auth_db.return_value = MagicMock()+ mock_settings_cls.return_value = mock_settings_manager+ mock_temp_auth.store_auth.return_value = "test_auth_token"++ 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/login?next=%2e%2e/admin",+ data={"username": "testuser", "password": "password123"},+ )++ # Encoded path traversal is blocked+ assert response.status_code == 302+ assert "admin" not in response.locationdiff --git a/tests/web/auth/test_decorators.py b/tests/web/auth/test_decorators.pyindex 14ea6592ca..83288a99f4 100644--- a/tests/web/auth/test_decorators.py+++ b/tests/web/auth/test_decorators.py@@ -6,10 +6,11 @@ Tests cover:- current_user function- get_current_db_session function- inject_current_user function+- _safe_redirect_to_login function"""from unittest.mock import Mock, patch-from flask import Flask, session, g+from flask import Blueprint, Flask, session, gclass TestLoginRequiredDecorator:@@ -312,3 +313,81 @@ class TestInjectCurrentUser:inject_current_user()# g.current_user should still be set for auth routesassert g.current_user == "testuser"+++class TestSafeRedirectToLogin:+ """Tests for _safe_redirect_to_login open redirect prevention."""++ def _setup_app_with_login_required_route(self):+ """Create a Flask app with auth blueprint and a protected route."""+ app = Flask(__name__)+ app.secret_key = "test"++ auth = Blueprint("auth", __name__)++ @auth.route("/login")+ def login():+ return "Login Page"++ app.register_blueprint(auth, url_prefix="/auth")+ return app++ def test_valid_same_host_next_url_is_preserved(self):+ """Valid same-host URL should be included as 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 login_required++ @app.route("/dashboard")+ @login_required+ def dashboard():+ return "Dashboard"++ with app.test_client() as client:+ response = client.get("/dashboard")+ assert response.status_code == 302+ location = response.location+ assert "/auth/login" in location+ assert "next=" in location++ def test_protocol_relative_url_rejected(self):+ """Protocol-relative URLs (//evil.com) should NOT appear in next param."""+ app = self._setup_app_with_login_required_route()++ with patch("local_deep_research.web.auth.decorators.db_manager"):+ with patch(+ "local_deep_research.web.auth.decorators.URLValidator"+ ) as mock_validator:+ # Simulate URLValidator rejecting the URL+ mock_validator.is_safe_redirect_url.return_value = False++ from local_deep_research.web.auth.decorators import (+ _safe_redirect_to_login,+ )++ with app.test_request_context(+ "//evil.com/steal-cookies",+ base_url="http://localhost:5000",+ ):+ response = _safe_redirect_to_login()+ assert response.status_code == 302+ # Should redirect to login WITHOUT next parameter+ assert "next=" not in response.location++ def test_path_traversal_url_rejected(self):+ """Path traversal in request URL should NOT appear in next param."""+ 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(+ "http://localhost:5000/../../../etc/passwd",+ base_url="http://localhost:5000",+ ):+ response = _safe_redirect_to_login()+ assert response.status_code == 302+ assert "next=" not in response.location