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.

refactor: Move URL validation to security module

LearningCircuita5626bcf1d45
diff --git a/src/local_deep_research/notifications/__init__.py b/src/local_deep_research/notifications/__init__.py
index 12c25fe627..bce1ed2f49 100644
--- a/src/local_deep_research/notifications/__init__.py
+++ b/src/local_deep_research/notifications/__init__.py
@@ -17,11 +17,8 @@ from .exceptions import (
from .service import NotificationService
from .manager import NotificationManager
from .templates import NotificationTemplate, EventType
-from .url_builder import (
- build_notification_url,
- validate_url,
- URLValidationError,
-)
+from .url_builder import build_notification_url
+from ..security.url_validator import URLValidator, URLValidationError
from .queue_helpers import (
send_queue_notification,
send_queue_failed_notification,
@@ -37,7 +34,7 @@ __all__ = [
"NotificationTemplate",
"EventType",
"build_notification_url",
- "validate_url",
+ "URLValidator",
"URLValidationError",
"send_queue_notification",
"send_queue_failed_notification",
diff --git a/src/local_deep_research/notifications/url_builder.py b/src/local_deep_research/notifications/url_builder.py
index f6dc225f20..6fedc79c97 100644
--- a/src/local_deep_research/notifications/url_builder.py
+++ b/src/local_deep_research/notifications/url_builder.py
@@ -9,79 +9,13 @@ Uses the existing security URL validator for consistency with the rest of the ap
"""
from typing import Optional
-from urllib.parse import urlparse
from loguru import logger
from ..security.url_builder import (
build_base_url_from_settings,
build_full_url,
)
-from ..security.url_validator import URLValidator
-
-
-class URLValidationError(ValueError):
- """Raised when URL construction fails validation."""
-
- pass
-
-
-def validate_url(url: str) -> bool:
- """
- Validate that a notification callback URL is well-formed and safe.
-
- This validates HTTP/HTTPS URLs that users will click on from notifications,
- not Apprise service URLs. Apprise URLs use different protocols like
- discord://, mailto://, etc. and are validated by Apprise itself.
-
- Args:
- url: HTTP/HTTPS callback URL to validate
-
- Returns:
- True if valid
-
- Raises:
- URLValidationError: If URL is invalid
- """
- if not url or not isinstance(url, str):
- raise URLValidationError("URL must be a non-empty string")
-
- try:
- parsed = urlparse(url)
-
- # Must have a scheme
- if not parsed.scheme:
- raise URLValidationError("URL must have a scheme (http or https)")
-
- # Must be http or https (notification callback URLs)
- if parsed.scheme not in ("http", "https"):
- raise URLValidationError(
- f"URL scheme must be http or https, got: {parsed.scheme}"
- )
-
- # Use the existing security URL validator for additional safety
- if not URLValidator.is_safe_url(url, require_scheme=True):
- raise URLValidationError(f"URL failed security validation: {url}")
-
- # Must have a netloc (hostname)
- if not parsed.netloc:
- raise URLValidationError("URL must have a hostname")
-
- # Check for obvious issues
- if parsed.netloc.startswith(".") or parsed.netloc.endswith("."):
- raise URLValidationError(f"Invalid hostname: {parsed.netloc}")
-
- # Path should be valid
- if parsed.path and not parsed.path.startswith("/"):
- raise URLValidationError(
- f"URL path must start with /: {parsed.path}"
- )
-
- return True
-
- except Exception as e:
- if isinstance(e, URLValidationError):
- raise
- raise URLValidationError(f"Failed to validate URL: {e}")
+from ..security.url_validator import URLValidator, URLValidationError
def build_notification_url(
@@ -147,9 +81,9 @@ def build_notification_url(
validate=False, # We'll validate with our own validator
)
- # Validate if requested using our own validator
+ # Validate if requested using the security module validator
if validate:
- validate_url(full_url)
+ URLValidator.validate_http_url(full_url)
return full_url
diff --git a/src/local_deep_research/security/url_validator.py b/src/local_deep_research/security/url_validator.py
index d9deb172cf..6deb12bb8e 100644
--- a/src/local_deep_research/security/url_validator.py
+++ b/src/local_deep_research/security/url_validator.py
@@ -11,6 +11,12 @@ from urllib.parse import urlparse
from loguru import logger
+class URLValidationError(ValueError):
+ """Raised when URL construction or validation fails."""
+
+ pass
+
+
class URLValidator:
"""Centralized URL validation for security."""
@@ -273,6 +279,69 @@ class URLValidator:
return None
+ @staticmethod
+ def validate_http_url(url: str) -> bool:
+ """
+ Validate that a callback URL is well-formed and safe for HTTP/HTTPS use.
+
+ This is stricter than is_safe_url() and specifically validates HTTP/HTTPS
+ URLs for use as application callbacks (e.g., in notifications, redirects).
+ It does NOT validate Apprise service URLs which use other protocols.
+
+ Args:
+ url: HTTP/HTTPS callback URL to validate
+
+ Returns:
+ True if valid
+
+ Raises:
+ URLValidationError: If URL is invalid
+ """
+ if not url or not isinstance(url, str):
+ raise URLValidationError("URL must be a non-empty string")
+
+ try:
+ parsed = urlparse(url)
+
+ # Must have a scheme
+ if not parsed.scheme:
+ raise URLValidationError(
+ "URL must have a scheme (http or https)"
+ )
+
+ # Must be http or https (callback URLs only)
+ if parsed.scheme not in ("http", "https"):
+ raise URLValidationError(
+ f"URL scheme must be http or https, got: {parsed.scheme}"
+ )
+
+ # Use the general security validator for additional safety
+ if not URLValidator.is_safe_url(url, require_scheme=True):
+ raise URLValidationError(
+ f"URL failed security validation: {url}"
+ )
+
+ # Must have a netloc (hostname)
+ if not parsed.netloc:
+ raise URLValidationError("URL must have a hostname")
+
+ # Check for obvious hostname issues
+ if parsed.netloc.startswith(".") or parsed.netloc.endswith("."):
+ raise URLValidationError(f"Invalid hostname: {parsed.netloc}")
+
+ # Path should be valid if present
+ if parsed.path and not parsed.path.startswith("/"):
+ raise URLValidationError(
+ f"URL path must start with /: {parsed.path}"
+ )
+
+ return True
+
+ except Exception as e:
+ if isinstance(e, URLValidationError):
+ raise
+ raise URLValidationError(f"Failed to validate URL: {e}")
+
def get_javascript_url_validator() -> str:
"""
diff --git a/tests/notifications/test_url_builder.py b/tests/notifications/test_url_builder.py
index 63fdaa99dd..ad262f56b4 100644
--- a/tests/notifications/test_url_builder.py
+++ b/tests/notifications/test_url_builder.py
@@ -5,9 +5,9 @@ Tests for notification URL builder.
import pytest
from unittest.mock import Mock
-from local_deep_research.notifications.url_builder import (
- build_notification_url,
- validate_url,
+from local_deep_research.notifications.url_builder import build_notification_url
+from local_deep_research.security.url_validator import (
+ URLValidator,
URLValidationError,
)
@@ -17,74 +17,84 @@ class TestValidateURL:
def test_valid_http_url(self):
"""Test validation accepts valid HTTP URLs."""
- assert validate_url("http://localhost:5000/path")
- assert validate_url("http://example.com/research/123")
- assert validate_url("http://192.168.1.100:8080/test")
+ assert URLValidator.validate_http_url("http://localhost:5000/path")
+ assert URLValidator.validate_http_url("http://example.com/research/123")
+ assert URLValidator.validate_http_url("http://192.168.1.100:8080/test")
def test_valid_https_url(self):
"""Test validation accepts valid HTTPS URLs."""
- assert validate_url("https://example.com/path")
- assert validate_url("https://ldr.example.com:8443/research")
- assert validate_url("https://sub.domain.example.com/test")
+ assert URLValidator.validate_http_url("https://example.com/path")
+ assert URLValidator.validate_http_url(
+ "https://ldr.example.com:8443/research"
+ )
+ assert URLValidator.validate_http_url(
+ "https://sub.domain.example.com/test"
+ )
def test_empty_url(self):
"""Test validation rejects empty URLs."""
with pytest.raises(URLValidationError, match="non-empty string"):
- validate_url("")
+ URLValidator.validate_http_url("")
def test_none_url(self):
"""Test validation rejects None."""
with pytest.raises(URLValidationError, match="non-empty string"):
- validate_url(None)
+ URLValidator.validate_http_url(None)
def test_invalid_type(self):
"""Test validation rejects non-string types."""
with pytest.raises(URLValidationError, match="non-empty string"):
- validate_url(123)
+ URLValidator.validate_http_url(123)
def test_missing_scheme(self):
"""Test validation rejects URLs without scheme."""
with pytest.raises(URLValidationError, match="must have a scheme"):
- validate_url("example.com/path")
+ URLValidator.validate_http_url("example.com/path")
def test_invalid_scheme(self):
"""Test validation rejects non-http(s) schemes."""
with pytest.raises(URLValidationError, match="must be http or https"):
- validate_url("ftp://example.com/path")
+ URLValidator.validate_http_url("ftp://example.com/path")
with pytest.raises(URLValidationError, match="must be http or https"):
- validate_url("javascript://alert(1)")
+ URLValidator.validate_http_url("javascript://alert(1)")
with pytest.raises(URLValidationError, match="must be http or https"):
- validate_url("file:///etc/passwd")
+ URLValidator.validate_http_url("file:///etc/passwd")
def test_missing_hostname(self):
"""Test validation rejects URLs without hostname."""
with pytest.raises(URLValidationError, match="must have a hostname"):
- validate_url("http:///path")
+ URLValidator.validate_http_url("http:///path")
def test_invalid_hostname(self):
"""Test validation rejects malformed hostnames."""
with pytest.raises(URLValidationError, match="Invalid hostname"):
- validate_url("http://.example.com/path")
+ URLValidator.validate_http_url("http://.example.com/path")
with pytest.raises(URLValidationError, match="Invalid hostname"):
- validate_url("http://example.com./path")
+ URLValidator.validate_http_url("http://example.com./path")
def test_url_with_port(self):
"""Test validation accepts URLs with ports."""
- assert validate_url("http://localhost:5000/path")
- assert validate_url("https://example.com:8443/path")
+ assert URLValidator.validate_http_url("http://localhost:5000/path")
+ assert URLValidator.validate_http_url("https://example.com:8443/path")
def test_url_with_query_params(self):
"""Test validation accepts URLs with query parameters."""
- assert validate_url("http://example.com/path?param=value")
- assert validate_url("https://example.com/research?id=123&user=test")
+ assert URLValidator.validate_http_url(
+ "http://example.com/path?param=value"
+ )
+ assert URLValidator.validate_http_url(
+ "https://example.com/research?id=123&user=test"
+ )
def test_url_with_fragment(self):
"""Test validation accepts URLs with fragments."""
- assert validate_url("http://example.com/path#section")
- assert validate_url("https://example.com/research/123#results")
+ assert URLValidator.validate_http_url("http://example.com/path#section")
+ assert URLValidator.validate_http_url(
+ "https://example.com/research/123#results"
+ )
class TestBuildNotificationURL:
@@ -257,7 +267,7 @@ class TestIntegration:
"""Test typical local development setup."""
url = build_notification_url("/research/abc123")
assert url == "http://localhost:5000/research/abc123"
- assert validate_url(url)
+ assert URLValidator.validate_http_url(url)
def test_realistic_production_scenario(self):
"""Test typical production setup with external URL."""
@@ -269,7 +279,7 @@ class TestIntegration:
)
assert url == "https://ldr.company.com/research/abc123"
- assert validate_url(url)
+ assert URLValidator.validate_http_url(url)
def test_realistic_custom_port_scenario(self):
"""Test setup with custom port."""
@@ -285,4 +295,4 @@ class TestIntegration:
)
assert url == "http://server.local:8080/research/abc123"
- assert validate_url(url)
+ assert URLValidator.validate_http_url(url)