~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(security): green the WebSocket-CORS unit suite + fix stale '*' default docs (#3091 follow-up) (#4807)
LearningCircuit2990fb8ecf7b
diff --git a/changelog.d/4807.security.md b/changelog.d/4807.security.mdnew file mode 100644index 0000000000..ab422393e9--- /dev/null+++ b/changelog.d/4807.security.md@@ -0,0 +1 @@+**WebSocket/Socket.IO connections now default to same-origin only.** When `LDR_SECURITY_WEBSOCKET_ALLOWED_ORIGINS` is unset or empty, cross-origin WebSocket connections are rejected instead of being allowed from any origin — closing a Cross-Site WebSocket Hijacking gap as defense-in-depth (the session cookie's `SameSite=Lax` already blocked the classic cross-site case) and matching the same-origin default already used for HTTP CORS. To run a cross-origin front-end, set `LDR_SECURITY_WEBSOCKET_ALLOWED_ORIGINS` (and `LDR_SECURITY_CORS_ALLOWED_ORIGINS`) to its origin. If you terminate TLS at a reverse proxy, forward `X-Forwarded-Proto` so the same-origin check sees `https` — otherwise the WebSocket handshake is rejected (see the troubleshooting guide). Set `*` to restore the previous allow-all behavior on trusted local/dev networks. A rejected WebSocket handshake is now logged with a warning naming the origin and how to allow it, so a misconfigured origin is diagnosable instead of a silently frozen progress UI.diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.mdindex f9f24fd098..c569783eb7 100644--- a/docs/CONFIGURATION.md+++ b/docs/CONFIGURATION.md@@ -54,7 +54,7 @@ They are not available in the Web UI because they are needed to start the applic| `LDR_NOTIFICATIONS_ALLOW_PRIVATE_IPS` | Boolean | `False` | No | | Allow notification webhooks to target private/local IP addresses. Environment-only to prevent SSRF bypass via the user-writable settings API. Only enable this if your notification endpoints are on a trusted local network. | Security | || `LDR_SECURITY_ALLOW_NAT64` | Boolean | `False` | No | | Allow outbound traffic to NAT64 prefixes (64:ff9b::/96 RFC 6052 well-known and 64:ff9b:1::/48 RFC 8215 local-use). Disabled by default to close the IPv6-wrapped SSRF bypass class — on hosts configured with NAT64 routes, attacker-supplied URLs can wrap cloud-metadata or RFC1918 destinations through these prefixes. Enable only on IPv6-only deployments (DNS64+NAT64) where outbound IPv4 traffic is synthesized through this prefix and the operator has accepted the residual SSRF risk. 6to4 (2002::/16), Teredo (2001::/32), and the discard prefix (100::/64) remain unconditionally blocked because they have no live legitimate use in 2026. The cloud-metadata block (ALWAYS_BLOCKED_METADATA_IPS) still applies via embedded-IPv4 extraction — see SECURITY.md. | Security | || `LDR_SECURITY_CORS_ALLOWED_ORIGINS` | String | `None` | No | | Allowed CORS origins for API routes (comma-separated). Use '*' for all origins, empty for same-origin only. Example: 'https://example.com,https://app.example.com' | Security | |-| `LDR_SECURITY_WEBSOCKET_ALLOWED_ORIGINS` | String | `None` | No | | Allowed origins for WebSocket/Socket.IO connections (comma-separated). Use '*' for all origins (default), empty for same-origin only. Example: 'https://example.com,https://app.example.com' | Security | |+| `LDR_SECURITY_WEBSOCKET_ALLOWED_ORIGINS` | String | `None` | No | | Allowed origins for WebSocket/Socket.IO connections (comma-separated). Unset or empty means same-origin only (default); use '*' to allow all origins. Example: 'https://example.com,https://app.example.com' | Security | || `LDR_SERVER_MAX_CONCURRENT_RESEARCH` | Integer | `10` | No | 1..1000 | Server-wide maximum concurrent research operations. Requires restart. | Server | LDR_MAX_GLOBAL_CONCURRENT || `LDR_TESTING_TEST_MODE` | Boolean | `False` | No | | Enable test mode (adds delays for testing concurrency) | Testing | |diff --git a/docs/env_configuration.md b/docs/env_configuration.mdindex 74f3f0ac85..ce6da9b33a 100644--- a/docs/env_configuration.md+++ b/docs/env_configuration.md@@ -234,16 +234,17 @@ WebSocket connections also require an authenticated session in addition to passi**Examples:**```bash-# Allow all origins for both API and WebSocket-export LDR_SECURITY_CORS_ALLOWED_ORIGINS="*"-export LDR_SECURITY_WEBSOCKET_ALLOWED_ORIGINS="*"+# Same-origin only (the default — leave both unset, shown here for clarity)+export LDR_SECURITY_WEBSOCKET_ALLOWED_ORIGINS=""-# Restrict to specific origins+# Allow specific cross-origin front-ends (recommended when you need cross-origin)export LDR_SECURITY_CORS_ALLOWED_ORIGINS="https://example.com,https://app.example.com"export LDR_SECURITY_WEBSOCKET_ALLOWED_ORIGINS="https://example.com,https://app.example.com"-# Same-origin only (strictest)-export LDR_SECURITY_WEBSOCKET_ALLOWED_ORIGINS=""+# Allow ALL origins — disables CORS/WebSocket origin checks.+# Trusted local/dev networks only; do not use in production.+export LDR_SECURITY_CORS_ALLOWED_ORIGINS="*"+export LDR_SECURITY_WEBSOCKET_ALLOWED_ORIGINS="*"```**Docker Compose example:**@@ -252,8 +253,10 @@ export LDR_SECURITY_WEBSOCKET_ALLOWED_ORIGINS=""services:local-deep-research:environment:- - LDR_SECURITY_CORS_ALLOWED_ORIGINS=*- - LDR_SECURITY_WEBSOCKET_ALLOWED_ORIGINS=*+ # Same-origin is the secure default — omit these unless you serve the UI+ # from a different origin, then list it explicitly (avoid "*").+ - LDR_SECURITY_CORS_ALLOWED_ORIGINS=https://app.example.com+ - LDR_SECURITY_WEBSOCKET_ALLOWED_ORIGINS=https://app.example.com```-**Note:** If WebSocket connections fail after upgrading, set `LDR_SECURITY_WEBSOCKET_ALLOWED_ORIGINS=*` to restore the previous permissive behavior.+**Note:** If WebSocket connections fail after upgrading to the same-origin default, the usual cause is a TLS-terminating reverse proxy that doesn't forward `X-Forwarded-Proto` (see the Socket.IO proxy snippet in [troubleshooting](troubleshooting.md) — the same header is needed for secure cookies/HSTS). Otherwise, set `LDR_SECURITY_WEBSOCKET_ALLOWED_ORIGINS` to your front-end origin (e.g. `https://app.example.com`); a fully cross-origin front-end must also set `LDR_SECURITY_CORS_ALLOWED_ORIGINS`. Using `*` re-enables allow-all and is not recommended outside trusted local/dev networks.diff --git a/docs/troubleshooting.md b/docs/troubleshooting.mdindex f1d4da1ee3..c77af3a8de 100644--- a/docs/troubleshooting.md+++ b/docs/troubleshooting.md@@ -340,6 +340,11 @@ python -m local_deep_research.web_search_engines.rate_limiting export --format cproxy_set_header Upgrade $http_upgrade;proxy_set_header Connection "upgrade";proxy_set_header Host $host;+ # Required when terminating TLS at the proxy: without X-Forwarded-Proto+ # the same-origin WebSocket check (the default) sees http:// and rejects+ # the browser's https Origin. Also needed for secure cookies / HSTS.+ proxy_set_header X-Forwarded-Proto $scheme;+ proxy_set_header X-Forwarded-Host $host;proxy_read_timeout 86400;}```diff --git a/src/local_deep_research/settings/env_definitions/security.py b/src/local_deep_research/settings/env_definitions/security.pyindex a2f2a7c296..1f06aeff8f 100644--- a/src/local_deep_research/settings/env_definitions/security.py+++ b/src/local_deep_research/settings/env_definitions/security.py@@ -29,7 +29,7 @@ SECURITY_SETTINGS = [key="security.websocket.allowed_origins",description=("Allowed origins for WebSocket/Socket.IO connections (comma-separated). "- "Use '*' for all origins (default), empty for same-origin only. "+ "Unset or empty means same-origin only (default); use '*' to allow all origins. ""Example: 'https://example.com,https://app.example.com'"),default=None,diff --git a/src/local_deep_research/web/services/socket_service.py b/src/local_deep_research/web/services/socket_service.pyindex 74dc5fc092..79f087bc42 100644--- a/src/local_deep_research/web/services/socket_service.py+++ b/src/local_deep_research/web/services/socket_service.py@@ -11,6 +11,54 @@ from ...database.session_passwords import session_password_storefrom ..routes.globals import get_active_research_snapshot+def _install_origin_rejection_logging(socketio: SocketIO) -> bool:+ """Re-emit engine.io's silenced WebSocket origin rejections via loguru.++ engine.io validates the Origin at handshake and calls+ ``_log_error_once('<origin> is not an accepted origin.', 'bad-origin')``,+ but the server runs with ``logger=False`` so that message never surfaces —+ the only symptom of a misconfigured WebSocket origin is a frozen progress+ UI. Wrap that one call to log a WARNING (deduped per origin) pointing at the+ fix. An Origin is a scheme+host, not PII. Best-effort: a no-op (returns+ False) if engine.io internals change, so it can never break startup.++ The dedup set is capped: the handshake is pre-auth and ``Origin`` is+ attacker-controlled, so an unbounded set would be a memory-growth + log-+ amplification vector. After ``cap`` distinct origins we stop tracking/warning+ (an operator has more than enough signal by then).+ """+ try:+ eio = socketio.server.eio+ original = eio._log_error_once+ except AttributeError:+ logger.debug(+ "Socket.IO: origin-rejection logging not installed "+ "(engine.io internals changed); handshake rejections stay silent"+ )+ return False++ warned: set[str] = set()+ cap = 100++ def _log_error_once(message, message_key):+ if (+ message_key == "bad-origin"+ and len(warned) < cap+ and message not in warned+ ):+ warned.add(message)+ logger.warning(+ f"Socket.IO rejected a WebSocket handshake: {message} Set "+ "LDR_SECURITY_WEBSOCKET_ALLOWED_ORIGINS to this origin if it is "+ "your front-end; behind a TLS-terminating proxy, also forward "+ "X-Forwarded-Proto so the same-origin check sees https."+ )+ return original(message, message_key)++ eio._log_error_once = _log_error_once+ return True++class SocketIOService:"""Singleton class for managing SocketIO connections and subscriptions.@@ -84,6 +132,12 @@ class SocketIOService:ping_interval=5,)+ # Make a rejected WebSocket origin diagnosable (otherwise it is a silent+ # frozen progress UI). Skipped for the allow-all case, which rejects+ # nothing.+ if socketio_cors != "*":+ _install_origin_rejection_logging(self.__socketio)+# Socket subscription tracking.self.__socket_subscriptions: dict[str, Any] = {}# Set to false to disable logging in the event handlers. This candiff --git a/tests/security/test_security_headers_gaps.py b/tests/security/test_security_headers_gaps.pyindex ba81757213..023e7b3103 100644--- a/tests/security/test_security_headers_gaps.py+++ b/tests/security/test_security_headers_gaps.py@@ -220,6 +220,71 @@ class TestCorsHeaders:resp = client.get("/api/test")assert resp.headers["Access-Control-Max-Age"] == "3600"+ def test_vary_origin_present_when_acao_is_dynamic(self):+ """A reflected (non-wildcard) ACAO must carry Vary: Origin so shared+ caches don't serve one origin's ACAO to another."""+ app = _make_app(+ SECURITY_CORS_ALLOWED_ORIGINS="https://a.com,https://b.com",+ )++ @app.route("/api/test")+ def api_test():+ return "ok"++ with app.test_client() as client:+ resp = client.get("/api/test", headers={"Origin": "https://b.com"})+ assert (+ resp.headers["Access-Control-Allow-Origin"] == "https://b.com"+ )+ vary_tokens = [+ v.strip().lower()+ for v in resp.headers.get("Vary", "").split(",")+ ]+ assert "origin" in vary_tokens++ def test_vary_origin_absent_for_wildcard(self):+ """A fixed wildcard ACAO is the same for every origin, so it must NOT+ add Vary: Origin (which would needlessly fragment caches)."""+ app = _make_app(SECURITY_CORS_ALLOWED_ORIGINS="*")++ @app.route("/api/test")+ def api_test():+ return "ok"++ with app.test_client() as client:+ resp = client.get("/api/test", headers={"Origin": "https://x.com"})+ assert resp.headers["Access-Control-Allow-Origin"] == "*"+ vary_tokens = [+ v.strip().lower()+ for v in resp.headers.get("Vary", "").split(",")+ ]+ assert "origin" not in vary_tokens++ def test_vary_origin_not_duplicated(self):+ """When the response already carries a Vary header, Origin is appended+ once rather than duplicated."""+ from flask import make_response++ app = _make_app(+ SECURITY_CORS_ALLOWED_ORIGINS="https://a.com,https://b.com",+ )++ @app.route("/api/test")+ def api_test():+ resp = make_response("ok")+ resp.headers["Vary"] = "Accept-Encoding"+ return resp++ with app.test_client() as client:+ resp = client.get("/api/test", headers={"Origin": "https://b.com"})+ vary_tokens = [+ v.strip().lower()+ for v in resp.headers.get("Vary", "").split(",")+ if v.strip()+ ]+ assert vary_tokens.count("origin") == 1+ assert "accept-encoding" in vary_tokens+class TestGetCspPolicy:def test_default_connect_src(self):diff --git a/tests/web/services/test_socket_service_init.py b/tests/web/services/test_socket_service_init.pyindex fb3bf09802..ad0fa6ad85 100644--- a/tests/web/services/test_socket_service_init.py+++ b/tests/web/services/test_socket_service_init.py@@ -134,3 +134,116 @@ class TestSocketIOServiceCorsConfig:SocketIOService(app=minimal_app)call_kwargs = mock_socketio.call_args[1]assert call_kwargs["path"] == "/socket.io"+++class TestOriginRejectionLogging:+ """The diagnostic hook that surfaces engine.io's silenced 'bad-origin'+ WebSocket rejections through loguru (so a misconfigured origin isn't a+ silent frozen UI)."""++ def test_logs_each_rejected_origin_once_and_ignores_other_errors(self):+ from loguru import logger+ from flask import Flask+ from flask_socketio import SocketIO+ from local_deep_research.web.services.socket_service import (+ _install_origin_rejection_logging,+ )++ app = Flask(__name__)+ app.config["SECRET_KEY"] = "test"+ socketio = SocketIO(+ app, async_mode="threading", cors_allowed_origins=None+ )++ assert _install_origin_rejection_logging(socketio) is True+ eio = socketio.server.eio++ # The package disables loguru by default (__init__.py); app startup+ # re-enables it. Enable it here so the warning emitted from inside the+ # socket_service module reaches our sink.+ logger.enable("local_deep_research")+ warnings: list[str] = []+ sink_id = logger.add(+ lambda m: warnings.append(m.record["message"]), level="WARNING"+ )+ try:+ eio._log_error_once(+ "https://evil.com is not an accepted origin.", "bad-origin"+ )+ # same origin again -> deduped (no second warning)+ eio._log_error_once(+ "https://evil.com is not an accepted origin.", "bad-origin"+ )+ # a different origin -> its own warning+ eio._log_error_once(+ "https://other.com is not an accepted origin.", "bad-origin"+ )+ # an unrelated engine.io error -> must NOT be turned into a warning+ eio._log_error_once("Invalid transport", "bad-transport")+ finally:+ logger.remove(sink_id)+ logger.disable("local_deep_research") # restore import-time default++ origin_warnings = [+ w for w in warnings if "rejected a WebSocket handshake" in w+ ]+ assert len(origin_warnings) == 2+ assert any("evil.com" in w for w in origin_warnings)+ assert any("other.com" in w for w in origin_warnings)+ # the fix hint is present; the unrelated error never warned+ assert all(+ "LDR_SECURITY_WEBSOCKET_ALLOWED_ORIGINS" in w+ for w in origin_warnings+ )+ assert not any("Invalid transport" in w for w in warnings)++ def test_returns_false_when_engineio_internals_absent(self):+ from unittest.mock import Mock+ from local_deep_research.web.services.socket_service import (+ _install_origin_rejection_logging,+ )++ broken = Mock()+ # No .server.eio._log_error_once -> AttributeError path -> no-op.+ del broken.server+ assert _install_origin_rejection_logging(broken) is False++ def test_dedup_set_is_capped(self):+ """The per-origin dedup set is bounded: Origin is attacker-controlled at+ the pre-auth handshake, so feeding many distinct origins must not warn+ (or grow) without limit."""+ from loguru import logger+ from flask import Flask+ from flask_socketio import SocketIO+ from local_deep_research.web.services.socket_service import (+ _install_origin_rejection_logging,+ )++ app = Flask(__name__)+ app.config["SECRET_KEY"] = "test"+ socketio = SocketIO(+ app, async_mode="threading", cors_allowed_origins=None+ )+ assert _install_origin_rejection_logging(socketio) is True+ eio = socketio.server.eio++ logger.enable("local_deep_research")+ warnings: list[str] = []+ sink_id = logger.add(+ lambda m: warnings.append(m.record["message"]), level="WARNING"+ )+ try:+ for i in range(250):+ eio._log_error_once(+ f"https://h{i}.example is not an accepted origin.",+ "bad-origin",+ )+ finally:+ logger.remove(sink_id)+ logger.disable("local_deep_research")++ origin_warnings = [+ w for w in warnings if "rejected a WebSocket handshake" in w+ ]+ # Capped at 100 despite 250 distinct origins fed in.+ assert len(origin_warnings) == 100