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(security): pin WebSocket origin resolution and normalise degenerate allowlists (#6547)

LearningCircuit51f8ac944b3a
diff --git a/changelog.d/6547.security.md b/changelog.d/6547.security.md
new file mode 100644
index 0000000000..14e3bcf9b1
--- /dev/null
+++ b/changelog.d/6547.security.md
@@ -0,0 +1,2 @@
+WebSocket origin allowlist resolution is now pinned: degenerate `LDR_SECURITY_WEBSOCKET_ALLOWED_ORIGINS` values (empty entries or whitespace only) now resolve to the documented same-origin default instead of rejecting every browser handshake; a `*` inside a list is treated as the explicit allow-all opt-in. The never-disable semantics are pinned by contract.
+The resolved WebSocket origin policy is now logged at server startup (previously it was logged at import time, before logging was enabled, so the line never appeared) and at a default-visible level: a bare `*` logs at INFO and a `*` mixed with named origins logs a WARNING (the named origins have no effect).
diff --git a/src/local_deep_research/web/fastapi_app.py b/src/local_deep_research/web/fastapi_app.py
index f205cc0c3a..7c706bd157 100644
--- a/src/local_deep_research/web/fastapi_app.py
+++ b/src/local_deep_research/web/fastapi_app.py
@@ -279,12 +279,24 @@ async def lifespan(app: FastAPI):
# this, emits from research workers / log queue silently no-op
# (asyncio.get_event_loop() in a worker thread doesn't return uvicorn's loop).
import asyncio as _asyncio
- from .services.socketio_asgi import init_lock, set_main_loop
+ from .services.socketio_asgi import (
+ init_lock,
+ log_socketio_cors_policy,
+ set_main_loop,
+ )
set_main_loop(_asyncio.get_running_loop())
# Eagerly create the Socket.IO subscription lock now that the loop is
# running, so the first connect/subscribe events don't race on lazy init.
init_lock()
+ # Report the WebSocket origin policy here rather than at socketio_asgi
+ # import time: that import happens while package logging is still
+ # disabled (before config_logger() runs), which silently dropped the
+ # allow-all INFO/WARNING. Logging-only, so never let it block startup.
+ try:
+ log_socketio_cors_policy()
+ except Exception:
+ logger.exception("Failed to log the Socket.IO CORS policy")
# Size the AnyIO worker pool that serves every plain `def` route.
#
@@ -2376,7 +2388,10 @@ def _configure_cors(app: FastAPI) -> None:
is registered, so the app stays same-origin only — exactly main's
empty-default behavior. Same-origin requests carry no Origin header
and never receive CORS headers regardless, so this is effectively
- scoped to genuine cross-origin API calls.
+ scoped to genuine cross-origin API calls. A separator-only value
+ (e.g. ``","``) parses to no origins at all and is treated the same
+ way — no middleware registered — rather than as an allowlist that
+ can never match anything.
"""
from ..settings.env_registry import get_env_setting
@@ -2393,6 +2408,13 @@ def _configure_cors(app: FastAPI) -> None:
else:
origins = [o.strip() for o in configured.split(",") if o.strip()]
allow_credentials = False
+ if not origins:
+ # Every entry was empty (e.g. "," or " , "): the same intent
+ # as unset. Registering middleware here would produce an
+ # allowlist that can never match any Origin and a "CORS
+ # enabled for API origins: []" log that misleadingly claims
+ # CORS is on, so treat it exactly like the unset case above.
+ return
from starlette.middleware.cors import CORSMiddleware
diff --git a/src/local_deep_research/web/services/socketio_asgi.py b/src/local_deep_research/web/services/socketio_asgi.py
index 142c73c009..97514d8a19 100644
--- a/src/local_deep_research/web/services/socketio_asgi.py
+++ b/src/local_deep_research/web/services/socketio_asgi.py
@@ -29,35 +29,85 @@ from ..research_state import get_active_research_snapshot
# Determine WebSocket CORS policy from env var
from ...settings.env_registry import get_env_setting
+
+def _resolve_socketio_cors(env_value: str | None) -> str | list[str] | None:
+ """Resolve the WebSocket origin allowlist, never yielding ``[]``.
+
+ None (NOT []) is load-bearing: engine.io treats None as "derive the
+ same-origin whitelist from Host/X-Forwarded-Proto", whereas an empty
+ list DISABLES origin validation entirely (engineio checks
+ ``if self.cors_allowed_origins != []`` before validating), i.e. [] is
+ effectively allow-all for WebSocket handshakes. Every degenerate
+ input (unset, empty, nothing but separators) therefore resolves to
+ None; ``*`` requires the explicit env opt-in. A ``*`` entry anywhere
+ inside a comma-separated list is treated as that same opt-in: engine.io
+ has no "allow-all plus named origins" mode, so a list containing ``*``
+ already accepts every Origin -- returning it as a list would silently
+ behave as allow-all while the startup log claims a finite allowlist.
+ """
+ if env_value is None or not env_value.strip():
+ return None
+ if env_value.strip() == "*":
+ return "*"
+ origins = [o.strip() for o in env_value.split(",") if o.strip()]
+ if "*" in origins:
+ return "*"
+ return origins or None
+
+
_ws_origins_env = get_env_setting("security.websocket.allowed_origins")
-_socketio_cors: str | list[str] | None
-if _ws_origins_env is not None:
- if _ws_origins_env == "*":
- _socketio_cors = "*"
- elif _ws_origins_env:
- _socketio_cors = [o.strip() for o in _ws_origins_env.split(",")]
+# Plain assignment (not annotated): the startup-ordering freeze contract
+# detects module-scope ast.Assign targets.
+_socketio_cors = _resolve_socketio_cors(_ws_origins_env)
+
+
+def _log_socketio_cors_policy(
+ cors: str | list[str] | None, env_value: str | None
+) -> None:
+ """Log the resolved WebSocket origin policy at a default-visible level.
+
+ The allow-all posture must never be hidden below the default INFO sink.
+ A ``*`` mixed with specific origins is logged at WARNING because it
+ almost certainly is a misconfiguration (the named origins have no
+ effect). Only the operator's own configured entries (stripped) are
+ logged, never request-supplied values.
+ """
+ if cors is None:
+ logger.info(
+ "Socket.IO CORS: same-origin only (set LDR_SECURITY_WEBSOCKET_ALLOWED_ORIGINS to configure)"
+ )
+ elif cors == "*":
+ named = [
+ o
+ for o in (env_value or "").split(",")
+ if o.strip() and o.strip() != "*"
+ ]
+ if named:
+ logger.warning(
+ "Socket.IO CORS: all origins allowed -- "
+ "LDR_SECURITY_WEBSOCKET_ALLOWED_ORIGINS contains '*' alongside "
+ f"specific origins {[o.strip() for o in named]}; engine.io has "
+ "no allow-all-plus-named mode, so the named origins have no "
+ "effect. Remove '*' to restrict to them."
+ )
+ else:
+ logger.info("Socket.IO CORS: all origins allowed ('*')")
else:
- _socketio_cors = None
-else:
- # No env var set — fail closed to same-origin only, matching HTTP CORS
- # default. Operators who need cross-origin WS access must set
- # LDR_SECURITY_WEBSOCKET_ALLOWED_ORIGINS explicitly.
- #
- # None (NOT []) is load-bearing: engine.io treats None as "derive the
- # same-origin whitelist from Host/X-Forwarded-Proto", whereas an empty
- # list DISABLES origin validation entirely (engineio checks
- # `if self.cors_allowed_origins != []` before validating), i.e. [] is
- # effectively allow-all for WebSocket handshakes.
- _socketio_cors = None
-
-if _socketio_cors is None:
- logger.info(
- "Socket.IO CORS: same-origin only (set LDR_SECURITY_WEBSOCKET_ALLOWED_ORIGINS to configure)"
- )
-elif _socketio_cors == "*":
- logger.debug("Socket.IO CORS: all origins allowed")
-else:
- logger.info(f"Socket.IO CORS: restricted to {_socketio_cors}")
+ logger.info(f"Socket.IO CORS: restricted to {cors}")
+
+
+def log_socketio_cors_policy() -> None:
+ """Log the import-time-resolved WebSocket origin policy.
+
+ Deliberately NOT called at module import: this module is imported at
+ the top of ``utilities/log_utils.py``, i.e. while the package's
+ ``logger.disable("local_deep_research")`` (``__init__.py``) is still in
+ effect and before ``config_logger()`` re-enables it, so an import-time
+ log line -- including the allow-all INFO/WARNING -- would be silently
+ dropped. The FastAPI lifespan startup calls this instead, once the
+ server is starting and logging is configured.
+ """
+ _log_socketio_cors_policy(_socketio_cors, _ws_origins_env)
def _install_origin_rejection_logging(sio: "socketio.AsyncServer") -> bool:
diff --git a/tests/security/test_socket_ownership_edges_fastapi.py b/tests/security/test_socket_ownership_edges_fastapi.py
index 9433a39c60..33d7653a47 100644
--- a/tests/security/test_socket_ownership_edges_fastapi.py
+++ b/tests/security/test_socket_ownership_edges_fastapi.py
@@ -673,6 +673,11 @@ class TestWebSocketOriginPolicyDerivation:
["https://a.example.com", "https://b.example.com"],
id="csv-is-stripped",
),
+ pytest.param(
+ "https://a.example.com,*",
+ "*",
+ id="star-within-a-list-is-allow-all",
+ ),
],
)
def test_policy_derivation(self, monkeypatch, env_value, expected):
@@ -688,6 +693,53 @@ class TestWebSocketOriginPolicyDerivation:
"the derived policy did not reach the engine.io server"
)
+ def test_a_star_within_a_list_logs_allow_all_not_a_restricted_list(
+ self, monkeypatch
+ ):
+ """``_resolve_socketio_cors`` collapses a `*`-containing list to
+ the bare allow-all value, and the startup policy log must follow: it
+ must not claim the policy is "restricted to [...]" when it is
+ actually allow-all.
+
+ The log is emitted by ``log_socketio_cors_policy()`` (called from
+ the FastAPI lifespan), not at import: the import happens while the
+ package logger is still disabled, so an import-time line is lost.
+ """
+ monkeypatch.setenv(WS_ORIGINS_ENV, "https://a.example.com,*")
+
+ import_records: list[str] = []
+ records: list[str] = []
+ logger.enable("local_deep_research")
+ sink_id = logger.add(
+ lambda message: import_records.append(message.record["message"]),
+ level="DEBUG",
+ )
+ try:
+ module = _load_socketio_asgi_fresh()
+ finally:
+ logger.remove(sink_id)
+ sink_id = logger.add(
+ lambda message: records.append(message.record["message"]),
+ level="DEBUG",
+ )
+ try:
+ module.log_socketio_cors_policy()
+ finally:
+ logger.remove(sink_id)
+ logger.disable("local_deep_research")
+
+ assert module._socketio_cors == "*"
+ assert not any("Socket.IO CORS" in r for r in import_records), (
+ "the origin policy must not be logged at import time (package "
+ f"logging is still disabled then): {import_records!r}"
+ )
+ assert not any("restricted to" in r for r in records), (
+ f"log claimed a restricted allowlist for an allow-all policy: {records!r}"
+ )
+ assert any("all origins allowed" in r for r in records), (
+ f"log did not report the allow-all policy: {records!r}"
+ )
+
@pytest.mark.parametrize(
"env_value", [None, "", "*", "https://a.test", "https://a.test,", ","]
)
diff --git a/tests/security/test_websocket_origin_fail_closed.py b/tests/security/test_websocket_origin_fail_closed.py
new file mode 100644
index 0000000000..87e26757d1
--- /dev/null
+++ b/tests/security/test_websocket_origin_fail_closed.py
@@ -0,0 +1,217 @@
+"""Contracts for the WebSocket origin allowlist resolution (never ``[]``).
+
+engine.io's origin check is ``if self.cors_allowed_origins != []``: an
+empty **list** disables origin validation entirely, while ``None``
+derives the same-origin allowlist from Host/X-Forwarded-Proto. The
+module-level resolution documents this as load-bearing — but nothing
+pinned the semantics:
+
+- unset env must resolve to ``None`` (never ``[]``),
+- an empty string must resolve the same way,
+- ``*`` must require the explicit env opt-in, including when it appears as
+ one entry inside a comma-separated list rather than alone,
+- whitespace-only input must resolve to exactly ``None``, not merely to
+ something that happens not to be ``[]``.
+
+The comma-edge (``","``) previously resolved to ``["", ""]`` — a list
+of empty-string origins that is neither the documented ``[]`` footgun
+nor a sane allowlist (engine.io rejects every handshake carrying an
+Origin header against it); it now resolves to ``None``, i.e. the
+documented same-origin default. This is a deliberate loosening to that
+default, not a fail-closed outcome.
+
+The import-time value never being the validation-disabling ``[]`` is
+pinned in ``tests/security/test_socket_ownership_edges_fastapi.py``
+(``TestLiveServerOriginPolicy``), not re-litigated here.
+
+The startup-ordering suite pins the resolution's module-scope freeze;
+these pin what it actually resolves.
+"""
+
+from __future__ import annotations
+
+import local_deep_research.web.services.socketio_asgi as prod_module
+
+
+class TestOriginResolutionFailsClosed:
+ def test_unset_env_resolves_to_none(self):
+ assert prod_module._resolve_socketio_cors(None) is None, (
+ "unset env must resolve to same-origin (None), never [] "
+ "(engine.io skips origin validation for [])"
+ )
+
+ def test_empty_string_resolves_to_none(self):
+ assert prod_module._resolve_socketio_cors("") is None
+
+ def test_comma_edge_resolves_to_none(self):
+ """',' splits into empty-string origins — resolve to the same-origin
+ default (None), not a junk allowlist."""
+ assert prod_module._resolve_socketio_cors(",") is None
+ assert prod_module._resolve_socketio_cors(" , ") is None
+
+ def test_star_requires_explicit_env(self):
+ assert prod_module._resolve_socketio_cors("*") == "*"
+
+ def test_star_within_a_list_is_the_explicit_allow_all_opt_in(self):
+ """engine.io has no "allow-all plus named origins" mode: a list
+ containing ``*`` already accepts every Origin, so it must resolve
+ the same as a bare ``*`` rather than as a list that behaves as
+ allow-all while the startup log claims a finite allowlist."""
+ assert prod_module._resolve_socketio_cors("https://a,*") == "*"
+ assert prod_module._resolve_socketio_cors("*, https://a") == "*"
+
+ def test_origin_list_is_split_stripped_and_empties_dropped(self):
+ assert prod_module._resolve_socketio_cors(
+ "https://a.example, https://b.example"
+ ) == ["https://a.example", "https://b.example"]
+ assert prod_module._resolve_socketio_cors(
+ " , https://x.example , "
+ ) == ["https://x.example"]
+
+ def test_resolution_never_returns_an_empty_list(self):
+ for hostile in (None, "", " ", ",", " , , "):
+ result = prod_module._resolve_socketio_cors(hostile)
+ assert result is None or (
+ isinstance(result, (str, list)) and result != []
+ ), f"{hostile!r} resolved to the validation-disabling {result!r}"
+
+ def test_whitespace_only_input_resolves_to_none_not_merely_non_empty(self):
+ """Stronger than ``!= []``: a mutant that returned ``"*"`` (or any
+ other truthy non-list value) for whitespace-only input would still
+ satisfy ``result != []`` above, so this pins the exact value --
+ whitespace-only input carries no origins and must resolve to
+ the same-origin default, never a permissive fallback."""
+ for whitespace_only in (" ", "\t", "\xa0", " , , "):
+ result = prod_module._resolve_socketio_cors(whitespace_only)
+ assert result is None, (
+ f"{whitespace_only!r} resolved to {result!r}, not the "
+ "same-origin default (None)"
+ )
+
+
+class TestAllowAllPolicyIsLoggedVisibly:
+ """The allow-all posture must be visible at the default INFO sink."""
+
+ @staticmethod
+ def _capture(cors, env_value):
+ from loguru import logger
+
+ records = []
+ # local_deep_research/__init__.py disables the package namespace;
+ # re-enable it so this capture works when run on its own, not only
+ # after some other test happened to enable it.
+ logger.enable("local_deep_research")
+ sink_id = logger.add(
+ lambda m: records.append(
+ (m.record["level"].name, m.record["message"])
+ ),
+ level="INFO",
+ )
+ try:
+ prod_module._log_socketio_cors_policy(cors, env_value)
+ finally:
+ logger.remove(sink_id)
+ logger.disable("local_deep_research")
+ return records
+
+ def test_mixed_star_and_origin_logs_warning(self):
+ env = "https://a.example,*"
+ records = self._capture(prod_module._resolve_socketio_cors(env), env)
+ assert len(records) == 1
+ level, message = records[0]
+ assert level == "WARNING"
+ assert "all origins allowed" in message
+ assert "https://a.example" in message
+
+ def test_bare_star_logs_info_not_hidden(self):
+ records = self._capture("*", "*")
+ assert [lvl for lvl, _ in records] == ["INFO"]
+ assert "all origins allowed" in records[0][1]
+
+
+class TestPolicyLogRunsAfterLoggingIsConfigured:
+ """The policy log must be emitted from the lifespan startup, not at
+ import.
+
+ ``socketio_asgi`` is imported at the top of ``utilities/log_utils.py``,
+ i.e. while ``logger.disable("local_deep_research")`` from the package
+ ``__init__`` is still in effect and before ``config_logger()``
+ re-enables it, so a module-scope log call is silently dropped in
+ production. Source-level pins: loading the FastAPI app here would pull
+ the whole application.
+ """
+
+ @staticmethod
+ def _module_ast(module):
+ import ast
+ import inspect
+
+ return ast.parse(inspect.getsource(module))
+
+ @staticmethod
+ def _called_names(node):
+ import ast
+
+ names = set()
+ for sub in ast.walk(node):
+ if isinstance(sub, ast.Call):
+ func = sub.func
+ if isinstance(func, ast.Name):
+ names.add(func.id)
+ elif isinstance(func, ast.Attribute):
+ names.add(func.attr)
+ return names
+
+ def test_policy_is_not_logged_at_module_scope(self):
+ import ast
+
+ tree = self._module_ast(prod_module)
+ module_scope_calls = set()
+ for stmt in tree.body:
+ if isinstance(
+ stmt, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)
+ ):
+ continue
+ module_scope_calls |= self._called_names(stmt)
+ assert not module_scope_calls & {
+ "_log_socketio_cors_policy",
+ "log_socketio_cors_policy",
+ }, (
+ "the WebSocket origin policy is logged at import time, while "
+ "package logging is still disabled -- the line is lost"
+ )
+
+ def test_lifespan_startup_logs_the_policy(self):
+ import ast
+ from pathlib import Path
+
+ fastapi_app_path = (
+ Path(prod_module.__file__).resolve().parents[1] / "fastapi_app.py"
+ )
+ tree = ast.parse(fastapi_app_path.read_text(encoding="utf-8"))
+ lifespans = [
+ node
+ for node in tree.body
+ if isinstance(node, ast.AsyncFunctionDef)
+ and node.name == "lifespan"
+ ]
+ assert len(lifespans) == 1, "premise: fastapi_app defines lifespan()"
+ assert "log_socketio_cors_policy" in self._called_names(lifespans[0]), (
+ "the lifespan startup no longer logs the WebSocket origin policy"
+ )
+
+ def test_public_entry_point_logs_the_resolved_policy(self):
+ from loguru import logger
+
+ records = []
+ logger.enable("local_deep_research")
+ sink_id = logger.add(
+ lambda m: records.append(m.record["message"]), level="INFO"
+ )
+ try:
+ prod_module.log_socketio_cors_policy()
+ finally:
+ logger.remove(sink_id)
+ logger.disable("local_deep_research")
+ assert len(records) == 1
+ assert records[0].startswith("Socket.IO CORS:")
diff --git a/tests/web/test_cors_config.py b/tests/web/test_cors_config.py
index 4de054cc3f..b53a6866fd 100644
--- a/tests/web/test_cors_config.py
+++ b/tests/web/test_cors_config.py
@@ -61,6 +61,12 @@ class TestFailClosed:
def test_empty_registers_no_cors(self):
assert _has_cors(_app_with_cors("")) is False
+ def test_separator_only_registers_no_cors(self):
+ """A separator-only value parses to zero origins -- the same intent
+ as unset, not an allowlist that can never match any Origin."""
+ assert _has_cors(_app_with_cors(",")) is False
+ assert _has_cors(_app_with_cors(" , , ")) is False
+
def test_no_cors_headers_when_unconfigured(self):
app = _app_with_cors(None)
client = TestClient(app)
diff --git a/tests/web/test_startup_ordering_contracts.py b/tests/web/test_startup_ordering_contracts.py
index fc82bd3660..b67e6fba5f 100644
--- a/tests/web/test_startup_ordering_contracts.py
+++ b/tests/web/test_startup_ordering_contracts.py
@@ -17,9 +17,10 @@ pytest only sets while a test body runs -- is always absent there). The
inventory below pins the other twelve, across five modules, so that adding a
fourteenth is a visible diff rather than a silent restart-only setting.
-**Which startup failures still serve traffic.** Eleven of the lifespan's
+**Which startup failures still serve traffic.** Twelve of the lifespan's
steps sit inside a ``try/except Exception`` that logs and continues (ten
-before #5982 moved the log-queue daemon across the line). That is a
+before #5982 moved the log-queue daemon across the line; eleven before
+#6547 added the guarded WebSocket origin-policy log line). That is a
deliberate policy -- a stale stylesheet is not worth refusing to boot over --
but it means the guarded list *is* the list of ways this app can come up
half-initialised and answer requests anyway. It is pinned here as a census,
@@ -577,6 +578,15 @@ def test_importing_the_web_app_has_the_filesystem_side_effects_it_has():
#: app can finish `lifespan` startup, report `lifespan.startup.complete`,
#: and begin answering requests with that subsystem dead.
_GUARDED_STARTUP_STEPS = {
+ # ADDED BY #6547, deliberately. Logging-only: the WebSocket origin
+ # policy is resolved and applied at `socketio_asgi` import time, so this
+ # step only reports the precomputed value (moved here from import time,
+ # where package logging was still disabled and the allow-all
+ # INFO/WARNING was silently dropped). Degraded mode is "the startup log
+ # lacks the origin-policy line", while the enforced policy is unchanged.
+ # Not worth refusing to boot over, and the handler uses
+ # logger.exception, so the failure still carries a traceback.
+ "log_socketio_cors_policy": "WebSocket origin-policy startup log line",
"warn_if_threadpool_exceeds_db_pool": "AnyIO worker pool sizing",
"theme_registry.get_combined_css": "themes.css regeneration",
"warn_if_weak_kdf_with_existing_databases": "weak-SQLCipher-KDF check",