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.

security: defense-in-depth for post-login redirect (CWE-601) (#2521)

LearningCircuitf11675c0685b
diff --git a/src/local_deep_research/security/url_validator.py b/src/local_deep_research/security/url_validator.py
index ec46b9078b..fc14559ba1 100644
--- a/src/local_deep_research/security/url_validator.py
+++ b/src/local_deep_research/security/url_validator.py
@@ -411,11 +411,50 @@ 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.netloc
)
+ @staticmethod
+ def get_safe_redirect_path(target: str, host_url: str) -> Optional[str]:
+ """
+ Validate a redirect target and return its path-only form.
+
+ Combines is_safe_redirect_url validation with defense-in-depth path
+ extraction. The target is resolved against host_url via urljoin, then
+ only the path, query, and fragment are returned. This ensures that
+ even a hypothetical validator bypass cannot cause an external redirect,
+ since path-only URLs always resolve to the same host.
+
+ Args:
+ target: The redirect URL to validate (can be relative or absolute)
+ host_url: The application's host URL (e.g., request.host_url)
+
+ Returns:
+ The safe path string (e.g., "/dashboard?tab=settings") if the
+ target is valid, or None if the target is unsafe.
+ """
+ if not URLValidator.is_safe_redirect_url(target, host_url):
+ return None
+
+ resolved = urljoin(host_url, target)
+ parsed = urlparse(resolved)
+ safe_path = parsed.path or "/"
+ if parsed.query:
+ safe_path += "?" + parsed.query
+ if parsed.fragment:
+ safe_path += "#" + parsed.fragment
+
+ # Final assertion: the constructed path must be relative (no netloc).
+ # This is always true by construction but guards against future bugs.
+ if urlparse(safe_path).netloc:
+ return None
+ return safe_path
+
def get_javascript_url_validator() -> str:
"""
diff --git a/src/local_deep_research/web/auth/routes.py b/src/local_deep_research/web/auth/routes.py
index cf1d1c47db..dd770ad4aa 100644
--- a/src/local_deep_research/web/auth/routes.py
+++ b/src/local_deep_research/web/auth/routes.py
@@ -27,6 +27,8 @@ from ...utilities.threading_utils import thread_context, thread_with_app_context
from .session_manager import SessionManager
from ..server_config import load_server_config
from ..utils.rate_limiter import login_limit, registration_limit
+from urllib.parse import urlparse
+
from ...security.url_validator import URLValidator
auth_bp = Blueprint("auth", __name__, url_prefix="/auth")
@@ -138,17 +140,13 @@ def login():
)
thread.start()
- # Redirect to original requested page or dashboard
next_page = request.args.get("next", "")
-
- # Security: URLValidator.is_safe_redirect_url() validates that the target URL
- # has http/https scheme and netloc matches the application host, preventing
- # open redirect attacks (CWE-601). CodeQL doesn't recognize custom sanitizers.
- if next_page and URLValidator.is_safe_redirect_url(
- next_page, request.host_url
- ):
- return redirect(next_page) # codeql[py/url-redirection]
-
+ safe_path = URLValidator.get_safe_redirect_path(next_page, request.host_url)
+ if safe_path:
+ safe_path = safe_path.replace("\\", "/")
+ parsed = urlparse(safe_path)
+ if not parsed.scheme and not parsed.netloc:
+ return redirect(safe_path)
return redirect(url_for("index"))
diff --git a/tests/security/test_url_validator_extended.py b/tests/security/test_url_validator_extended.py
index 43bd3f244c..9c993dfb6f 100644
--- a/tests/security/test_url_validator_extended.py
+++ b/tests/security/test_url_validator_extended.py
@@ -834,6 +834,23 @@ class TestIsSafeRedirectUrlExtended:
def test_root_path(self):
assert URLValidator.is_safe_redirect_url("/", self.HOST) is True
+ # -- double-slash path bypass --
+ def test_double_slash_in_absolute_url_path_blocked(self):
+ """http://host//evil.com/path has same netloc but // path -- blocked."""
+ assert (
+ URLValidator.is_safe_redirect_url(
+ "http://example.com//evil.com/path", self.HOST
+ )
+ is False
+ )
+
+ def test_dot_slash_double_slash_blocked(self):
+ """/.//evil.com resolves to //evil.com path -- blocked."""
+ assert (
+ URLValidator.is_safe_redirect_url("/.//evil.com", self.HOST)
+ is False
+ )
+
# -- HTTPS host URL variations --
def test_https_host_with_http_relative(self):
"""Relative path from HTTPS host stays on same host."""
@@ -854,3 +871,205 @@ class TestIsSafeRedirectUrlExtended:
)
is False
)
+
+
+# ---------------------------------------------------------------------------
+# get_safe_redirect_path -- defense-in-depth path extraction
+# ---------------------------------------------------------------------------
+class TestGetSafeRedirectPath:
+ """
+ Tests for get_safe_redirect_path which validates a redirect target
+ and returns only its path+query+fragment, preventing external redirects
+ even if the validator were bypassed.
+ """
+
+ HOST = "http://example.com/"
+
+ # -- unsafe targets return None --
+
+ def test_returns_none_for_external_url(self):
+ assert (
+ URLValidator.get_safe_redirect_path(
+ "http://evil.com/steal", self.HOST
+ )
+ is None
+ )
+
+ def test_returns_none_for_empty_string(self):
+ assert URLValidator.get_safe_redirect_path("", self.HOST) is None
+
+ def test_returns_none_for_none(self):
+ assert URLValidator.get_safe_redirect_path(None, self.HOST) is None
+
+ def test_returns_none_for_protocol_relative(self):
+ assert (
+ URLValidator.get_safe_redirect_path("//evil.com/path", self.HOST)
+ is None
+ )
+
+ def test_returns_none_for_path_traversal(self):
+ assert (
+ URLValidator.get_safe_redirect_path(
+ "/../../../etc/passwd", self.HOST
+ )
+ is None
+ )
+
+ def test_returns_none_for_crlf_injection(self):
+ assert (
+ URLValidator.get_safe_redirect_path(
+ "/path\r\nSet-Cookie: evil=1", self.HOST
+ )
+ is None
+ )
+
+ def test_returns_none_for_javascript_scheme(self):
+ assert (
+ URLValidator.get_safe_redirect_path(
+ "javascript:alert(1)", self.HOST
+ )
+ is None
+ )
+
+ def test_double_slash_path_bypass_returns_none(self):
+ """http://host//evil.com/path passes netloc check but has // path."""
+ assert (
+ URLValidator.get_safe_redirect_path(
+ "http://example.com//evil.com/path", self.HOST
+ )
+ is None
+ )
+
+ # -- simple relative paths --
+
+ def test_relative_path(self):
+ assert (
+ URLValidator.get_safe_redirect_path("/dashboard", self.HOST)
+ == "/dashboard"
+ )
+
+ def test_root_path(self):
+ assert URLValidator.get_safe_redirect_path("/", self.HOST) == "/"
+
+ def test_nested_path(self):
+ assert (
+ URLValidator.get_safe_redirect_path("/a/b/c", self.HOST) == "/a/b/c"
+ )
+
+ # -- absolute same-host URLs have scheme/host stripped --
+
+ def test_absolute_same_host_extracts_path(self):
+ result = URLValidator.get_safe_redirect_path(
+ "http://example.com/dashboard", self.HOST
+ )
+ assert result == "/dashboard"
+
+ def test_absolute_same_host_https(self):
+ host = "https://example.com/"
+ result = URLValidator.get_safe_redirect_path(
+ "https://example.com/page", host
+ )
+ assert result == "/page"
+
+ def test_absolute_same_host_with_port(self):
+ host = "http://localhost:5000/"
+ result = URLValidator.get_safe_redirect_path(
+ "http://localhost:5000/settings", host
+ )
+ assert result == "/settings"
+
+ # -- query string preservation --
+
+ def test_preserves_query_string(self):
+ assert (
+ URLValidator.get_safe_redirect_path("/search?q=hello", self.HOST)
+ == "/search?q=hello"
+ )
+
+ def test_preserves_multiple_query_params(self):
+ assert (
+ URLValidator.get_safe_redirect_path(
+ "/search?q=hello&page=2&sort=date", self.HOST
+ )
+ == "/search?q=hello&page=2&sort=date"
+ )
+
+ def test_absolute_url_preserves_query(self):
+ result = URLValidator.get_safe_redirect_path(
+ "http://example.com/research?id=123&tab=sources", self.HOST
+ )
+ assert result == "/research?id=123&tab=sources"
+
+ def test_preserves_encoded_chars_in_query(self):
+ """Percent-encoded characters in query should be preserved as-is."""
+ assert (
+ URLValidator.get_safe_redirect_path(
+ "/search?q=hello%26world", self.HOST
+ )
+ == "/search?q=hello%26world"
+ )
+
+ # -- fragment preservation --
+
+ def test_preserves_fragment(self):
+ assert (
+ URLValidator.get_safe_redirect_path("/page#section", self.HOST)
+ == "/page#section"
+ )
+
+ def test_preserves_query_and_fragment(self):
+ assert (
+ URLValidator.get_safe_redirect_path(
+ "/page?tab=info#details", self.HOST
+ )
+ == "/page?tab=info#details"
+ )
+
+ # -- empty path edge cases (the bugs this method fixes) --
+
+ def test_absolute_url_no_trailing_slash_returns_root(self):
+ """http://example.com (no path) should return '/' not empty string."""
+ host = "http://example.com/"
+ result = URLValidator.get_safe_redirect_path("http://example.com", host)
+ assert result == "/"
+
+ def test_absolute_url_with_trailing_slash(self):
+ result = URLValidator.get_safe_redirect_path(
+ "http://example.com/", self.HOST
+ )
+ assert result == "/"
+
+ # -- relative paths without leading slash (resolved via urljoin) --
+
+ def test_relative_no_leading_slash_resolved(self):
+ """'dashboard' should resolve to '/dashboard' not stay as 'dashboard'."""
+ result = URLValidator.get_safe_redirect_path("dashboard", self.HOST)
+ assert result == "/dashboard"
+
+ def test_dot_relative_resolved(self):
+ """'./dashboard' should resolve to '/dashboard'."""
+ result = URLValidator.get_safe_redirect_path("./dashboard", self.HOST)
+ assert result == "/dashboard"
+
+ # -- special characters in paths --
+
+ def test_path_with_encoded_spaces(self):
+ assert (
+ URLValidator.get_safe_redirect_path("/my%20page", self.HOST)
+ == "/my%20page"
+ )
+
+ def test_path_with_tilde(self):
+ assert (
+ URLValidator.get_safe_redirect_path("/~user/page", self.HOST)
+ == "/~user/page"
+ )
+
+ def test_path_with_plus_in_query(self):
+ """Plus signs in query strings should be preserved."""
+ assert (
+ URLValidator.get_safe_redirect_path(
+ "/search?q=hello+world", self.HOST
+ )
+ == "/search?q=hello+world"
+ )
diff --git a/tests/web/auth/test_auth_routes.py b/tests/web/auth/test_auth_routes.py
index 6bb915f13f..ff5206d1fb 100644
--- a/tests/web/auth/test_auth_routes.py
+++ b/tests/web/auth/test_auth_routes.py
@@ -870,3 +870,178 @@ class TestOpenRedirectPrevention:
# Encoded path traversal is blocked
assert response.status_code == 302
assert "admin" not in response.location
+
+
+class TestRedirectPathExtraction:
+ """Tests for defense-in-depth path extraction from redirect URLs.
+
+ After is_safe_redirect_url validates same-host, the code extracts only
+ the path+query+fragment via urljoin+urlparse. These tests verify that
+ absolute URLs are correctly converted to relative paths and edge cases
+ are handled safely.
+ """
+
+ def _make_app_and_login(self, next_param):
+ """Helper: create app, register auth blueprint, POST login with next param."""
+ 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(
+ f"/auth/login?next={next_param}",
+ data={"username": "testuser", "password": "password123"},
+ )
+ return response
+
+ def test_absolute_same_origin_url_extracts_path(self):
+ """Absolute same-origin URL should redirect to path only."""
+ response = self._make_app_and_login("http://localhost/dashboard")
+ assert response.status_code == 302
+ assert response.location.endswith("/dashboard")
+ assert "localhost" not in response.location.split("/dashboard")[0]
+
+ def test_preserves_query_string(self):
+ """Query string in next param should be preserved in redirect."""
+ # URL-encode the next value so &page=2 isn't split as a separate param
+ from urllib.parse import quote
+
+ response = self._make_app_and_login(
+ quote("/search?q=test&page=2", safe="")
+ )
+ assert response.status_code == 302
+ assert "/search?q=test&page=2" in response.location
+
+ def test_preserves_fragment(self):
+ """Fragment in next param should be preserved in redirect."""
+ response = self._make_app_and_login("/dashboard%23section")
+ assert response.status_code == 302
+ assert "/dashboard" in response.location
+
+ def test_absolute_url_with_query_extracts_path_and_query(self):
+ """Absolute URL with query should extract path+query only."""
+ from urllib.parse import quote
+
+ response = self._make_app_and_login(
+ quote("http://localhost/research?id=123&tab=sources", safe="")
+ )
+ assert response.status_code == 302
+ assert "/research?id=123&tab=sources" in response.location
+ # Must not contain the scheme/host
+ assert "http://localhost" not in response.location
+
+ def test_no_next_param_redirects_to_index(self):
+ """Missing next param should redirect to index."""
+ 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",
+ data={"username": "testuser", "password": "password123"},
+ )
+ assert response.status_code == 302
+ assert response.location.endswith("/")