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): add CORS env var support and remove hardcoded wildcard headers (#2243)

LearningCircuitc93bb248ad3a
diff --git a/docs/env_configuration.md b/docs/env_configuration.md
index 260387d832..1ac5128b66 100644
--- a/docs/env_configuration.md
+++ b/docs/env_configuration.md
@@ -231,3 +231,44 @@ Database encryption settings are configured exclusively via environment variable
| `LDR_ALLOW_UNENCRYPTED` | `LDR_BOOTSTRAP_ALLOW_UNENCRYPTED` |
A deprecation warning is logged when a deprecated name is used. If both canonical and deprecated names are set, the canonical name takes precedence.
+
+### CORS / WebSocket Security
+
+These settings control Cross-Origin Resource Sharing (CORS) for API routes and WebSocket connections. By default, API CORS is restricted to same-origin, and WebSocket allows all origins for broad compatibility.
+
+| Setting | Env Var | Default | Description |
+|---------|---------|---------|-------------|
+| API CORS origins | `LDR_SECURITY_CORS_ALLOWED_ORIGINS` | `""` (same-origin) | Allowed origins for API routes |
+| WebSocket origins | `LDR_SECURITY_WEBSOCKET_ALLOWED_ORIGINS` | `"*"` (all origins) | Allowed origins for Socket.IO connections |
+
+**Values:**
+- `*` — Allow all origins (most permissive)
+- Empty string or unset — Same-origin only (most restrictive)
+- Comma-separated list — Allow specific origins only
+
+**Examples:**
+
+```bash
+# Allow all origins for both API and WebSocket
+export LDR_SECURITY_CORS_ALLOWED_ORIGINS="*"
+export LDR_SECURITY_WEBSOCKET_ALLOWED_ORIGINS="*"
+
+# Restrict to specific origins
+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=""
+```
+
+**Docker Compose example:**
+
+```yaml
+services:
+ local-deep-research:
+ environment:
+ - LDR_SECURITY_CORS_ALLOWED_ORIGINS=*
+ - LDR_SECURITY_WEBSOCKET_ALLOWED_ORIGINS=*
+```
+
+**Note:** If WebSocket connections fail after upgrading, set `LDR_SECURITY_WEBSOCKET_ALLOWED_ORIGINS=*` to restore the previous permissive behavior.
diff --git a/src/local_deep_research/security/security_headers.py b/src/local_deep_research/security/security_headers.py
index 9957234cd5..49b0cfa07f 100644
--- a/src/local_deep_research/security/security_headers.py
+++ b/src/local_deep_research/security/security_headers.py
@@ -65,9 +65,18 @@ class SecurityHeaders:
)
app.config.setdefault("SECURITY_CORS_ENABLED", True)
app.config.setdefault("SECURITY_CORS_ALLOW_CREDENTIALS", False)
+
+ # CORS allowed origins: check env var first, then fall back to default
+ # Env var: LDR_SECURITY_CORS_ALLOWED_ORIGINS
# Default to empty (fail closed) - require explicit configuration for CORS
- # Using "*" creates a security footgun - users must explicitly allow origins
- app.config.setdefault("SECURITY_CORS_ALLOWED_ORIGINS", "")
+ from ..settings.env_registry import get_env_setting
+
+ cors_env = get_env_setting("security.cors.allowed_origins")
+ if cors_env is not None:
+ app.config["SECURITY_CORS_ALLOWED_ORIGINS"] = cors_env
+ else:
+ app.config.setdefault("SECURITY_CORS_ALLOWED_ORIGINS", "")
+
app.config.setdefault("SECURITY_COEP_POLICY", "credentialless")
self.app = app
@@ -212,7 +221,11 @@ class SecurityHeaders:
Returns:
True if path is an API route
"""
- return path.startswith("/api/") or path.startswith("/research/api/")
+ return (
+ path.startswith("/api/")
+ or path.startswith("/research/api/")
+ or path.startswith("/history/api")
+ )
def _validate_cors_config(self) -> None:
"""Validate CORS configuration at startup to catch misconfigurations early.
diff --git a/src/local_deep_research/settings/env_definitions/security.py b/src/local_deep_research/settings/env_definitions/security.py
index 5a27d0dc0f..c8c3d66c95 100644
--- a/src/local_deep_research/settings/env_definitions/security.py
+++ b/src/local_deep_research/settings/env_definitions/security.py
@@ -1,11 +1,12 @@
"""
Security environment settings.
-These settings control security-related behavior like SSRF validation.
+These settings control security-related behavior like SSRF validation
+and CORS origin restrictions.
"""
import os
-from ..env_settings import BooleanSetting
+from ..env_settings import BooleanSetting, StringSetting
# External environment variables (set by pytest, CI systems)
@@ -20,4 +21,22 @@ SECURITY_SETTINGS = [
description="Disable SSRF validation (test/dev only - NEVER in production)",
default=False,
),
+ StringSetting(
+ key="security.cors.allowed_origins",
+ description=(
+ "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'"
+ ),
+ default=None,
+ ),
+ StringSetting(
+ 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. "
+ "Example: 'https://example.com,https://app.example.com'"
+ ),
+ default=None,
+ ),
]
diff --git a/src/local_deep_research/web/routes/history_routes.py b/src/local_deep_research/web/routes/history_routes.py
index af8f9542c4..0a4a3109ae 100644
--- a/src/local_deep_research/web/routes/history_routes.py
+++ b/src/local_deep_research/web/routes/history_routes.py
@@ -1,6 +1,6 @@
import json
-from flask import Blueprint, jsonify, make_response, session
+from flask import Blueprint, jsonify, session
from loguru import logger
from ...constants import ResearchStatus
@@ -131,36 +131,17 @@ def get_history():
"items": history, # Use 'items' key as expected by client
}
- # Add CORS headers
- response = make_response(jsonify(response_data))
- response.headers.add("Access-Control-Allow-Origin", "*")
- response.headers.add(
- "Access-Control-Allow-Headers", "Content-Type,Authorization"
- )
- response.headers.add(
- "Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS"
- )
- return response
+ # CORS headers are handled by SecurityHeaders middleware
+ return jsonify(response_data)
except Exception:
logger.exception("Error getting history")
- # Return empty array with CORS headers
- response = make_response(
- jsonify(
- {
- "status": "error",
- "items": [],
- "message": "Failed to retrieve history",
- }
- )
- )
- response.headers.add("Access-Control-Allow-Origin", "*")
- response.headers.add(
- "Access-Control-Allow-Headers", "Content-Type,Authorization"
- )
- response.headers.add(
- "Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS"
+ return jsonify(
+ {
+ "status": "error",
+ "items": [],
+ "message": "Failed to retrieve history",
+ }
)
- return response
@history_bp.route("/status/<string:research_id>")
diff --git a/src/local_deep_research/web/services/socket_service.py b/src/local_deep_research/web/services/socket_service.py
index 33469647a2..ad8ff4fa04 100644
--- a/src/local_deep_research/web/services/socket_service.py
+++ b/src/local_deep_research/web/services/socket_service.py
@@ -45,9 +45,34 @@ class SocketIOService:
"""
self.__app = app # Store the Flask app reference
+
+ # Determine WebSocket CORS policy from env var or default
+ from ...settings.env_registry import get_env_setting
+
+ ws_origins_env = get_env_setting("security.websocket.allowed_origins")
+ 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(",")]
+ else:
+ socketio_cors = None
+ else:
+ # No env var set — preserve existing permissive default
+ socketio_cors = "*"
+
+ 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}")
+
self.__socketio = SocketIO(
app,
- cors_allowed_origins="*",
+ cors_allowed_origins=socketio_cors,
async_mode="threading",
path="/socket.io",
logger=False,