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.

fix: enable localhost HTTP for development without TESTING flag

LearningCircuit3be8341f665d
diff --git a/.github/workflows/security-tests.yml b/.github/workflows/security-tests.yml
index 5df2066ae0..a1bf243954 100644
--- a/.github/workflows/security-tests.yml
+++ b/.github/workflows/security-tests.yml
@@ -117,6 +117,10 @@ jobs:
pdm run python -m pytest tests/test_session_security.py -v --tb=short -n auto
fi
+ - name: Run cookie security tests
+ run: |
+ pdm run python -m pytest tests/security/test_cookie_security.py -v --tb=short -n auto
+
- name: Run API security tests
run: |
pdm run python -m pytest tests/security/test_api_security.py -v --tb=short -n auto
diff --git a/examples/api_usage/http/advanced/http_api_examples.py b/examples/api_usage/http/advanced/http_api_examples.py
index d7554079fe..d65746bdec 100755
--- a/examples/api_usage/http/advanced/http_api_examples.py
+++ b/examples/api_usage/http/advanced/http_api_examples.py
@@ -10,7 +10,26 @@ Requirements:
- LDR server running: python -m local_deep_research.web.app
- Beautiful Soup: pip install beautifulsoup4
-This example works COMPLETELY out of the box - no manual setup required!
+================================================================================
+IMPORTANT - LOCALHOST ONLY
+================================================================================
+This example ONLY works when connecting via localhost:
+ ✅ http://localhost:5000
+ ✅ http://127.0.0.1:5000
+
+It will NOT work when connecting via:
+ ❌ http://192.168.x.x:5000 (local network IP)
+ ❌ http://your-server.com:5000 (remote server)
+
+WHY: For security, session cookies require HTTPS for non-localhost connections.
+
+SOLUTIONS for non-localhost access:
+1. Use HTTPS with a reverse proxy (recommended for production)
+2. SSH tunnel: ssh -L 5000:localhost:5000 user@server, then use localhost:5000
+3. Set TESTING=1 when starting server (INSECURE - development only!)
+
+WARNING: TESTING=1 disables secure cookie protection. Never use in production.
+================================================================================
"""
import time
diff --git a/examples/api_usage/http/advanced/simple_http_example.py b/examples/api_usage/http/advanced/simple_http_example.py
index edcc96e972..eaae331be0 100755
--- a/examples/api_usage/http/advanced/simple_http_example.py
+++ b/examples/api_usage/http/advanced/simple_http_example.py
@@ -4,6 +4,25 @@ Simple HTTP API Example for Local Deep Research v1.0+
This example shows how to use the LDR API with authentication.
Works completely out of the box with automatic user creation.
+
+================================================================================
+IMPORTANT - LOCALHOST ONLY
+================================================================================
+This example ONLY works when connecting via localhost:
+ ✅ http://localhost:5000
+ ✅ http://127.0.0.1:5000
+
+It will NOT work via http://192.168.x.x:5000 or other non-localhost addresses.
+
+WHY: Session cookies require HTTPS for non-localhost (security).
+
+SOLUTIONS for non-localhost:
+1. HTTPS with reverse proxy (production)
+2. SSH tunnel: ssh -L 5000:localhost:5000 user@server
+3. TESTING=1 env var (INSECURE - dev only!)
+
+WARNING: TESTING=1 disables cookie security. Never use in production.
+================================================================================
"""
import requests
diff --git a/examples/api_usage/http/simple_working_example.py b/examples/api_usage/http/simple_working_example.py
index 84674ad1eb..43884d1974 100644
--- a/examples/api_usage/http/simple_working_example.py
+++ b/examples/api_usage/http/simple_working_example.py
@@ -9,7 +9,30 @@ Requirements:
- LDR v1.0+ server running: python -m local_deep_research.web.app
- Beautiful Soup: pip install beautifulsoup4
-This example works COMPLETELY out of the box - no manual setup required!
+================================================================================
+IMPORTANT - LOCALHOST ONLY
+================================================================================
+This example ONLY works when connecting via localhost:
+ ✅ http://localhost:5000
+ ✅ http://127.0.0.1:5000
+
+It will NOT work when connecting via:
+ ❌ http://192.168.x.x:5000 (local network IP)
+ ❌ http://your-server.com:5000 (remote server)
+ ❌ http://0.0.0.0:5000 (even from the same machine)
+
+WHY: For security, session cookies require HTTPS for non-localhost connections.
+This prevents session hijacking on untrusted networks.
+
+SOLUTIONS for non-localhost access:
+1. Use HTTPS with a reverse proxy (recommended for production)
+2. SSH tunnel: ssh -L 5000:localhost:5000 user@server, then use localhost:5000
+3. Set TESTING=1 when starting server (INSECURE - development only!)
+ Example: TESTING=1 python -m local_deep_research.web.app
+
+WARNING: TESTING=1 disables secure cookie protection. Session cookies can be
+intercepted by network attackers. Never use in production or on public networks.
+================================================================================
"""
import requests
diff --git a/src/local_deep_research/web/app_factory.py b/src/local_deep_research/web/app_factory.py
index 9e10d0d6ed..219b0d03ca 100644
--- a/src/local_deep_research/web/app_factory.py
+++ b/src/local_deep_research/web/app_factory.py
@@ -78,6 +78,74 @@ def create_app():
x_prefix=0, # Don't trust X-Forwarded-Prefix (security)
)
+ # WSGI middleware for dynamic cookie security
+ # This wraps AFTER ProxyFix so we have access to the real client IP
+ # Must be WSGI level because Flask session cookies are set after after_request handlers
+ class SecureCookieMiddleware:
+ """WSGI middleware to add Secure flag to cookies based on request context.
+
+ Security model:
+ - Localhost HTTP (127.0.0.1, ::1): Skip Secure flag (local traffic is safe)
+ - Proxied requests (X-Forwarded-For present): Add Secure flag (production)
+ - Non-localhost HTTP: Add Secure flag (will fail, by design - use HTTPS)
+ - TESTING mode: Never add Secure flag (for CI/development)
+
+ This prevents X-Forwarded-For spoofing attacks by checking for the header's
+ presence rather than its value - if the header exists, we're behind a proxy.
+ """
+
+ def __init__(self, wsgi_app, flask_app):
+ self.wsgi_app = wsgi_app
+ self.flask_app = flask_app
+
+ def __call__(self, environ, start_response):
+ # Check if we should add Secure flag
+ should_add_secure = self._should_add_secure_flag(environ)
+
+ def custom_start_response(status, headers, exc_info=None):
+ if should_add_secure:
+ # Modify Set-Cookie headers to add Secure flag
+ new_headers = []
+ for name, value in headers:
+ if name.lower() == "set-cookie":
+ if (
+ "; Secure" not in value
+ and "; secure" not in value
+ ):
+ value = value + "; Secure"
+ new_headers.append((name, value))
+ headers = new_headers
+ return start_response(status, headers, exc_info)
+
+ return self.wsgi_app(environ, custom_start_response)
+
+ def _should_add_secure_flag(self, environ):
+ """Determine if Secure flag should be added based on request context."""
+ # Skip if in explicit testing mode
+ if self.flask_app.config.get("LDR_TESTING_MODE"):
+ return False
+
+ # Check for proxy indicators - if proxied, always require Secure
+ # This prevents X-Forwarded-For spoofing attacks
+ # Note: After ProxyFix, HTTP_X_FORWARDED_FOR is the original header
+ xff = environ.get("HTTP_X_FORWARDED_FOR")
+ if xff is not None:
+ # Behind proxy = production, always add Secure flag
+ return True
+
+ # Direct connection - check if from localhost
+ remote_addr = environ.get("REMOTE_ADDR", "")
+ is_localhost = remote_addr in ("127.0.0.1", "::1")
+
+ # Check if HTTPS
+ is_https = environ.get("wsgi.url_scheme") == "https"
+
+ # Add Secure if HTTPS or if NOT from localhost
+ return is_https or not is_localhost
+
+ # Wrap the app with our cookie security middleware
+ app.wsgi_app = SecureCookieMiddleware(app.wsgi_app, app)
+
# App configuration
# Generate or load a unique SECRET_KEY per installation
import secrets
@@ -105,32 +173,20 @@ def create_app():
logger.warning(f"Could not save secret key file: {e}")
app.config["SECRET_KEY"] = new_key
# Session cookie security settings
- # SECURE: Only send cookies over HTTPS in production
- # Allow HTTP cookies in debug mode, CI/test environments, or localhost
-
- # Check if binding to localhost (common dev scenario)
- # Localhost traffic never leaves the machine, so Secure flag isn't needed
- # Note: 0.0.0.0 is NOT localhost - it binds to all interfaces
- # Use LDR settings system which checks LDR_WEB_HOST env var automatically
- # Note: This runs before database is available, so we use SettingsManager without db_session
- from ..settings.manager import SettingsManager
-
- settings_manager = SettingsManager(db_session=None)
-
- server_name = app.config.get("SERVER_NAME") or ""
- host = settings_manager.get_setting("web.host", "127.0.0.1")
- is_localhost = host in ("localhost", "127.0.0.1") or server_name.startswith(
- ("localhost", "127.0.0.1")
- )
-
+ # SECURE flag is added dynamically based on request context (see after_request below)
+ # This allows localhost HTTP to work for development while keeping production secure
+ #
+ # Check if explicitly in testing mode (for backwards compatibility)
is_testing = (
os.getenv("CI")
or os.getenv("TESTING")
or os.getenv("PYTEST_CURRENT_TEST")
or app.debug
- or is_localhost # Auto-detect localhost for dev convenience
)
- app.config["SESSION_COOKIE_SECURE"] = not is_testing
+ # Set to False - we add Secure flag dynamically in after_request handler
+ # Exception: if TESTING mode is active, we never add Secure flag
+ app.config["SESSION_COOKIE_SECURE"] = False
+ app.config["LDR_TESTING_MODE"] = bool(is_testing) # Store for after_request
app.config["SESSION_COOKIE_HTTPONLY"] = (
True # Prevent JavaScript access (XSS mitigation)
)
@@ -182,6 +238,10 @@ def create_app():
message="Too many attempts. Please try again later.",
), 429
+ # Note: Dynamic cookie security is handled by SecureCookieMiddleware (WSGI level)
+ # This is necessary because Flask's session cookies are set AFTER after_request handlers
+ # The middleware wrapping happens below near ProxyFix
+
# Disable CSRF for API routes
@app.before_request
def disable_csrf_for_api():
@@ -639,21 +699,34 @@ def register_error_handlers(app):
def handle_csrf_error(error):
"""Handle CSRF errors with helpful debugging info."""
# Check if this might be a Secure cookie issue over HTTP
- is_http = request.scheme == "http"
- is_non_localhost = not request.host.startswith(
- ("localhost", "127.0.0.1")
- )
+ is_http = not request.is_secure
+ is_non_localhost = request.remote_addr not in ("127.0.0.1", "::1")
+ is_proxied = request.headers.get("X-Forwarded-For") is not None
error_msg = str(error.description)
- if is_http and is_non_localhost:
+ # Provide detailed help for HTTP + non-localhost scenario
+ if is_http and (is_non_localhost or is_proxied):
logger.warning(
- f"CSRF validation failed over HTTP from non-localhost: "
- f"{request.host}. Session cookies may not be sent over HTTP."
+ f"CSRF validation failed - likely due to Secure cookie over HTTP. "
+ f"remote_addr={request.remote_addr}, proxied={is_proxied}, "
+ f"host={request.host}"
)
error_msg = (
- f"{error.description}. Session cookies require HTTPS for "
- "non-localhost requests. Use HTTPS or access via localhost."
+ "Session cookie error: You're accessing over HTTP from a "
+ "non-localhost address or through a proxy. "
+ "This is blocked for security reasons.\n\n"
+ "Solutions:\n"
+ "1. Use HTTPS with a reverse proxy (recommended for production)\n"
+ "2. Access directly from localhost (http://127.0.0.1:5000)\n"
+ "3. Use SSH tunnel: ssh -L 5000:localhost:5000 user@server, "
+ "then access http://localhost:5000\n"
+ "4. Set TESTING=1 environment variable when starting the server "
+ "(INSECURE - development only!)\n"
+ " Example: TESTING=1 python -m local_deep_research.web.app\n\n"
+ "WARNING: Using TESTING=1 disables secure cookie protection. "
+ "Session cookies can be intercepted by network attackers. "
+ "Never use this in production or on public networks."
)
return make_response(jsonify({"error": error_msg}), 400)
diff --git a/tests/security/test_cookie_security.py b/tests/security/test_cookie_security.py
new file mode 100644
index 0000000000..c66bea96e9
--- /dev/null
+++ b/tests/security/test_cookie_security.py
@@ -0,0 +1,271 @@
+"""
+Cookie Security Tests
+
+Tests for the dynamic cookie security behavior that allows localhost HTTP
+while requiring HTTPS for non-localhost connections.
+
+Security model:
+- Localhost HTTP (127.0.0.1, ::1): Cookies work without Secure flag
+- Proxied requests (X-Forwarded-For): Always get Secure flag
+- Non-localhost HTTP: Get Secure flag (will fail, by design)
+- HTTPS: Always get Secure flag
+- TESTING mode: Never get Secure flag (for CI/development)
+"""
+
+import pytest
+from tests.test_utils import add_src_to_path
+
+add_src_to_path()
+
+
+def app():
+ """Create test application with TESTING mode enabled (default for tests)."""
+ from src.local_deep_research.web.app_factory import create_app
+
+ app, _ = create_app()
+ app.config["TESTING"] = True
+ app.config["WTF_CSRF_ENABLED"] = False # Disable CSRF for these tests
+ # LDR_TESTING_MODE is set by create_app based on env vars
+ # For most tests, this is True (CI environment)
+ return app
+
+
+def app_production_mode():
+ """Create test application with production-like cookie security."""
+ import os
+ from src.local_deep_research.web.app_factory import create_app
+
+ # Temporarily unset ALL testing env vars to simulate production
+ # Note: PYTEST_CURRENT_TEST is also checked by create_app
+ old_testing = os.environ.pop("TESTING", None)
+ old_ci = os.environ.pop("CI", None)
+ old_pytest = os.environ.pop("PYTEST_CURRENT_TEST", None)
+
+ try:
+ app, _ = create_app()
+ app.config["TESTING"] = True # Flask testing mode for test client
+ app.config["WTF_CSRF_ENABLED"] = False
+ # Explicitly disable LDR testing mode to test production cookie behavior
+ app.config["LDR_TESTING_MODE"] = False
+ # Set to http to properly test HTTP behavior (default is https for URL generation)
+ # In real production with HTTPS, wsgi.url_scheme is set by the server
+ app.config["PREFERRED_URL_SCHEME"] = "http"
+ return app
+ finally:
+ # Restore env vars
+ if old_testing is not None:
+ os.environ["TESTING"] = old_testing
+ if old_ci is not None:
+ os.environ["CI"] = old_ci
+ if old_pytest is not None:
+ os.environ["PYTEST_CURRENT_TEST"] = old_pytest
+
+
+def client(app):
+ """Create test client."""
+ return app.test_client()
+
+
+class TestLocalhostCookieSecurity:
+ """Test that localhost HTTP connections work without Secure flag."""
+
+ def test_localhost_http_no_secure_flag(self, client):
+ """Localhost HTTP requests should NOT have Secure flag on cookies."""
+ # Default test client simulates localhost (127.0.0.1)
+ response = client.get("/auth/login")
+
+ # Check Set-Cookie header
+ set_cookie = response.headers.get("Set-Cookie", "")
+
+ # Should NOT have Secure flag for localhost HTTP
+ # Note: In TESTING mode, Secure is never added
+ assert response.status_code == 200
+ # The cookie should be set (session cookie)
+ assert "session=" in set_cookie
+
+ def test_localhost_session_cookie_works(self, client):
+ """Verify session cookies are sent back on subsequent requests from localhost."""
+ # Get login page (establishes session)
+ response1 = client.get("/auth/login")
+ assert response1.status_code == 200
+
+ # Make another request - session should persist
+ response2 = client.get("/auth/login")
+ assert response2.status_code == 200
+
+ # Session should be maintained (cookie sent back)
+ # This would fail if Secure flag was set but we're on HTTP
+
+
+class TestLocalhostProductionMode:
+ """Test localhost HTTP works in production mode (non-testing)."""
+
+ def test_localhost_http_no_secure_flag_in_production(
+ self, app_production_mode
+ ):
+ """Localhost HTTP requests should NOT have Secure flag even in production mode."""
+ app = app_production_mode
+
+ with app.test_client() as client:
+ # Direct localhost request (no X-Forwarded-For)
+ response = client.get("/auth/login")
+
+ set_cookie = response.headers.get("Set-Cookie", "")
+
+ # Should NOT have Secure flag for direct localhost HTTP
+ assert "; Secure" not in set_cookie, (
+ f"Localhost HTTP should NOT have Secure flag. Got: {set_cookie}"
+ )
+ assert "session=" in set_cookie # Cookie should still be set
+
+
+class TestProxiedRequestSecurity:
+ """Test that proxied requests always get Secure flag."""
+
+ def test_proxied_request_gets_secure_flag(self, app_production_mode):
+ """Requests with X-Forwarded-For should get Secure flag."""
+ app = app_production_mode
+
+ with app.test_client() as client:
+ # Simulate proxied request with X-Forwarded-For header
+ # Note: Flask test client always has REMOTE_ADDR=127.0.0.1
+ # but our code checks for X-Forwarded-For header presence
+ response = client.get(
+ "/auth/login",
+ headers={"X-Forwarded-For": "192.168.1.100"},
+ )
+
+ set_cookie = response.headers.get("Set-Cookie", "")
+
+ # Should have Secure flag because X-Forwarded-For header is present
+ # This indicates request came through a proxy
+ assert "; Secure" in set_cookie, (
+ f"Proxied requests should have Secure flag. Got: {set_cookie}"
+ )
+
+ def test_spoofed_localhost_via_xff_still_secure(self, app_production_mode):
+ """X-Forwarded-For: 127.0.0.1 should still get Secure flag (anti-spoofing)."""
+ app = app_production_mode
+
+ with app.test_client() as client:
+ # Attacker tries to spoof localhost via X-Forwarded-For
+ response = client.get(
+ "/auth/login",
+ headers={"X-Forwarded-For": "127.0.0.1"},
+ )
+
+ set_cookie = response.headers.get("Set-Cookie", "")
+
+ # Should STILL have Secure flag - we detect the proxy header
+ # and treat all proxied requests as production
+ assert "; Secure" in set_cookie, (
+ f"Spoofed localhost via X-Forwarded-For should still get Secure. Got: {set_cookie}"
+ )
+
+
+class TestTestingModeBehavior:
+ """Test that TESTING mode disables Secure flag entirely."""
+
+ def test_testing_mode_no_secure_flag(self, app):
+ """In TESTING mode, Secure flag should never be added."""
+ app.config["LDR_TESTING_MODE"] = True
+
+ with app.test_client() as client:
+ # Even with X-Forwarded-For, TESTING mode skips Secure
+ response = client.get(
+ "/auth/login",
+ headers={"X-Forwarded-For": "192.168.1.100"},
+ )
+
+ set_cookie = response.headers.get("Set-Cookie", "")
+
+ # In TESTING mode, no Secure flag
+ assert "; Secure" not in set_cookie
+
+
+class TestCSRFErrorMessage:
+ """Test that CSRF errors provide helpful messages for cookie issues."""
+
+ def test_csrf_error_message_is_helpful(self, app):
+ """CSRF error for non-localhost HTTP should explain the issue."""
+ app.config["WTF_CSRF_ENABLED"] = True
+ app.config["LDR_TESTING_MODE"] = False
+
+ with app.test_client() as client:
+ # Get login page to establish session
+ client.get("/auth/login")
+
+ # Try to POST without proper CSRF token
+ # Simulating non-localhost by adding X-Forwarded-For
+ response = client.post(
+ "/auth/login",
+ data={"username": "test", "password": "test"},
+ headers={"X-Forwarded-For": "192.168.1.100"},
+ )
+
+ # Should get a 400 error with helpful message
+ assert response.status_code == 400
+
+ # Check for helpful error message
+ data = response.get_json()
+ if data and "error" in data:
+ error_msg = data["error"]
+ # Should mention the security issue
+ assert (
+ "Session cookie error" in error_msg or "CSRF" in error_msg
+ )
+
+
+class TestCookieSecurityDocumentation:
+ """Documentation tests explaining the security model."""
+
+ def test_security_model_documentation(self):
+ """
+ Document the cookie security model.
+
+ WHY THIS EXISTS:
+ - Session cookies with Secure flag only work over HTTPS
+ - Local development typically uses HTTP
+ - We want security in production but usability in development
+
+ HOW IT WORKS:
+ 1. Check if request has X-Forwarded-For header (proxy indicator)
+ 2. If proxied: Always add Secure flag (production behind proxy)
+ 3. If not proxied: Check request.remote_addr
+ - 127.0.0.1 or ::1: Skip Secure flag (localhost development)
+ - Other IPs: Add Secure flag (direct non-localhost = needs HTTPS)
+ 4. TESTING mode: Never add Secure flag (CI/test environments)
+
+ SECURITY PROPERTIES:
+ - Localhost HTTP: ✅ Works - traffic is local only
+ - Proxied requests: ✅ Secure - always requires HTTPS
+ - X-Forwarded-For spoofing: ✅ Blocked - proxy presence = Secure
+ - Non-localhost HTTP: ✅ Blocked - requires HTTPS
+ - TESTING mode: ⚠️ Insecure but explicit opt-in
+
+ ATTACK PREVENTION:
+ - Session hijacking on public networks: Prevented by Secure flag
+ - X-Forwarded-For spoofing: Prevented by checking for proxy header
+ - Development convenience: Preserved for localhost only
+ """
+ assert True # Documentation test
+
+
+def test_cookie_security_summary():
+ """
+ Summary of cookie security behavior for CI validation.
+
+ Expected behavior:
+ | Scenario | Secure Flag | Should Work? |
+ |-----------------------------|-------------|--------------|
+ | localhost:5000 (direct) | No | ✅ Yes |
+ | 127.0.0.1:5000 (direct) | No | ✅ Yes |
+ | 192.168.x.x:5000 (direct) | Yes | ❌ No (HTTP) |
+ | Behind proxy (any) | Yes | ✅ If HTTPS |
+ | X-Forwarded-For spoof | Yes | ❌ Blocked |
+ | TESTING=1 mode | No | ✅ Yes |
+ """
+ assert True # Documentation/summary test