~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
security: gate global scheduler control behind setting (#2035)
LearningCircuita466877273ac
diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.mdindex c867977dfc..13a5e1218d 100644--- a/docs/CONFIGURATION.md+++ b/docs/CONFIGURATION.md@@ -47,6 +47,7 @@ They are not available in the Web UI because they are needed to start the applic| `LDR_DB_CONFIG_KDF_ITERATIONS` | Integer | `256000` | No | 1000..1000000 | Number of KDF iterations for key derivation | Db Config | LDR_DB_KDF_ITERATIONS || `LDR_DB_CONFIG_PAGE_SIZE` | Integer | `16384` | No | 512..65536 | SQLite page size (must be power of 2) | Db Config | LDR_DB_PAGE_SIZE || `LDR_DB_CONFIG_SYNCHRONOUS` | Enum | `'NORMAL'` | No | EXTRA, FULL, NORMAL, OFF | SQLite synchronous mode | Db Config | LDR_DB_SYNCHRONOUS |+| `LDR_NEWS_SCHEDULER_ALLOW_API_CONTROL` | Boolean | `False` | No | | Allow authenticated users to start/stop the global news scheduler via API. Disable in multi-user deployments to prevent users from affecting each other. | News Scheduler | || `LDR_NEWS_SCHEDULER_ENABLED` | Boolean | `True` | No | | Enable or disable the news subscription scheduler | News Scheduler | || `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 | |@@ -131,6 +132,7 @@ They are not available in the Web UI because they are needed to start the applic| `news.progress.generating_searches` | `LDR_NEWS_PROGRESS_GENERATING_SEARCHES` | `50` | Progress percentage when generating searches | APP || `news.refresh.default_hours` | `LDR_NEWS_REFRESH_DEFAULT_HOURS` | `4` | Default refresh interval in hours | APP || `news.scheduler.activity_check_interval` | `LDR_NEWS_SCHEDULER_ACTIVITY_CHECK_INTERVAL` | `5` | How often to check for due subscriptions (minutes) | APP |+| `news.scheduler.allow_api_control` | `LDR_NEWS_SCHEDULER_ALLOW_API_CONTROL` | `false` | Allow authenticated users to start, stop, and trigger the global news scheduler via API. This setting cannot be changed from the UI for security reasons. Disable in multi-user deployments by setting the environment variable LDR_NEWS_SCHEDULER_ALLOW_API_CONTROL=false. | APP || `news.scheduler.batch_size` | `LDR_NEWS_SCHEDULER_BATCH_SIZE` | `5` | Number of subscriptions to process in each batch | APP || `news.scheduler.cleanup_interval_hours` | `LDR_NEWS_SCHEDULER_CLEANUP_INTERVAL_HOURS` | `1` | How often to run cleanup job for inactive users | APP || `news.scheduler.enabled` | `LDR_NEWS_SCHEDULER_ENABLED` | `true` | Enable automatic news subscription updates for active users | APP |diff --git a/src/local_deep_research/defaults/default_settings.json b/src/local_deep_research/defaults/default_settings.jsonindex 255126be1f..c850cc86a5 100644--- a/src/local_deep_research/defaults/default_settings.json+++ b/src/local_deep_research/defaults/default_settings.json@@ -4720,6 +4720,20 @@"value": true,"visible": true},+ "news.scheduler.allow_api_control": {+ "category": "news_scheduler",+ "description": "Allow authenticated users to start, stop, and trigger the global news scheduler via API. This setting cannot be changed from the UI for security reasons. Disable in multi-user deployments by setting the environment variable LDR_NEWS_SCHEDULER_ALLOW_API_CONTROL=false.",+ "editable": false,+ "max_value": null,+ "min_value": null,+ "name": "Allow Scheduler API Control",+ "options": null,+ "step": null,+ "type": "APP",+ "ui_element": "checkbox",+ "value": false,+ "visible": true+ },"news.scheduler.retention_hours": {"category": "news_scheduler","description": "Hours to keep user credentials in memory after last activity",diff --git a/src/local_deep_research/news/flask_api.py b/src/local_deep_research/news/flask_api.pyindex d77b309388..33aa16cd0b 100644--- a/src/local_deep_research/news/flask_api.py+++ b/src/local_deep_research/news/flask_api.py@@ -3,6 +3,7 @@ Flask API endpoints for news system.Converted from FastAPI to match LDR's Flask architecture."""+from functools import wrapsfrom typing import Dict, Anyfrom flask import Blueprint, request, jsonifyfrom loguru import logger@@ -12,11 +13,44 @@ from .folder_manager import FolderManagerfrom ..database.models import SubscriptionFolderfrom ..web.auth.decorators import login_requiredfrom ..database.session_context import get_user_db_session+from ..settings.env_registry import get_env_settingfrom ..utilities.db_utils import get_settings_managerfrom ..security import safe_postfrom ..security.decorators import require_json_body+def scheduler_control_required(f):+ """Decorator that gates global scheduler control behind a setting.++ The news scheduler is a global singleton — starting, stopping, or+ triggering it affects all users. This decorator checks the+ ``news.scheduler.allow_api_control`` setting (env var+ ``LDR_NEWS_SCHEDULER_ALLOW_API_CONTROL``, default ``false``) and+ returns 403 when the setting is disabled.++ Must be placed *after* ``@login_required`` in the decorator stack.+ """++ @wraps(f)+ def wrapper(*args, **kwargs):+ if not get_env_setting("news.scheduler.allow_api_control", False):+ logger.warning(+ "Scheduler API control blocked for endpoint %s", f.__name__+ )+ return (+ jsonify(+ {+ "error": "Scheduler API control is disabled. "+ "Set LDR_NEWS_SCHEDULER_ALLOW_API_CONTROL=true to enable."+ }+ ),+ 403,+ )+ return f(*args, **kwargs)++ return wrapper++def safe_error_message(e: Exception, context: str = "") -> str:"""Return a safe error message that doesn't expose internal details.@@ -733,6 +767,7 @@ def get_scheduler_status() -> Dict[str, Any]:@news_api_bp.route("/scheduler/start", methods=["POST"])@login_required+@scheduler_control_requireddef start_scheduler() -> Dict[str, Any]:"""Start the subscription scheduler."""try:@@ -768,6 +803,7 @@ def start_scheduler() -> Dict[str, Any]:@news_api_bp.route("/scheduler/stop", methods=["POST"])@login_required+@scheduler_control_requireddef stop_scheduler() -> Dict[str, Any]:"""Stop the subscription scheduler."""try:@@ -797,6 +833,7 @@ def stop_scheduler() -> Dict[str, Any]:@news_api_bp.route("/scheduler/check-now", methods=["POST"])@login_required+@scheduler_control_requireddef check_subscriptions_now() -> Dict[str, Any]:"""Manually trigger subscription checking."""try:@@ -856,6 +893,7 @@ def check_subscriptions_now() -> Dict[str, Any]:@news_api_bp.route("/scheduler/cleanup-now", methods=["POST"])@login_required+@scheduler_control_requireddef trigger_cleanup() -> Dict[str, Any]:"""Manually trigger cleanup job."""try:diff --git a/src/local_deep_research/settings/env_definitions/news_scheduler.py b/src/local_deep_research/settings/env_definitions/news_scheduler.pyindex 62a8f79f71..54be032a91 100644--- a/src/local_deep_research/settings/env_definitions/news_scheduler.py+++ b/src/local_deep_research/settings/env_definitions/news_scheduler.py@@ -15,4 +15,10 @@ NEWS_SCHEDULER_SETTINGS = [description="Enable or disable the news subscription scheduler",default=True,),+ BooleanSetting(+ key="news.scheduler.allow_api_control",+ description="Allow authenticated users to start/stop the global news scheduler via API. "+ "Disable in multi-user deployments to prevent users from affecting each other.",+ default=False,+ ),]diff --git a/tests/news/test_flask_api.py b/tests/news/test_flask_api.pyindex dd2eebefd9..45c6895fea 100644--- a/tests/news/test_flask_api.py+++ b/tests/news/test_flask_api.py@@ -12,7 +12,7 @@ Tests cover:import pytestfrom unittest.mock import patch-from flask import Flask+from flask import Flask, jsonify@pytest.fixture@@ -332,6 +332,223 @@ class TestRefreshEndpoint:assert response.status_code in [302, 401, 403, 404]+class TestSchedulerControlRequired:+ """Tests for scheduler_control_required decorator (PR #2035).++ The decorator gates global scheduler control endpoints behind+ the news.scheduler.allow_api_control setting, returning 403+ when disabled.+ """++ def test_decorator_allows_when_setting_enabled(self, app):+ """Decorated function executes when setting is True."""+ from local_deep_research.news.flask_api import (+ scheduler_control_required,+ )++ with app.app_context():+ with patch(+ "local_deep_research.news.flask_api.get_env_setting",+ return_value=True,+ ):++ @scheduler_control_required+ def dummy_view():+ return jsonify({"status": "ok"}), 200++ response, status_code = dummy_view()+ assert status_code == 200++ def test_decorator_blocks_when_setting_disabled(self, app):+ """Decorated function returns 403 when setting is False."""+ from local_deep_research.news.flask_api import (+ scheduler_control_required,+ )++ with app.app_context():+ with patch(+ "local_deep_research.news.flask_api.get_env_setting",+ return_value=False,+ ):++ @scheduler_control_required+ def dummy_view():+ return jsonify({"status": "ok"}), 200++ response, status_code = dummy_view()+ assert status_code == 403++ def test_decorator_returns_error_message_when_disabled(self, app):+ """403 response includes informative error message."""+ from local_deep_research.news.flask_api import (+ scheduler_control_required,+ )++ with app.app_context():+ with patch(+ "local_deep_research.news.flask_api.get_env_setting",+ return_value=False,+ ):++ @scheduler_control_required+ def dummy_view():+ return jsonify({"status": "ok"}), 200++ response, status_code = dummy_view()+ data = response.get_json()+ assert "error" in data+ assert "disabled" in data["error"].lower()++ def test_decorator_checks_correct_setting_key(self, app):+ """Decorator checks news.scheduler.allow_api_control setting."""+ from local_deep_research.news.flask_api import (+ scheduler_control_required,+ )++ with app.app_context():+ with patch(+ "local_deep_research.news.flask_api.get_env_setting",+ return_value=True,+ ) as mock_setting:++ @scheduler_control_required+ def dummy_view():+ return jsonify({"status": "ok"}), 200++ dummy_view()+ mock_setting.assert_called_once_with(+ "news.scheduler.allow_api_control", False+ )++ def test_decorator_preserves_function_name(self):+ """Decorator preserves the wrapped function's name."""+ from local_deep_research.news.flask_api import (+ scheduler_control_required,+ )++ @scheduler_control_required+ def my_endpoint():+ pass++ assert my_endpoint.__name__ == "my_endpoint"++ def test_decorator_passes_args_to_wrapped_function(self, app):+ """Decorator forwards positional and keyword arguments."""+ from local_deep_research.news.flask_api import (+ scheduler_control_required,+ )++ with app.app_context():+ with patch(+ "local_deep_research.news.flask_api.get_env_setting",+ return_value=True,+ ):++ @scheduler_control_required+ def dummy_view(a, b, key=None):+ return jsonify({"a": a, "b": b, "key": key}), 200++ response, status_code = dummy_view(1, 2, key="val")+ assert status_code == 200+ data = response.get_json()+ assert data["a"] == 1+ assert data["b"] == 2+ assert data["key"] == "val"++ def test_decorator_does_not_call_wrapped_when_disabled(self, app):+ """Wrapped function is never invoked when setting is disabled."""+ from local_deep_research.news.flask_api import (+ scheduler_control_required,+ )++ call_tracker = {"called": False}++ with app.app_context():+ with patch(+ "local_deep_research.news.flask_api.get_env_setting",+ return_value=False,+ ):++ @scheduler_control_required+ def dummy_view():+ call_tracker["called"] = True+ return jsonify({"status": "ok"}), 200++ dummy_view()+ assert call_tracker["called"] is False+++class TestSchedulerEndpointGating:+ """Integration tests verifying scheduler endpoints are properly gated.++ Tests that mutating scheduler endpoints (start, stop, check-now,+ cleanup-now) return 403 when the allow_api_control setting is+ disabled, while read-only endpoints (status, users, stats) remain+ accessible.+ """++ GATED_ENDPOINTS = [+ "/news/api/scheduler/start",+ "/news/api/scheduler/stop",+ "/news/api/scheduler/check-now",+ "/news/api/scheduler/cleanup-now",+ ]++ NON_GATED_ENDPOINTS = [+ "/news/api/scheduler/status",+ "/news/api/scheduler/users",+ "/news/api/scheduler/stats",+ ]++ def _auth_session(self, client):+ """Inject a valid session so login_required passes."""+ with client.session_transaction() as sess:+ sess["username"] = "testuser"++ def test_gated_endpoints_return_403_when_disabled(self, client, app):+ """Mutating scheduler endpoints return 403 when control disabled."""+ self._auth_session(client)+ with (+ patch(+ "local_deep_research.news.flask_api.get_env_setting",+ return_value=False,+ ),+ patch(+ "local_deep_research.web.auth.decorators.db_manager",+ ) as mock_db,+ ):+ mock_db.connections = {"testuser": True}++ for endpoint in self.GATED_ENDPOINTS:+ response = client.post(endpoint)+ assert response.status_code == 403, (+ f"{endpoint} should return 403 when control disabled, "+ f"got {response.status_code}"+ )++ def test_read_only_endpoints_not_gated(self, client, app):+ """Read-only scheduler endpoints are not blocked by the setting."""+ self._auth_session(client)+ with (+ patch(+ "local_deep_research.news.flask_api.get_env_setting",+ return_value=False,+ ),+ patch(+ "local_deep_research.web.auth.decorators.db_manager",+ ) as mock_db,+ ):+ mock_db.connections = {"testuser": True}++ for endpoint in self.NON_GATED_ENDPOINTS:+ response = client.get(endpoint)+ # Should NOT be 403 — these are read-only and not gated+ assert response.status_code != 403, (+ f"{endpoint} should not be gated by allow_api_control, "+ f"but got 403"+ )++class TestErrorHandling:"""Tests for error handling in endpoints."""