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(auth): set Secure cookie flag based on protocol, not source IP (#3849) (#3960)

LearningCircuit69e71c628e09
diff --git a/changelog.d/3849.bugfix.md b/changelog.d/3849.bugfix.md
new file mode 100644
index 0000000000..7dbabfbce6
--- /dev/null
+++ b/changelog.d/3849.bugfix.md
@@ -0,0 +1,5 @@
+Fix login/registration over `http://localhost:5001` on Docker Desktop.
+The session cookie's `Secure` flag is now driven purely by the request
+protocol (HTTPS) rather than by source-IP heuristics, so HTTP requests
+from any IP — including Docker Desktop's NAT gateway — now keep their
+cookies and CSRF tokens.
diff --git a/src/local_deep_research/web/app_factory.py b/src/local_deep_research/web/app_factory.py
index e63289f2ec..ab38348f07 100644
--- a/src/local_deep_research/web/app_factory.py
+++ b/src/local_deep_research/web/app_factory.py
@@ -42,6 +42,87 @@ def _is_private_ip(ip_str: str) -> bool:
return False
+class SecureCookieMiddleware:
+ """WSGI middleware that adds the Secure flag to Set-Cookie iff the
+ request is HTTPS.
+
+ The Secure flag tells the browser to send the cookie only over HTTPS.
+ Setting it on a response served over HTTP causes the browser to drop
+ the cookie entirely, so it must only be added when the user's
+ connection is actually HTTPS. ProxyFix (with x_proto=1) translates
+ X-Forwarded-Proto into wsgi.url_scheme before this middleware runs.
+
+ Side effect: logs a one-shot warning when the app serves HTTP to a
+ non-private end-user IP, signalling a likely missing HTTPS proxy
+ configuration. Skipped in LDR_TESTING_MODE.
+ """
+
+ def __init__(self, wsgi_app, flask_app):
+ self.wsgi_app = wsgi_app
+ self.flask_app = flask_app
+ self._warned_insecure_public = False
+
+ def __call__(self, environ, start_response):
+ self._maybe_warn_insecure_public(environ)
+ should_add_secure = self._should_add_secure_flag(environ)
+
+ def custom_start_response(status, headers, exc_info=None):
+ if should_add_secure:
+ 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):
+ if self.flask_app.config.get("LDR_TESTING_MODE"):
+ return False
+ return environ.get("wsgi.url_scheme") == "https"
+
+ def _maybe_warn_insecure_public(self, environ):
+ if self._warned_insecure_public:
+ return
+ if self.flask_app.config.get("LDR_TESTING_MODE"):
+ return
+ if environ.get("wsgi.url_scheme") == "https":
+ return
+ remote_addr = environ.get("REMOTE_ADDR", "")
+ if _is_private_ip(remote_addr):
+ return
+ self._warned_insecure_public = True
+ logger.warning(
+ f"Serving HTTP to non-private client {remote_addr}. "
+ f"Session cookies will be sent in plaintext. Configure HTTPS "
+ f"at the reverse proxy and ensure X-Forwarded-Proto is set."
+ )
+
+
+class ServerHeaderMiddleware:
+ """WSGI middleware that strips the Server header from responses to
+ prevent information disclosure about the underlying web server.
+ Applied as the outermost wrapper.
+ """
+
+ def __init__(self, wsgi_app):
+ self.wsgi_app = wsgi_app
+
+ def __call__(self, environ, start_response):
+ def custom_start_response(status, headers, exc_info=None):
+ filtered_headers = [
+ (name, value)
+ for name, value in headers
+ if name.lower() != "server"
+ ]
+ return start_response(status, filtered_headers, exc_info)
+
+ return self.wsgi_app(environ, custom_start_response)
+
+
class DiskSpoolingRequest(Request):
"""Custom Request class that spools large file uploads to disk.
@@ -123,9 +204,13 @@ def create_app():
# This prevents memory exhaustion from large file uploads (issue #1176)
app.request_class = DiskSpoolingRequest
- # Add proxy support for deployments behind load balancers/reverse proxies
- # This ensures X-Forwarded-For and X-Forwarded-Proto headers are properly handled
- # Important for rate limiting and security (gets real client IP, not proxy IP)
+ # Middleware stack (wrapped innermost -> outermost; runs in reverse at
+ # request time):
+ # 1. SecureCookieMiddleware: adds Secure flag iff wsgi.url_scheme=https.
+ # Wrapped INSIDE ProxyFix so it reads the post-rewrite scheme.
+ # 2. ProxyFix: translates X-Forwarded-* into REMOTE_ADDR / wsgi.url_scheme.
+ # 3. ServerHeaderMiddleware: strips Server header (outermost).
+ app.wsgi_app = SecureCookieMiddleware(app.wsgi_app, app) # type: ignore[method-assign]
app.wsgi_app = ProxyFix( # type: ignore[method-assign]
app.wsgi_app,
x_for=1, # Trust 1 proxy for X-Forwarded-For
@@ -134,110 +219,6 @@ def create_app():
x_port=0, # Don't trust X-Forwarded-Port (security)
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.
-
- Security model:
- - Check the ACTUAL connection IP (REMOTE_ADDR), not X-Forwarded-For header
- - SecureCookieMiddleware is outer wrapper, so we see original REMOTE_ADDR
- - If connection comes from private IP (client or proxy), allow HTTP
- - If connection comes from public IP, require HTTPS
-
- This is safe because:
- - We never trust X-Forwarded-For header values (can be spoofed)
- - We only check the actual TCP connection source IP
- - Spoofing X-Forwarded-For from public IP doesn't bypass this check
- - Local proxies (nginx on localhost/LAN) have private REMOTE_ADDR
- """
- # Skip if in explicit testing mode
- if self.flask_app.config.get("LDR_TESTING_MODE"):
- return False
-
- # Check actual connection source IP (before ProxyFix modifies it)
- # This is either:
- # - Direct client IP (if no proxy)
- # - Proxy server IP (if behind proxy)
- # Local proxies (nginx on localhost, Traefik on LAN) have private IPs
- remote_addr = environ.get("REMOTE_ADDR", "")
- is_private = _is_private_ip(remote_addr)
-
- # Check if HTTPS
- is_https = environ.get("wsgi.url_scheme") == "https"
-
- # Add Secure flag if:
- # - Using HTTPS (always secure over HTTPS)
- # - OR connection is from public IP (require HTTPS for public access)
- return is_https or not is_private
-
- # Wrap the app with our cookie security middleware
- app.wsgi_app = SecureCookieMiddleware(app.wsgi_app, app) # type: ignore[method-assign]
-
- # WSGI middleware to remove Server header
- # This must be the outermost wrapper to catch headers added by Werkzeug
- class ServerHeaderMiddleware:
- """WSGI middleware to remove Server header from all responses.
-
- Prevents information disclosure about the underlying web server.
- Must be outermost middleware to catch headers added by WSGI layer.
- """
-
- def __init__(self, wsgi_app):
- self.wsgi_app = wsgi_app
-
- def __call__(self, environ, start_response):
- def custom_start_response(status, headers, exc_info=None):
- filtered_headers = [
- (name, value)
- for name, value in headers
- if name.lower() != "server"
- ]
- return start_response(status, filtered_headers, exc_info)
-
- return self.wsgi_app(environ, custom_start_response)
-
- # Apply ServerHeaderMiddleware as outermost wrapper
app.wsgi_app = ServerHeaderMiddleware(app.wsgi_app) # type: ignore[method-assign]
# App configuration
@@ -952,42 +933,15 @@ def register_error_handlers(app):
)
return jsonify(error.to_dict()), error.status_code
- # Handle CSRF validation errors with helpful message
+ # Handle CSRF validation errors as JSON
try:
from flask_wtf.csrf import CSRFError
@app.errorhandler(CSRFError)
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 = not request.is_secure
- is_private = _is_private_ip(request.remote_addr or "")
- is_proxied = request.headers.get("X-Forwarded-For") is not None
-
- error_msg = str(error.description)
-
- # Provide detailed help for HTTP + public IP or proxied scenario
- if is_http and (not is_private or is_proxied):
- logger.warning(
- 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 = (
- "Session cookie error: You're accessing over HTTP from a "
- "public IP 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 from your local network (LAN IPs like 192.168.x.x work over HTTP)\n"
- "3. Access directly from localhost (http://127.0.0.1:5000)\n"
- "4. Use SSH tunnel: ssh -L 5000:localhost:5000 user@server, "
- "then access http://localhost:5000\n\n"
- "Note: LAN access (192.168.x.x, 10.x.x.x, 172.16-31.x.x) works over HTTP. "
- "Only public internet access requires HTTPS."
- )
-
- return make_response(jsonify({"error": error_msg}), 400)
+ return make_response(
+ jsonify({"error": str(error.description)}), 400
+ )
except ImportError:
pass
diff --git a/tests/security/test_cookie_security.py b/tests/security/test_cookie_security.py
index 96aed8b82c..fecae02500 100644
--- a/tests/security/test_cookie_security.py
+++ b/tests/security/test_cookie_security.py
@@ -1,26 +1,18 @@
"""
Cookie Security Tests
-Tests for the dynamic cookie security behavior that allows private network HTTP
-while requiring HTTPS for public internet connections.
+Tests for the dynamic cookie security behavior.
Security model:
-- Private network HTTP (localhost, LAN IPs): Cookies work without Secure flag
-- Local proxy (nginx on localhost/LAN): Cookies work without Secure flag
-- Public proxy (Cloudflare, AWS): Get Secure flag (requires HTTPS)
-- Public IP HTTP: Get Secure flag (will fail, by design - requires HTTPS)
-- HTTPS: Always get Secure flag
-- TESTING mode: Never get Secure flag (for CI/development)
-
-Key insight: We check the ACTUAL connection IP (REMOTE_ADDR), not X-Forwarded-For.
-SecureCookieMiddleware is the outer wrapper, so it sees the original REMOTE_ADDR
-before ProxyFix modifies it. This means:
-- Local proxy (nginx on 127.0.0.1) → REMOTE_ADDR=127.0.0.1 (private) → HTTP works
-- Public proxy (Cloudflare) → REMOTE_ADDR=104.16.x.x (public) → requires HTTPS
-- Spoofed X-Forwarded-For from public IP → still blocked (REMOTE_ADDR is public)
-
-Private IPs (RFC 1918) include: 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, plus localhost.
-This matches the behavior of self-hosted apps like Jellyfin and Home Assistant.
+- Secure flag is added iff wsgi.url_scheme == "https".
+- ProxyFix (with x_proto=1) translates X-Forwarded-Proto into wsgi.url_scheme
+ before SecureCookieMiddleware sees it, so requests served over HTTPS by a
+ reverse proxy correctly receive the Secure flag.
+- HTTP requests never get Secure regardless of source IP. Setting Secure on
+ an HTTP response causes the browser to drop the cookie entirely, so doing
+ so based on IP heuristics broke legitimate Docker/LAN access without
+ providing any cryptographic protection (issue #3849).
+- TESTING mode: Never get Secure flag (for CI/development).
"""
import pytest
@@ -36,9 +28,7 @@ def 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)
+ app.config["WTF_CSRF_ENABLED"] = False
return app
@@ -48,24 +38,18 @@ def app_production_mode():
import os
from 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["TESTING"] = True
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:
@@ -81,333 +65,124 @@ def client(app):
class TestLocalhostCookieSecurity:
- """Test that localhost HTTP connections work without Secure flag."""
+ """Localhost HTTP works 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)."""
+ """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
+ assert "session=" in set_cookie
-class TestLANIPCookieSecurity:
- """Test that LAN/private network IPs work without Secure flag (RFC 1918)."""
-
- def test_lan_ip_192_168_no_secure_flag(self, app_production_mode):
- """192.168.x.x LAN IPs should NOT have Secure flag."""
- app = app_production_mode
-
- with app.test_client() as client:
- # Simulate request from 192.168.1.100 (common home network)
- response = client.get(
- "/auth/login",
- environ_base={"REMOTE_ADDR": "192.168.1.100"},
- )
+class TestHttpCookieSecurity:
+ """HTTP requests never get the Secure flag, regardless of source IP.
- set_cookie = response.headers.get("Set-Cookie", "")
-
- # Should NOT have Secure flag for LAN IP over HTTP
- assert "; Secure" not in set_cookie, (
- f"LAN IP 192.168.x.x should NOT have Secure flag. Got: {set_cookie}"
- )
- assert "session=" in set_cookie # Cookie should still be set
-
- def test_lan_ip_10_x_no_secure_flag(self, app_production_mode):
- """10.x.x.x LAN IPs should NOT have Secure flag."""
- app = app_production_mode
-
- with app.test_client() as client:
- # Simulate request from 10.0.0.50 (common corporate network)
- response = client.get(
- "/auth/login",
- environ_base={"REMOTE_ADDR": "10.0.0.50"},
- )
-
- set_cookie = response.headers.get("Set-Cookie", "")
-
- assert "; Secure" not in set_cookie, (
- f"LAN IP 10.x.x.x should NOT have Secure flag. Got: {set_cookie}"
- )
-
- def test_lan_ip_172_16_no_secure_flag(self, app_production_mode):
- """172.16-31.x.x LAN IPs should NOT have Secure flag."""
- app = app_production_mode
-
- with app.test_client() as client:
- # Simulate request from 172.16.0.1
- response = client.get(
- "/auth/login",
- environ_base={"REMOTE_ADDR": "172.16.0.1"},
- )
-
- set_cookie = response.headers.get("Set-Cookie", "")
-
- assert "; Secure" not in set_cookie, (
- f"LAN IP 172.16.x.x should NOT have Secure flag. Got: {set_cookie}"
- )
-
- def test_public_ip_gets_secure_flag(self, app_production_mode):
- """Public IPs (non-RFC 1918) should get Secure flag over HTTP."""
- app = app_production_mode
-
- with app.test_client() as client:
- # Simulate request from a public IP (Google DNS)
- response = client.get(
- "/auth/login",
- environ_base={"REMOTE_ADDR": "8.8.8.8"},
- )
-
- set_cookie = response.headers.get("Set-Cookie", "")
-
- # Public IP should have Secure flag
- assert "; Secure" in set_cookie, (
- f"Public IP should have Secure flag. Got: {set_cookie}"
- )
-
-
-class TestLocalProxySecurity:
- """Test that local proxies (nginx on localhost/LAN) work without Secure flag."""
-
- def test_local_proxy_no_secure_flag(self, app_production_mode):
- """Local proxy (127.0.0.1) with X-Forwarded-For should NOT have Secure flag."""
- app = app_production_mode
-
- with app.test_client() as client:
- # Proxy on localhost, client behind it
- # REMOTE_ADDR is the proxy's IP (127.0.0.1 = private)
- response = client.get(
- "/auth/login",
- headers={"X-Forwarded-For": "192.168.1.100"},
- environ_base={"REMOTE_ADDR": "127.0.0.1"},
- )
-
- set_cookie = response.headers.get("Set-Cookie", "")
-
- # Should NOT have Secure flag - proxy is on localhost (private)
- assert "; Secure" not in set_cookie, (
- f"Local proxy should NOT have Secure flag. Got: {set_cookie}"
- )
+ This is the core fix for #3849: setting Secure on an HTTP response makes
+ the browser drop the cookie, breaking sessions without adding any real
+ security (the underlying transport is still plaintext).
+ """
- def test_lan_proxy_no_secure_flag(self, app_production_mode):
- """LAN proxy (192.168.x.x) with X-Forwarded-For should NOT have Secure flag."""
+ @pytest.mark.parametrize(
+ "remote_addr",
+ [
+ "127.0.0.1",
+ "192.168.1.100",
+ "10.0.0.50",
+ "172.16.0.1",
+ "172.17.0.2", # Default Docker bridge
+ "172.67.130.145", # Docker Desktop NAT (the #3849 trigger)
+ "8.8.8.8",
+ "104.16.0.1",
+ ],
+ )
+ def test_http_no_secure_flag(self, app_production_mode, remote_addr):
app = app_production_mode
-
with app.test_client() as client:
- # Proxy on LAN, client could claim any IP
response = client.get(
"/auth/login",
- headers={
- "X-Forwarded-For": "8.8.8.8"
- }, # Client claims public IP
- environ_base={
- "REMOTE_ADDR": "192.168.1.1"
- }, # But proxy is on LAN
+ environ_base={"REMOTE_ADDR": remote_addr},
)
-
set_cookie = response.headers.get("Set-Cookie", "")
-
- # Should NOT have Secure flag - proxy is on LAN (private)
assert "; Secure" not in set_cookie, (
- f"LAN proxy should NOT have Secure flag. Got: {set_cookie}"
- )
-
- def test_public_proxy_gets_secure_flag(self, app_production_mode):
- """Public proxy (Cloudflare, AWS) should get Secure flag."""
- app = app_production_mode
-
- with app.test_client() as client:
- # Public proxy (e.g., Cloudflare IP)
- response = client.get(
- "/auth/login",
- headers={
- "X-Forwarded-For": "192.168.1.100"
- }, # Client claims LAN
- environ_base={
- "REMOTE_ADDR": "104.16.0.1"
- }, # Proxy is public IP
+ f"HTTP from {remote_addr} should NOT have Secure flag. "
+ f"Got: {set_cookie}"
)
- set_cookie = response.headers.get("Set-Cookie", "")
- # Public proxy should have Secure flag
- assert "; Secure" in set_cookie, (
- f"Public proxy should have Secure flag. Got: {set_cookie}"
- )
+class TestHttpsCookieSecurity:
+ """HTTPS requests always get the Secure flag."""
- def test_spoofed_xff_from_public_ip_blocked(self, app_production_mode):
- """Spoofed X-Forwarded-For from public IP should still be blocked."""
+ def test_https_via_x_forwarded_proto_gets_secure(self, app_production_mode):
+ """A reverse proxy terminating HTTPS sets X-Forwarded-Proto: https.
+ ProxyFix translates this into wsgi.url_scheme, after which Secure is
+ added.
+ """
app = app_production_mode
-
with app.test_client() as client:
- # Attacker tries to spoof private IP in X-Forwarded-For header
response = client.get(
"/auth/login",
- headers={"X-Forwarded-For": "127.0.0.1"}, # Spoofed localhost
- environ_base={
- "REMOTE_ADDR": "8.8.8.8"
- }, # But actual IP is public
+ headers={"X-Forwarded-Proto": "https"},
+ environ_base={"REMOTE_ADDR": "10.0.0.1"},
)
-
set_cookie = response.headers.get("Set-Cookie", "")
-
- # Should still have Secure flag - we check REMOTE_ADDR, not header
assert "; Secure" in set_cookie, (
- f"Spoofed X-Forwarded-For from public IP should be blocked. Got: {set_cookie}"
+ f"HTTPS via reverse proxy should add Secure. Got: {set_cookie}"
)
class TestTestingModeBehavior:
- """Test that TESTING mode disables Secure flag entirely."""
+ """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"},
+ headers={"X-Forwarded-Proto": "https"},
)
-
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."""
-
- @pytest.mark.skip(reason="documentation/placeholder test - not implemented")
- def test_security_model_documentation(self):
- """
- Document the cookie security model.
-
- WHY THIS EXISTS:
- - Session cookies with Secure flag only work over HTTPS
- - Local/LAN development typically uses HTTP
- - We want security for public internet but usability for private networks
- - Matches behavior of self-hosted apps like Jellyfin, Home Assistant
-
- HOW IT WORKS:
- 1. Check the ACTUAL connection IP (REMOTE_ADDR), not X-Forwarded-For
- 2. SecureCookieMiddleware is outer wrapper, sees original REMOTE_ADDR
- 3. If REMOTE_ADDR is private (RFC 1918): Skip Secure flag
- - This includes both direct clients AND local proxy servers
- 4. If REMOTE_ADDR is public: Add Secure flag (requires HTTPS)
- 5. TESTING mode: Never add Secure flag (CI/test environments)
-
- SECURITY PROPERTIES:
- - Localhost HTTP: ✅ Works - traffic is local only
- - LAN HTTP (192.168.x.x, 10.x.x.x, 172.16-31.x.x): ✅ Works - private network
- - Local proxy (nginx on localhost/LAN): ✅ Works - proxy has private IP
- - Public proxy (Cloudflare, AWS): ✅ Blocked - proxy has public IP
- - Public IP HTTP: ✅ Blocked - requires HTTPS
- - X-Forwarded-For spoofing: ✅ Blocked - we check REMOTE_ADDR, not header
- - 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 REMOTE_ADDR (actual IP)
- - Private network convenience: Preserved for RFC 1918 IPs
- """
- assert True # Documentation test
-
-
def test_cookie_security_summary():
"""
Summary of cookie security behavior for CI validation.
Expected behavior:
- | Scenario | REMOTE_ADDR | Secure Flag | Works? |
- |-------------------------------|---------------|-------------|--------|
- | localhost:5000 (direct) | 127.0.0.1 | No | ✅ Yes |
- | LAN client (direct) | 192.168.x.x | No | ✅ Yes |
- | Local proxy (nginx) | 127.0.0.1 | No | ✅ Yes |
- | LAN proxy (nginx on LAN) | 192.168.x.x | No | ✅ Yes |
- | Public proxy (Cloudflare) | 104.16.x.x | Yes | ❌ No |
- | Public IP (direct) | 8.8.8.8 | Yes | ❌ No |
- | Spoofed XFF from public IP | 8.8.8.8 | Yes | ❌ No |
- | TESTING=1 mode | any | No | ✅ Yes |
-
- Note: We check REMOTE_ADDR (actual connection IP), not X-Forwarded-For.
- This allows local proxies while blocking spoofing attacks from public IPs.
+ | Scenario | wsgi.url_scheme | Secure Flag |
+ |-------------------------------|-----------------|-------------|
+ | HTTP from localhost | http | No |
+ | HTTP from LAN client | http | No |
+ | HTTP from Docker NAT gateway | http | No |
+ | HTTP from public IP | http | No |
+ | HTTPS via reverse proxy | https | Yes |
+ | Direct HTTPS | https | Yes |
+ | TESTING=1 mode | any | No |
+
+ The decision is based purely on the protocol (post-ProxyFix), not the
+ source IP. Setting Secure on HTTP responses doesn't add security and
+ breaks the browser's ability to store the cookie.
"""
- assert True # Documentation/summary test
+ assert True
diff --git a/tests/web/test_app_factory.py b/tests/web/test_app_factory.py
index 9759c83c3d..08f6dfb11b 100644
--- a/tests/web/test_app_factory.py
+++ b/tests/web/test_app_factory.py
@@ -346,69 +346,107 @@ class TestFileUploadSecurity:
class TestSecureCookieMiddleware:
- """Tests for SecureCookieMiddleware WSGI middleware."""
+ """Tests for SecureCookieMiddleware WSGI middleware.
- def test_secure_flag_logic_for_public_ip(self):
- """Secure flag should be added for public IP HTTP connections."""
- from local_deep_research.web.app_factory import _is_private_ip
-
- # Public IP + HTTP = should add secure (will fail by design)
- # Note: 203.0.113.x is TEST-NET-3 (reserved for documentation) and
- # is treated as private by Python's ipaddress module.
- # Use a truly public IP (8.8.8.8 - Google DNS) for testing.
- remote_addr = "8.8.8.8" # Public IP
- is_private = _is_private_ip(remote_addr)
- is_https = False
-
- should_add = is_https or not is_private
- assert should_add is True
-
- def test_secure_flag_logic_for_localhost(self):
- """Secure flag should be skipped for localhost HTTP connections."""
- from local_deep_research.web.app_factory import _is_private_ip
-
- remote_addr = "127.0.0.1"
- is_private = _is_private_ip(remote_addr)
- is_https = False
-
- should_add = is_https or not is_private
- assert should_add is False
-
- def test_secure_flag_logic_for_https(self):
- """Secure flag should always be added for HTTPS connections."""
- from local_deep_research.web.app_factory import _is_private_ip
-
- # Even localhost should get secure flag with HTTPS
- remote_addr = "127.0.0.1"
- is_private = _is_private_ip(remote_addr)
- is_https = True
-
- should_add = is_https or not is_private
- assert should_add is True
-
- def test_secure_flag_logic_for_lan_ip(self):
- """Secure flag should be skipped for LAN IP HTTP connections."""
- from local_deep_research.web.app_factory import _is_private_ip
-
- # LAN IP + HTTP = should NOT add secure (LAN traffic is allowed over HTTP)
- remote_addr = "192.168.1.100"
- is_private = _is_private_ip(remote_addr)
- is_https = False
-
- should_add = is_https or not is_private
- assert should_add is False
+ The middleware adds the Secure flag iff the request is HTTPS, regardless
+ of source IP. ProxyFix translates X-Forwarded-Proto into wsgi.url_scheme
+ before this middleware runs.
+ """
- def test_secure_flag_logic_for_docker_network(self):
- """Secure flag should be skipped for Docker network IPs."""
- from local_deep_research.web.app_factory import _is_private_ip
+ def _make_middleware(self, testing_mode=False):
+ from local_deep_research.web.app_factory import (
+ SecureCookieMiddleware,
+ )
- # Docker typically uses 172.17.x.x
- remote_addr = "172.17.0.2"
- is_private = _is_private_ip(remote_addr)
- is_https = False
+ def inner(environ, start_response):
+ start_response(
+ "200 OK", [("Set-Cookie", "session=abc; Path=/; HttpOnly")]
+ )
+ return [b""]
+
+ flask_app = Mock()
+ flask_app.config = {"LDR_TESTING_MODE": testing_mode}
+ return SecureCookieMiddleware(inner, flask_app)
+
+ def _capture_headers(self, mw, environ):
+ captured = {}
+
+ def start_response(status, headers, exc_info=None):
+ captured["headers"] = headers
+
+ list(mw(environ, start_response))
+ return captured["headers"]
+
+ def test_http_does_not_add_secure_regardless_of_source(self):
+ """HTTP requests never get Secure, even from public IPs (#3849)."""
+ mw = self._make_middleware()
+ for remote_addr in [
+ "127.0.0.1",
+ "192.168.1.100",
+ "172.17.0.2",
+ "8.8.8.8",
+ # Docker Desktop NAT gateway range that triggered #3849
+ "172.67.130.145",
+ ]:
+ headers = self._capture_headers(
+ mw,
+ {"REMOTE_ADDR": remote_addr, "wsgi.url_scheme": "http"},
+ )
+ cookie = next(v for n, v in headers if n.lower() == "set-cookie")
+ assert "Secure" not in cookie, (
+ f"HTTP from {remote_addr} should not get Secure flag"
+ )
- should_add = is_https or not is_private
- assert should_add is False
+ def test_https_adds_secure(self):
+ """HTTPS requests always get Secure."""
+ mw = self._make_middleware()
+ headers = self._capture_headers(
+ mw, {"REMOTE_ADDR": "8.8.8.8", "wsgi.url_scheme": "https"}
+ )
+ cookie = next(v for n, v in headers if n.lower() == "set-cookie")
+ assert "Secure" in cookie
+
+ def test_testing_mode_skips_secure_even_on_https(self):
+ """LDR_TESTING_MODE disables the Secure flag entirely."""
+ mw = self._make_middleware(testing_mode=True)
+ headers = self._capture_headers(
+ mw, {"REMOTE_ADDR": "8.8.8.8", "wsgi.url_scheme": "https"}
+ )
+ cookie = next(v for n, v in headers if n.lower() == "set-cookie")
+ assert "Secure" not in cookie
+
+ def test_warning_fires_once_per_instance(self):
+ """The HTTP-to-public-IP warning is one-shot per middleware instance."""
+ mw = self._make_middleware()
+ env = {"REMOTE_ADDR": "8.8.8.8", "wsgi.url_scheme": "http"}
+ with patch("local_deep_research.web.app_factory.logger") as mock_logger:
+ self._capture_headers(mw, env)
+ self._capture_headers(mw, env)
+ self._capture_headers(mw, env)
+ warning_calls = [
+ c
+ for c in mock_logger.warning.call_args_list
+ if "Serving HTTP to non-private client" in c.args[0]
+ ]
+ assert len(warning_calls) == 1
+
+ def test_warning_does_not_fire_for_private_ip(self):
+ """No warning when end-user IP is in a private range."""
+ mw = self._make_middleware()
+ with patch("local_deep_research.web.app_factory.logger") as mock_logger:
+ self._capture_headers(
+ mw,
+ {
+ "REMOTE_ADDR": "192.168.1.100",
+ "wsgi.url_scheme": "http",
+ },
+ )
+ warning_calls = [
+ c
+ for c in mock_logger.warning.call_args_list
+ if "Serving HTTP to non-private client" in c.args[0]
+ ]
+ assert not warning_calls
class TestSessionConfiguration:
diff --git a/tests/web/test_app_factory_coverage.py b/tests/web/test_app_factory_coverage.py
index 5e233c2031..7020746af1 100644
--- a/tests/web/test_app_factory_coverage.py
+++ b/tests/web/test_app_factory_coverage.py
@@ -151,46 +151,6 @@ class TestRegisterErrorHandlers:
data = response.get_json()
assert "error" in data
- def test_csrf_error_http_public_ip_path(self):
- """CSRF handler with HTTP + public IP shows detailed help message."""
- from local_deep_research.web.app_factory import register_error_handlers
-
- try:
- from flask_wtf.csrf import CSRFError, CSRFProtect # noqa: F401
- except ImportError:
- pytest.skip("flask_wtf not available")
-
- app = _minimal_app()
- app.config["WTF_CSRF_ENABLED"] = True
- app.config["SECRET_KEY"] = "test-csrf-public-ip"
- CSRFProtect(app)
- register_error_handlers(app)
-
- @app.route("/csrf-test", methods=["POST"])
- def csrf_test():
- return "ok"
-
- app.test_client()
- # Simulate request from a "public" remote address by overriding environ
- with app.test_request_context(
- "/csrf-test",
- method="POST",
- environ_base={"REMOTE_ADDR": "8.8.8.8"},
- headers={"X-Forwarded-For": "8.8.8.8"},
- ):
- # Manually invoke the error handler logic
-
- err = CSRFError()
- err.description = "The CSRF token is missing."
-
- # Locate and call the handler directly
- handler = app.error_handler_spec[None][None].get(CSRFError)
- if handler is None:
- pytest.skip("CSRFError handler not found")
- resp = handler(err)
- # Response should be 400 with JSON containing "error"
- assert resp is not None
-
class TestNewsApiExceptionHandler:
"""Tests for the NewsAPIException error handler."""
diff --git a/tests/web/test_app_factory_middleware.py b/tests/web/test_app_factory_middleware.py
index ae0660a3d8..db5d2f29f6 100644
--- a/tests/web/test_app_factory_middleware.py
+++ b/tests/web/test_app_factory_middleware.py
@@ -1,81 +1,17 @@
"""
Tests for app_factory middleware components: _is_private_ip, DiskSpoolingRequest,
SecureCookieMiddleware, and ServerHeaderMiddleware.
-
-Since SecureCookieMiddleware and ServerHeaderMiddleware are inner classes defined
-inside create_app(), they cannot be directly imported. We replicate their exact
-logic in standalone test versions and verify behavior at the WSGI level.
"""
import ipaddress
from flask import Flask, Request
-
-# ---------------------------------------------------------------------------
-# Replicas of the inner middleware classes from app_factory.create_app()
-# These mirror the production code exactly so we can unit-test the WSGI
-# behaviour without spinning up the full application stack.
-# ---------------------------------------------------------------------------
-
-
-def _is_private_ip(ip_str: str) -> bool:
- """Exact copy of local_deep_research.web.app_factory._is_private_ip."""
- try:
- ip = ipaddress.ip_address(ip_str)
- return ip.is_private or ip.is_loopback
- except ValueError:
- return False
-
-
-class SecureCookieMiddleware:
- """Replica of the inner SecureCookieMiddleware from create_app()."""
-
- def __init__(self, wsgi_app, flask_app):
- self.wsgi_app = wsgi_app
- self.flask_app = flask_app
-
- def __call__(self, environ, start_response):
- should_add_secure = self._should_add_secure_flag(environ)
-
- def custom_start_response(status, headers, exc_info=None):
- if should_add_secure:
- 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):
- if self.flask_app.config.get("LDR_TESTING_MODE"):
- return False
- remote_addr = environ.get("REMOTE_ADDR", "")
- is_private = _is_private_ip(remote_addr)
- is_https = environ.get("wsgi.url_scheme") == "https"
- return is_https or not is_private
-
-
-class ServerHeaderMiddleware:
- """Replica of the inner ServerHeaderMiddleware from create_app()."""
-
- def __init__(self, wsgi_app):
- self.wsgi_app = wsgi_app
-
- def __call__(self, environ, start_response):
- def custom_start_response(status, headers, exc_info=None):
- filtered_headers = [
- (name, value)
- for name, value in headers
- if name.lower() != "server"
- ]
- return start_response(status, filtered_headers, exc_info)
-
- return self.wsgi_app(environ, custom_start_response)
+from local_deep_research.web.app_factory import (
+ SecureCookieMiddleware,
+ ServerHeaderMiddleware,
+ _is_private_ip,
+)
# ---------------------------------------------------------------------------
@@ -114,44 +50,36 @@ class TestIsPrivateIp:
"""Unit tests for the module-level _is_private_ip helper."""
def test_loopback_ipv4(self):
- from local_deep_research.web.app_factory import _is_private_ip
assert _is_private_ip("127.0.0.1") is True
def test_loopback_ipv6(self):
- from local_deep_research.web.app_factory import _is_private_ip
assert _is_private_ip("::1") is True
def test_class_a_private(self):
- from local_deep_research.web.app_factory import _is_private_ip
assert _is_private_ip("10.0.0.1") is True
def test_class_b_private(self):
- from local_deep_research.web.app_factory import _is_private_ip
assert _is_private_ip("172.16.0.1") is True
def test_class_c_private(self):
- from local_deep_research.web.app_factory import _is_private_ip
assert _is_private_ip("192.168.1.1") is True
def test_public_google_dns(self):
- from local_deep_research.web.app_factory import _is_private_ip
assert _is_private_ip("8.8.8.8") is False
def test_public_cloudflare_dns(self):
- from local_deep_research.web.app_factory import _is_private_ip
assert _is_private_ip("1.1.1.1") is False
def test_public_documentation_range(self):
"""203.0.113.0/24 (TEST-NET-3) is documentation/reserved, not routable.
Python's ipaddress module treats it as private."""
- from local_deep_research.web.app_factory import _is_private_ip
# This is actually considered private by Python's ipaddress module
# because it is reserved. Verify against the real implementation.
@@ -160,28 +88,23 @@ class TestIsPrivateIp:
assert result == (ip.is_private or ip.is_loopback)
def test_invalid_string(self):
- from local_deep_research.web.app_factory import _is_private_ip
assert _is_private_ip("not-an-ip") is False
def test_empty_string(self):
- from local_deep_research.web.app_factory import _is_private_ip
assert _is_private_ip("") is False
def test_invalid_octet_values(self):
- from local_deep_research.web.app_factory import _is_private_ip
assert _is_private_ip("256.256.256.256") is False
def test_ipv6_private(self):
- from local_deep_research.web.app_factory import _is_private_ip
# fc00::/7 is unique local address (private)
assert _is_private_ip("fc00::1") is True
def test_ipv6_public(self):
- from local_deep_research.web.app_factory import _is_private_ip
# 2001:4860:4860::8888 is Google Public DNS IPv6
assert _is_private_ip("2001:4860:4860::8888") is False
@@ -230,160 +153,141 @@ class TestDiskSpoolingRequest:
class TestSecureCookieMiddlewareShouldAddSecure:
- """Tests for SecureCookieMiddleware._should_add_secure_flag decision logic."""
+ """Tests for SecureCookieMiddleware._should_add_secure_flag decision logic.
+
+ The new rule is: add Secure iff wsgi.url_scheme == 'https' (and not in
+ testing mode). Source IP no longer affects the decision.
+ """
def _make_middleware(self, **config):
flask_app = Flask(__name__)
flask_app.config["LDR_TESTING_MODE"] = False
flask_app.config.update(config)
- mw = SecureCookieMiddleware(wsgi_app=None, flask_app=flask_app)
- return mw
+ return SecureCookieMiddleware(wsgi_app=None, flask_app=flask_app)
def test_testing_mode_returns_false(self):
mw = self._make_middleware(LDR_TESTING_MODE=True)
environ = {"REMOTE_ADDR": "8.8.8.8", "wsgi.url_scheme": "https"}
assert mw._should_add_secure_flag(environ) is False
- def test_private_ip_http_returns_false(self):
- mw = self._make_middleware()
- environ = {"REMOTE_ADDR": "127.0.0.1", "wsgi.url_scheme": "http"}
- assert mw._should_add_secure_flag(environ) is False
-
- def test_private_ip_192_168_http_returns_false(self):
- mw = self._make_middleware()
- environ = {"REMOTE_ADDR": "192.168.1.1", "wsgi.url_scheme": "http"}
- assert mw._should_add_secure_flag(environ) is False
-
- def test_private_ip_10_x_http_returns_false(self):
- mw = self._make_middleware()
- environ = {"REMOTE_ADDR": "10.0.0.1", "wsgi.url_scheme": "http"}
- assert mw._should_add_secure_flag(environ) is False
-
- def test_private_ip_172_16_http_returns_false(self):
- mw = self._make_middleware()
- environ = {"REMOTE_ADDR": "172.16.0.1", "wsgi.url_scheme": "http"}
- assert mw._should_add_secure_flag(environ) is False
-
- def test_ipv6_loopback_http_returns_false(self):
- mw = self._make_middleware()
- environ = {"REMOTE_ADDR": "::1", "wsgi.url_scheme": "http"}
- assert mw._should_add_secure_flag(environ) is False
-
- def test_public_ip_http_returns_true(self):
+ def test_http_returns_false_regardless_of_source_ip(self):
+ """HTTP requests never get Secure, even from public IPs (#3849)."""
mw = self._make_middleware()
- environ = {"REMOTE_ADDR": "8.8.8.8", "wsgi.url_scheme": "http"}
- assert mw._should_add_secure_flag(environ) is True
+ for remote_addr in [
+ "127.0.0.1",
+ "::1",
+ "192.168.1.1",
+ "10.0.0.1",
+ "172.16.0.1",
+ "172.17.0.2", # Default Docker bridge
+ "172.67.130.145", # Docker Desktop NAT (the #3849 trigger)
+ "8.8.8.8",
+ "1.1.1.1",
+ "",
+ ]:
+ environ = {
+ "REMOTE_ADDR": remote_addr,
+ "wsgi.url_scheme": "http",
+ }
+ assert mw._should_add_secure_flag(environ) is False, (
+ f"HTTP from {remote_addr!r} should not get Secure"
+ )
- def test_public_ip_1_1_1_1_http_returns_true(self):
+ def test_https_returns_true_regardless_of_source_ip(self):
mw = self._make_middleware()
- environ = {"REMOTE_ADDR": "1.1.1.1", "wsgi.url_scheme": "http"}
- assert mw._should_add_secure_flag(environ) is True
+ for remote_addr in ["127.0.0.1", "192.168.1.1", "8.8.8.8"]:
+ environ = {
+ "REMOTE_ADDR": remote_addr,
+ "wsgi.url_scheme": "https",
+ }
+ assert mw._should_add_secure_flag(environ) is True
- def test_https_with_private_ip_returns_true(self):
- mw = self._make_middleware()
- environ = {"REMOTE_ADDR": "127.0.0.1", "wsgi.url_scheme": "https"}
- assert mw._should_add_secure_flag(environ) is True
- def test_https_with_public_ip_returns_true(self):
- mw = self._make_middleware()
- environ = {"REMOTE_ADDR": "8.8.8.8", "wsgi.url_scheme": "https"}
- assert mw._should_add_secure_flag(environ) is True
+class TestSecureCookieMiddlewareCall:
+ """Tests for SecureCookieMiddleware.__call__ cookie header modification."""
- def test_empty_remote_addr_http_returns_true(self):
- """Empty REMOTE_ADDR is not a valid private IP, so returns True
- (non-private + non-HTTPS = add Secure flag)."""
- mw = self._make_middleware()
- environ = {"REMOTE_ADDR": "", "wsgi.url_scheme": "http"}
- # _is_private_ip("") returns False, so not is_private = True
- # is_https = False, so is_https or not is_private = True
- # BUT the spec says returns False for empty string not HTTPS.
- # Let's check what actually happens:
- # _is_private_ip("") -> False (ValueError from ipaddress)
- # not False = True, so should_add = True
- # The user spec says "Returns False when REMOTE_ADDR is empty string
- # and not HTTPS" but the actual code returns True because empty string
- # fails _is_private_ip => not private => add secure flag.
- # We test against what the code actually does.
- assert mw._should_add_secure_flag(environ) is True
-
- def test_missing_remote_addr_http_returns_true(self):
- """Missing REMOTE_ADDR defaults to '' which is not private."""
- mw = self._make_middleware()
- environ = {"wsgi.url_scheme": "http"}
- assert mw._should_add_secure_flag(environ) is True
+ def _capture_headers(self, wrapped, environ):
+ captured = []
+ def start_response(status, headers, exc_info=None):
+ captured.extend(headers)
-class TestSecureCookieMiddlewareCall:
- """Tests for SecureCookieMiddleware.__call__ cookie header modification."""
+ list(wrapped(environ, start_response))
+ return captured
- def test_appends_secure_to_set_cookie_when_public_ip(self):
- """Set-Cookie headers get '; Secure' appended for public IP requests."""
+ def test_no_secure_appended_for_public_ip_http(self):
+ """Public IP over HTTP must NOT get Secure - core fix for #3849."""
app = _make_simple_app()
-
- # Wrap with SecureCookieMiddleware
wrapped = SecureCookieMiddleware(app.wsgi_app, app)
app.wsgi_app = wrapped
- # Flask test client uses 127.0.0.1 by default (private), so we need
- # to test at the WSGI level with a custom environ.
with app.test_request_context():
- environ = {
- "REQUEST_METHOD": "GET",
- "PATH_INFO": "/set-cookie",
- "SERVER_NAME": "localhost",
- "SERVER_PORT": "5000",
- "REMOTE_ADDR": "8.8.8.8",
- "wsgi.url_scheme": "http",
- "wsgi.input": b"",
- }
-
- captured_headers = []
-
- def mock_start_response(status, headers, exc_info=None):
- captured_headers.extend(headers)
-
- list(wrapped(environ, mock_start_response))
-
- cookie_headers = [
- v for n, v in captured_headers if n.lower() == "set-cookie"
- ]
- for cookie_val in cookie_headers:
- assert "; Secure" in cookie_val
+ captured = self._capture_headers(
+ wrapped,
+ {
+ "REQUEST_METHOD": "GET",
+ "PATH_INFO": "/set-cookie",
+ "SERVER_NAME": "localhost",
+ "SERVER_PORT": "5000",
+ "REMOTE_ADDR": "8.8.8.8",
+ "wsgi.url_scheme": "http",
+ "wsgi.input": b"",
+ },
+ )
+ cookies = [v for n, v in captured if n.lower() == "set-cookie"]
+ for cookie in cookies:
+ assert "Secure" not in cookie
def test_no_secure_appended_for_private_ip_http(self):
- """Set-Cookie headers are NOT modified for private IP HTTP requests."""
+ """Private IP HTTP requests are unmodified."""
app = _make_simple_app()
wrapped = SecureCookieMiddleware(app.wsgi_app, app)
app.wsgi_app = wrapped
with app.test_request_context():
- environ = {
- "REQUEST_METHOD": "GET",
- "PATH_INFO": "/set-cookie",
- "SERVER_NAME": "localhost",
- "SERVER_PORT": "5000",
- "REMOTE_ADDR": "127.0.0.1",
- "wsgi.url_scheme": "http",
- "wsgi.input": b"",
- }
-
- captured_headers = []
-
- def mock_start_response(status, headers, exc_info=None):
- captured_headers.extend(headers)
-
- list(wrapped(environ, mock_start_response))
+ captured = self._capture_headers(
+ wrapped,
+ {
+ "REQUEST_METHOD": "GET",
+ "PATH_INFO": "/set-cookie",
+ "SERVER_NAME": "localhost",
+ "SERVER_PORT": "5000",
+ "REMOTE_ADDR": "127.0.0.1",
+ "wsgi.url_scheme": "http",
+ "wsgi.input": b"",
+ },
+ )
+ cookies = [v for n, v in captured if n.lower() == "set-cookie"]
+ for cookie in cookies:
+ assert "Secure" not in cookie
+
+ def test_secure_appended_for_https(self):
+ """HTTPS requests get Secure flag added."""
+ app = _make_simple_app()
+ wrapped = SecureCookieMiddleware(app.wsgi_app, app)
+ app.wsgi_app = wrapped
- cookie_headers = [
- v for n, v in captured_headers if n.lower() == "set-cookie"
- ]
- for cookie_val in cookie_headers:
- assert "; Secure" not in cookie_val
+ with app.test_request_context():
+ captured = self._capture_headers(
+ wrapped,
+ {
+ "REQUEST_METHOD": "GET",
+ "PATH_INFO": "/set-cookie",
+ "SERVER_NAME": "localhost",
+ "SERVER_PORT": "5000",
+ "REMOTE_ADDR": "127.0.0.1",
+ "wsgi.url_scheme": "https",
+ "wsgi.input": b"",
+ },
+ )
+ cookies = [v for n, v in captured if n.lower() == "set-cookie"]
+ assert cookies, "expected at least one Set-Cookie header"
+ for cookie in cookies:
+ assert "Secure" in cookie
def test_no_duplicate_secure_flag(self):
"""If cookie already has '; Secure', don't add it again."""
- # Create a tiny WSGI app that returns a Set-Cookie with Secure already
def inner_app(environ, start_response):
headers = [
("Content-Type", "text/plain"),
@@ -394,27 +298,15 @@ class TestSecureCookieMiddlewareCall:
flask_app = Flask(__name__)
flask_app.config["LDR_TESTING_MODE"] = False
-
wrapped = SecureCookieMiddleware(inner_app, flask_app)
- environ = {
- "REMOTE_ADDR": "8.8.8.8",
- "wsgi.url_scheme": "http",
- }
-
- captured_headers = []
-
- def mock_start_response(status, headers, exc_info=None):
- captured_headers.extend(headers)
-
- list(wrapped(environ, mock_start_response))
-
- cookie_headers = [
- v for n, v in captured_headers if n.lower() == "set-cookie"
- ]
- assert len(cookie_headers) == 1
- # Should still have exactly one "; Secure", not two
- assert cookie_headers[0].count("; Secure") == 1
+ captured = self._capture_headers(
+ wrapped,
+ {"REMOTE_ADDR": "8.8.8.8", "wsgi.url_scheme": "https"},
+ )
+ cookies = [v for n, v in captured if n.lower() == "set-cookie"]
+ assert len(cookies) == 1
+ assert cookies[0].count("; Secure") == 1
def test_non_cookie_headers_unchanged(self):
"""Non-Set-Cookie headers pass through unmodified."""
@@ -430,60 +322,36 @@ class TestSecureCookieMiddlewareCall:
flask_app = Flask(__name__)
flask_app.config["LDR_TESTING_MODE"] = False
-
wrapped = SecureCookieMiddleware(inner_app, flask_app)
- environ = {
- "REMOTE_ADDR": "8.8.8.8",
- "wsgi.url_scheme": "http",
- }
-
- captured_headers = []
-
- def mock_start_response(status, headers, exc_info=None):
- captured_headers.extend(headers)
-
- list(wrapped(environ, mock_start_response))
-
- # Content-Type and X-Custom should be untouched
- content_type = [v for n, v in captured_headers if n == "Content-Type"]
+ captured = self._capture_headers(
+ wrapped,
+ {"REMOTE_ADDR": "8.8.8.8", "wsgi.url_scheme": "http"},
+ )
+ content_type = [v for n, v in captured if n == "Content-Type"]
assert content_type == ["text/html"]
-
- x_custom = [v for n, v in captured_headers if n == "X-Custom"]
+ x_custom = [v for n, v in captured if n == "X-Custom"]
assert x_custom == ["value123"]
def test_testing_mode_leaves_cookies_alone(self):
"""When LDR_TESTING_MODE is True, cookies are never modified."""
def inner_app(environ, start_response):
- headers = [
- ("Set-Cookie", "test=value"),
- ]
+ headers = [("Set-Cookie", "test=value")]
start_response("200 OK", headers)
return [b"ok"]
flask_app = Flask(__name__)
flask_app.config["LDR_TESTING_MODE"] = True
-
wrapped = SecureCookieMiddleware(inner_app, flask_app)
- environ = {
- "REMOTE_ADDR": "8.8.8.8",
- "wsgi.url_scheme": "https",
- }
-
- captured_headers = []
-
- def mock_start_response(status, headers, exc_info=None):
- captured_headers.extend(headers)
-
- list(wrapped(environ, mock_start_response))
-
- cookie_headers = [
- v for n, v in captured_headers if n.lower() == "set-cookie"
- ]
- assert cookie_headers == ["test=value"]
- assert "; Secure" not in cookie_headers[0]
+ captured = self._capture_headers(
+ wrapped,
+ {"REMOTE_ADDR": "8.8.8.8", "wsgi.url_scheme": "https"},
+ )
+ cookies = [v for n, v in captured if n.lower() == "set-cookie"]
+ assert cookies == ["test=value"]
+ assert "Secure" not in cookies[0]
# ===================================================================
@@ -637,86 +505,83 @@ class TestMiddlewareComposition:
"""Test that SecureCookieMiddleware and ServerHeaderMiddleware
compose correctly when stacked (as they are in production)."""
- def test_stacked_middlewares(self):
- """Server header is removed AND Secure flag is added when appropriate."""
-
- def inner_app(environ, start_response):
- headers = [
- ("Content-Type", "text/plain"),
- ("Set-Cookie", "sid=abc123"),
- ("Server", "Werkzeug/2.3.0"),
- ]
- start_response("200 OK", headers)
- return [b"ok"]
-
- flask_app = Flask(__name__)
- flask_app.config["LDR_TESTING_MODE"] = False
-
- # Stack in the same order as create_app:
- # inner -> ProxyFix -> SecureCookieMiddleware -> ServerHeaderMiddleware
- secure_mw = SecureCookieMiddleware(inner_app, flask_app)
- server_mw = ServerHeaderMiddleware(secure_mw)
-
- environ = {
- "REMOTE_ADDR": "8.8.8.8",
- "wsgi.url_scheme": "http",
- }
-
- captured_headers = []
-
- def mock_start_response(status, headers, exc_info=None):
- captured_headers.extend(headers)
-
- list(server_mw(environ, mock_start_response))
-
- header_names = [n for n, v in captured_headers]
- # Server header should be removed
- assert "Server" not in header_names
-
- # Set-Cookie should have Secure flag (public IP + HTTP)
- cookie_headers = [
- v for n, v in captured_headers if n.lower() == "set-cookie"
- ]
- assert len(cookie_headers) == 1
- assert "; Secure" in cookie_headers[0]
-
- # Content-Type should pass through
- assert ("Content-Type", "text/plain") in captured_headers
-
- def test_stacked_middlewares_private_ip(self):
- """Private IP: no Secure flag added, Server header still removed."""
+ def _run_stack(self, environ, set_cookies, with_server_header=True):
+ """Run inner -> SecureCookie -> ProxyFix -> ServerHeader stack."""
+ from werkzeug.middleware.proxy_fix import ProxyFix
def inner_app(environ, start_response):
- headers = [
- ("Set-Cookie", "sid=abc123"),
- ("Server", "Werkzeug"),
+ headers = [("Content-Type", "text/plain")] + [
+ ("Set-Cookie", c) for c in set_cookies
]
+ if with_server_header:
+ headers.append(("Server", "Werkzeug/2.3.0"))
start_response("200 OK", headers)
return [b"ok"]
flask_app = Flask(__name__)
flask_app.config["LDR_TESTING_MODE"] = False
- secure_mw = SecureCookieMiddleware(inner_app, flask_app)
- server_mw = ServerHeaderMiddleware(secure_mw)
+ # Match create_app's wrap order:
+ # inner -> SecureCookie (innermost) -> ProxyFix -> ServerHeader (outer)
+ wsgi = SecureCookieMiddleware(inner_app, flask_app)
+ wsgi = ProxyFix(wsgi, x_for=1, x_proto=1)
+ wsgi = ServerHeaderMiddleware(wsgi)
- environ = {
- "REMOTE_ADDR": "192.168.1.100",
- "wsgi.url_scheme": "http",
- }
+ captured = []
- captured_headers = []
+ def start_response(status, headers, exc_info=None):
+ captured.extend(headers)
- def mock_start_response(status, headers, exc_info=None):
- captured_headers.extend(headers)
+ list(wsgi(environ, start_response))
+ return captured
- list(server_mw(environ, mock_start_response))
-
- header_names_lower = [n.lower() for n, v in captured_headers]
- assert "server" not in header_names_lower
-
- cookie_headers = [
- v for n, v in captured_headers if n.lower() == "set-cookie"
- ]
- assert len(cookie_headers) == 1
- assert "; Secure" not in cookie_headers[0]
+ def test_stacked_http_public_ip_no_secure(self):
+ """Public IP over HTTP: no Secure flag, Server header stripped."""
+ captured = self._run_stack(
+ {"REMOTE_ADDR": "8.8.8.8", "wsgi.url_scheme": "http"},
+ set_cookies=["sid=abc123"],
+ )
+ assert "Server" not in [n for n, _ in captured]
+ cookies = [v for n, v in captured if n.lower() == "set-cookie"]
+ assert len(cookies) == 1
+ assert "Secure" not in cookies[0]
+ assert ("Content-Type", "text/plain") in captured
+
+ def test_stacked_https_adds_secure(self):
+ """HTTPS request gets Secure flag added."""
+ captured = self._run_stack(
+ {"REMOTE_ADDR": "8.8.8.8", "wsgi.url_scheme": "https"},
+ set_cookies=["sid=abc123"],
+ )
+ cookies = [v for n, v in captured if n.lower() == "set-cookie"]
+ assert len(cookies) == 1
+ assert "Secure" in cookies[0]
+
+ def test_stacked_private_ip_no_secure(self):
+ """Private IP over HTTP: no Secure flag, Server header stripped."""
+ captured = self._run_stack(
+ {"REMOTE_ADDR": "192.168.1.100", "wsgi.url_scheme": "http"},
+ set_cookies=["sid=abc123"],
+ with_server_header=True,
+ )
+ assert "Server" not in [n for n, _ in captured]
+ cookies = [v for n, v in captured if n.lower() == "set-cookie"]
+ assert len(cookies) == 1
+ assert "Secure" not in cookies[0]
+
+ def test_stacked_proxyfix_translates_xfp_https(self):
+ """ProxyFix should rewrite scheme from X-Forwarded-Proto, after
+ which SecureCookieMiddleware adds Secure even though the raw
+ wsgi.url_scheme is http."""
+ captured = self._run_stack(
+ {
+ "REMOTE_ADDR": "10.0.0.1", # trusted proxy
+ "wsgi.url_scheme": "http",
+ "HTTP_X_FORWARDED_PROTO": "https",
+ "HTTP_X_FORWARDED_FOR": "203.0.113.50",
+ },
+ set_cookies=["sid=abc123"],
+ )
+ cookies = [v for n, v in captured if n.lower() == "set-cookie"]
+ assert len(cookies) == 1
+ assert "Secure" in cookies[0]
diff --git a/tests/web/test_error_handler_behavior.py b/tests/web/test_error_handler_behavior.py
index a051d656fb..91cc93d08a 100644
--- a/tests/web/test_error_handler_behavior.py
+++ b/tests/web/test_error_handler_behavior.py
@@ -199,40 +199,15 @@ class TestCsrfErrorHandler:
response = handler(error)
return response
- def test_csrf_private_ip_http_generic_message(self, app):
- """Private IP over HTTP gets generic CSRF error (no public IP warning)."""
- response = self._trigger_csrf(app, "192.168.1.1")
- data = response.get_json()
- assert "public IP" not in data["error"]
- assert "HTTP from a" not in data["error"]
-
- def test_csrf_public_ip_http_detailed_message(self, app):
- """Public IP over HTTP gets detailed guidance about HTTPS."""
- response = self._trigger_csrf(app, "8.8.8.8")
- data = response.get_json()
- assert "HTTP" in data["error"] or "public IP" in data["error"]
- assert "Solutions" in data["error"]
-
- def test_csrf_proxied_request_gets_guidance(self, app):
- """Proxied request (X-Forwarded-For) gets proxy/HTTPS guidance."""
- response = self._trigger_csrf(
- app, "192.168.1.1", forwarded_for="203.0.113.1"
- )
- data = response.get_json()
- # Proxied + private IP + HTTP => is_proxied=True => detailed message
- assert "Solutions" in data["error"]
-
- def test_csrf_https_no_http_warning(self, app):
- """HTTPS requests get standard CSRF error, no HTTP-specific warning."""
- response = self._trigger_csrf(app, "8.8.8.8", is_secure=True)
- data = response.get_json()
- # is_http=False, so the detailed message branch is not taken
- assert "HTTP from a" not in data["error"]
-
- def test_csrf_error_does_not_leak_raw_ip(self, app):
- """Error message should not contain the raw client IP address."""
+ def test_csrf_error_returns_description_as_json(self, app):
+ """CSRF errors return the error description as JSON, regardless of
+ source IP or scheme. The old IP-based 'use HTTPS' branch is gone."""
response = self._trigger_csrf(app, "8.8.8.8")
+ assert response.status_code == 400
data = response.get_json()
+ assert "error" in data
+ # No IP-specific guidance is added anymore
+ assert "Solutions" not in data["error"]
assert "8.8.8.8" not in data["error"]
def test_csrf_returns_400_status(self, app):