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.

refactor: eliminate server_config.json — env-var-only server settings (#2505)

LearningCircuit8d32f5f9e318
diff --git a/.github/scripts/check-file-writes.sh b/.github/scripts/check-file-writes.sh
index 74b0820ad8..8f44bd7265 100755
--- a/.github/scripts/check-file-writes.sh
+++ b/.github/scripts/check-file-writes.sh
@@ -181,7 +181,7 @@ if [ -n "$ALL_MATCHES" ]; then
# Filter system config files (not user data)
if [ "$skip_line" -eq 0 ]; then
- if echo "$line" | grep -qE "web/app_factory\.py|web/server_config\.py|document_loaders/bytes_loader\.py"; then
+ if echo "$line" | grep -qE "web/app_factory\.py|document_loaders/bytes_loader\.py"; then
skip_line=1
fi
fi
diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md
index 13a5e1218d..e894292a90 100644
--- a/docs/CONFIGURATION.md
+++ b/docs/CONFIGURATION.md
@@ -60,8 +60,8 @@ They are not available in the Web UI because they are needed to start the applic
| Key | Environment Variable | Default Value | Description | Type |
|-----|----------------------|---------------|-------------|------|
-| `app.allow_registrations` | `LDR_APP_ALLOW_REGISTRATIONS` | `true` | Allow new user registrations through the web interface. This setting cannot be changed from the UI for security reasons. To disable registration on public-facing deployments, set the environment variable LDR_APP_ALLOW_REGISTRATIONS=false. Enabled by default so initial account creation works out of the box. | APP |
-| `app.debug` | `LDR_APP_DEBUG` | `false` | Produces more informative errors when something goes wrong, but may expose sensitive data. This setting cannot be changed from the UI for security reasons. To enable debug mode, set the environment variable LDR_APP_DEBUG=true or edit server_config.json. | APP |
+| `app.allow_registrations` | `LDR_APP_ALLOW_REGISTRATIONS` | `true` | Allow new user registrations through the web interface. Configured via LDR_APP_ALLOW_REGISTRATIONS environment variable. Set to 'false' to disable on public-facing deployments. Enabled by default so initial account creation works out of the box. Requires server restart. | APP |
+| `app.debug` | `LDR_APP_DEBUG` | `false` | Produces more informative errors when something goes wrong, but may expose sensitive data. Configured via LDR_APP_DEBUG environment variable. Requires server restart. | APP |
| `app.enable_file_logging` | `LDR_APP_ENABLE_FILE_LOGGING` | `false` | Enable logging to files (WARNING: Log files are unencrypted and may contain sensitive data) | APP |
| `app.enable_notifications` | `LDR_APP_ENABLE_NOTIFICATIONS` | `true` | Enable browser notifications for research events | APP |
| `app.enable_web` | `LDR_APP_ENABLE_WEB` | `true` | Enable the web interface. When disabled, the application runs in CLI-only mode. Requires server restart to take effect. | APP |
@@ -77,6 +77,7 @@ They are not available in the Web UI because they are needed to start the applic
| `app.timezone` | `TZ` | `UTC` | Timezone for date calculations (e.g., news subscription YYYY-MM-DD placeholder). Use 'UTC' for server time or specify your local timezone. | APP |
| `app.warnings.dismiss_context_reduced` | `LDR_APP_WARNINGS_DISMISS_CONTEXT_REDUCED` | `false` | Dismiss warnings based on historical context usage and truncation | APP |
| `app.warnings.dismiss_high_context` | `LDR_APP_WARNINGS_DISMISS_HIGH_CONTEXT` | `false` | Dismiss warnings about high context window sizes that may cause memory issues | APP |
+| `app.warnings.dismiss_legacy_config` | `LDR_APP_WARNINGS_DISMISS_LEGACY_CONFIG` | `false` | Dismiss warnings about the deprecated server_config.json file | APP |
| `app.warnings.dismiss_model_mismatch` | `LDR_APP_WARNINGS_DISMISS_MODEL_MISMATCH` | `false` | Dismiss warnings about context size vs model size mismatches | APP |
| `app.warnings.dismiss_searxng_recommendation` | `LDR_APP_WARNINGS_DISMISS_SEARXNG_RECOMMENDATION` | `false` | Dismiss recommendations about using more questions instead of iterations with SearXNG | APP |
| `app.web_interface` | `LDR_APP_WEB_INTERFACE` | `true` | Enable the web interface | APP |
@@ -533,19 +534,20 @@ They are not available in the Web UI because they are needed to start the applic
| `search.region` | `LDR_SEARCH_REGION` | `us` | Geographic region for search results localization. Affects which results are prioritized based on regional relevance. | SEARCH |
| `search.safe_search` | `LDR_SEARCH_SAFE_SEARCH` | `true` | Filter out adult and inappropriate content from search results. Passed to search engines that support content filtering. | SEARCH |
| `search.search_language` | `LDR_SEARCH_SEARCH_LANGUAGE` | `English` | Preferred language for search results. Search engines will attempt to return and prioritize results in this language when available. | SEARCH |
-| `search.search_strategy` | `LDR_SEARCH_SEARCH_STRATEGY` | `source-based` | Research methodology. 'source-based': Finds and extracts from sources (good for comprehensive research). 'focused-iteration': Uses entity-based progressive exploration (optimized for factual Q&A, ~95% SimpleQA accuracy, requires larger context windows). 'focused-iteration-standard': Comprehensive variant of focused-iteration with broader exploration. 'iterative-refinement': LLM-guided progressive refinement with gap analysis. 'topic-organization': Organizes research around discovered topic clusters. | SEARCH |
+| `search.search_strategy` | `LDR_SEARCH_SEARCH_STRATEGY` | `source-based` | Research methodology. 'source-based': Finds and extracts from sources (good for comprehensive research). 'focused-iteration': Uses entity-based progressive exploration (optimized for factual Q&A, ~95% SimpleQA accuracy, requires larger context windows). 'focused-iteration-standard': Comprehensive variant of focused-iteration with broader exploration. 'iterative-refinement': LLM-guided progressive refinement with gap analysis. 'topic-organization': Organizes research around discovered topic clusters. 'mcp': Agentic ReAct-pattern research using MCP tools. | SEARCH |
| `search.searches_per_section` | `LDR_SEARCH_SEARCHES_PER_SECTION` | `2` | Number of independent searches per report section when generating structured reports. Increases coverage but also increases API usage. | SEARCH |
| `search.skip_relevance_filter` | `LDR_SEARCH_SKIP_RELEVANCE_FILTER` | `true` | Global override to skip LLM relevance filtering for ALL search engines. When false, filtering is auto-enabled for academic engines (arXiv, Semantic Scholar, etc.) that use keyword matching, and auto-disabled for generic engines (Google, Brave, etc.) that already use semantic search. | SEARCH |
| `search.snippets_only` | `LDR_SEARCH_SNIPPETS_ONLY` | `true` | Only retrieve search snippets instead of full webpage content. Reduces API usage and processing time, but provides less context for analysis. | SEARCH |
| `search.time_period` | `LDR_SEARCH_TIME_PERIOD` | `y` | Time range filter for search results. Limits results to content published within the specified period (day, week, month, year, or all time). | SEARCH |
| `search.tool` | `LDR_SEARCH_TOOL` | `searxng` | Web search engine to use for research | SEARCH |
-| `security.rate_limit_default` | `LDR_SECURITY_RATE_LIMIT_DEFAULT` | `5000 per hour;50000 per day` | Default rate limit for all HTTP endpoints. Multiple limits can be separated by semicolons (e.g., '5000 per hour;50000 per day'). Format: 'N per hour/minute/day'. | APP |
-| `security.rate_limit_login` | `LDR_SECURITY_RATE_LIMIT_LOGIN` | `5 per 15 minutes` | Rate limit for login attempts to prevent brute force attacks (e.g., '5 per 15 minutes'). | APP |
-| `security.rate_limit_registration` | `LDR_SECURITY_RATE_LIMIT_REGISTRATION` | `3 per hour` | Rate limit for registration attempts to prevent spam (e.g., '3 per hour'). | APP |
+| `security.rate_limit_default` | `LDR_SECURITY_RATE_LIMIT_DEFAULT` | `5000 per hour;50000 per day` | Default rate limit for all HTTP endpoints. Configured via LDR_SECURITY_RATE_LIMIT_DEFAULT environment variable. Multiple limits can be separated by semicolons (e.g., '5000 per hour;50000 per day'). Format: 'N per hour/minute/day'. Requires server restart. | APP |
+| `security.rate_limit_login` | `LDR_SECURITY_RATE_LIMIT_LOGIN` | `5 per 15 minutes` | Rate limit for login attempts to prevent brute force attacks. Configured via LDR_SECURITY_RATE_LIMIT_LOGIN environment variable (e.g., '5 per 15 minutes'). Requires server restart. | APP |
+| `security.rate_limit_registration` | `LDR_SECURITY_RATE_LIMIT_REGISTRATION` | `3 per hour` | Rate limit for registration attempts to prevent spam. Configured via LDR_SECURITY_RATE_LIMIT_REGISTRATION environment variable (e.g., '3 per hour'). Requires server restart. | APP |
+| `security.rate_limit_settings` | `LDR_SECURITY_RATE_LIMIT_SETTINGS` | `30 per minute` | Rate limit for settings modification endpoints. Configured via LDR_SECURITY_RATE_LIMIT_SETTINGS environment variable. Requires server restart. | APP |
| `security.session_remember_me_days` | `LDR_SECURITY_SESSION_REMEMBER_ME_DAYS` | `30` | Number of days a 'Remember Me' session remains valid before requiring re-login. | APP |
| `security.session_timeout_hours` | `LDR_SECURITY_SESSION_TIMEOUT_HOURS` | `2` | Session timeout in hours for sessions without 'Remember Me' checked. Only applies to internal session validation (browser sessions expire on close). | APP |
-| `web.host` | `LDR_WEB_HOST` | `0.0.0.0` | The host address to listen on. | SEARCH |
-| `web.port` | `LDR_WEB_PORT` | `5000` | The port to listen on. | SEARCH |
-| `web.use_https` | `LDR_WEB_USE_HTTPS` | `true` | Whether to enable HTTPS for the web interface. | SEARCH |
+| `web.host` | `LDR_WEB_HOST` | `0.0.0.0` | The host address to listen on. Configured via LDR_WEB_HOST environment variable. Requires server restart. | APP |
+| `web.port` | `LDR_WEB_PORT` | `5000` | The port to listen on. Configured via LDR_WEB_PORT environment variable. Requires server restart. | APP |
+| `web.use_https` | `LDR_WEB_USE_HTTPS` | `true` | Whether to enable HTTPS for the web interface. Configured via LDR_WEB_USE_HTTPS environment variable. Requires server restart. | APP |
*Generated by scripts/generate_config_docs.py*
diff --git a/docs/env_configuration.md b/docs/env_configuration.md
index 0cb2bafd9d..9e66ac8d6c 100644
--- a/docs/env_configuration.md
+++ b/docs/env_configuration.md
@@ -113,15 +113,35 @@ docker run -p 5000:5000 \
local-deep-research
```
+## Migrating from server_config.json
+
+The `server_config.json` file is deprecated and will be removed in a future release. Migrate your settings to environment variables using this mapping:
+
+| server_config.json key | Environment Variable |
+|------------------------|---------------------|
+| `host` | `LDR_WEB_HOST` |
+| `port` | `LDR_WEB_PORT` |
+| `debug` | `LDR_APP_DEBUG` |
+| `use_https` | `LDR_WEB_USE_HTTPS` |
+| `allow_registrations` | `LDR_APP_ALLOW_REGISTRATIONS` |
+| `rate_limit_default` | `LDR_SECURITY_RATE_LIMIT_DEFAULT` |
+| `rate_limit_login` | `LDR_SECURITY_RATE_LIMIT_LOGIN` |
+| `rate_limit_registration` | `LDR_SECURITY_RATE_LIMIT_REGISTRATION` |
+| `rate_limit_settings` | `LDR_SECURITY_RATE_LIMIT_SETTINGS` |
+
+After setting the environment variables, delete `server_config.json` from your data directory. The web UI will show a warning banner while the file still exists.
+
## Common Operations
### Changing the Web Port
```bash
-export LDR_APP_PORT=8080 # Linux/Mac
-set LDR_APP_PORT=8080 # Windows
+export LDR_WEB_PORT=8080 # Linux/Mac
+set LDR_WEB_PORT=8080 # Windows
```
+> **Note:** `LDR_APP_PORT` is a separate setting for notification URL generation. To change the port the server listens on, use `LDR_WEB_PORT`. Requires server restart.
+
### Setting API Keys
```bash
diff --git a/src/local_deep_research/defaults/default_settings.json b/src/local_deep_research/defaults/default_settings.json
index dc827291e7..c41212c969 100644
--- a/src/local_deep_research/defaults/default_settings.json
+++ b/src/local_deep_research/defaults/default_settings.json
@@ -1,7 +1,7 @@
{
"app.debug": {
"category": "app_interface",
- "description": "Produces more informative errors when something goes wrong, but may expose sensitive data. This setting cannot be changed from the UI for security reasons. To enable debug mode, set the environment variable LDR_APP_DEBUG=true or edit server_config.json.",
+ "description": "Produces more informative errors when something goes wrong, but may expose sensitive data. Configured via LDR_APP_DEBUG environment variable. Requires server restart.",
"editable": false,
"max_value": null,
"min_value": null,
@@ -11,7 +11,7 @@
"type": "APP",
"ui_element": "checkbox",
"value": false,
- "visible": true
+ "visible": false
},
"app.lock_settings": {
"category": "app_interface",
@@ -263,7 +263,7 @@
},
"app.allow_registrations": {
"category": "app_interface",
- "description": "Allow new user registrations through the web interface. This setting cannot be changed from the UI for security reasons. To disable registration on public-facing deployments, set the environment variable LDR_APP_ALLOW_REGISTRATIONS=false. Enabled by default so initial account creation works out of the box.",
+ "description": "Allow new user registrations through the web interface. Configured via LDR_APP_ALLOW_REGISTRATIONS environment variable. Set to 'false' to disable on public-facing deployments. Enabled by default so initial account creation works out of the box. Requires server restart.",
"editable": false,
"max_value": null,
"min_value": null,
@@ -273,7 +273,7 @@
"type": "APP",
"ui_element": "checkbox",
"value": true,
- "visible": true
+ "visible": false
},
"llm.llamacpp_f16_kv": {
"category": null,
@@ -3359,45 +3359,45 @@
},
"web.host": {
"category": null,
- "description": "The host address to listen on.",
- "editable": true,
+ "description": "The host address to listen on. Configured via LDR_WEB_HOST environment variable. Requires server restart.",
+ "editable": false,
"max_value": null,
"min_value": null,
"name": "Host",
"options": null,
"step": null,
- "type": "SEARCH",
+ "type": "APP",
"ui_element": "text",
"value": "0.0.0.0",
- "visible": true
+ "visible": false
},
"web.port": {
"category": null,
- "description": "The port to listen on.",
- "editable": true,
- "max_value": 0,
- "min_value": 65535,
+ "description": "The port to listen on. Configured via LDR_WEB_PORT environment variable. Requires server restart.",
+ "editable": false,
+ "max_value": 65535,
+ "min_value": 1,
"name": "Port",
"options": null,
"step": null,
- "type": "SEARCH",
+ "type": "APP",
"ui_element": "number",
"value": 5000,
- "visible": true
+ "visible": false
},
"web.use_https": {
"category": null,
- "description": "Whether to enable HTTPS for the web interface.",
- "editable": true,
+ "description": "Whether to enable HTTPS for the web interface. Configured via LDR_WEB_USE_HTTPS environment variable. Requires server restart.",
+ "editable": false,
"max_value": null,
"min_value": null,
"name": "Use HTTPS",
"options": null,
"step": null,
- "type": "SEARCH",
+ "type": "APP",
"ui_element": "checkbox",
"value": true,
- "visible": true
+ "visible": false
},
"search.engine.web.wikipedia.display_name": {
"category": "wikipedia",
@@ -4280,6 +4280,20 @@
"value": false,
"visible": true
},
+ "app.warnings.dismiss_legacy_config": {
+ "category": "warnings",
+ "description": "Dismiss warnings about the deprecated server_config.json file",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Dismiss Legacy Config Warnings",
+ "options": null,
+ "step": null,
+ "type": "APP",
+ "ui_element": "checkbox",
+ "value": false,
+ "visible": true
+ },
"app.warnings.dismiss_model_mismatch": {
"category": "warnings",
"description": "Permanently hide the warning shown when using a large model (70B+ parameters) with a local provider and high context window, which may exceed available GPU memory.",
diff --git a/src/local_deep_research/defaults/settings_security.json b/src/local_deep_research/defaults/settings_security.json
index 04709920af..dcdf9ac451 100644
--- a/src/local_deep_research/defaults/settings_security.json
+++ b/src/local_deep_research/defaults/settings_security.json
@@ -1,39 +1,51 @@
{
"security.rate_limit_default": {
"category": "security",
- "description": "Default rate limit for all HTTP endpoints. Multiple limits can be separated by semicolons (e.g., '5000 per hour;50000 per day'). Format: 'N per hour/minute/day'.",
- "editable": true,
+ "description": "Default rate limit for all HTTP endpoints. Configured via LDR_SECURITY_RATE_LIMIT_DEFAULT environment variable. Multiple limits can be separated by semicolons (e.g., '5000 per hour;50000 per day'). Format: 'N per hour/minute/day'. Requires server restart.",
+ "editable": false,
"max_value": null,
"min_value": null,
"name": "Default Rate Limit",
"type": "APP",
"ui_element": "text",
"value": "5000 per hour;50000 per day",
- "visible": true
+ "visible": false
},
"security.rate_limit_login": {
"category": "security",
- "description": "Rate limit for login attempts to prevent brute force attacks (e.g., '5 per 15 minutes').",
- "editable": true,
+ "description": "Rate limit for login attempts to prevent brute force attacks. Configured via LDR_SECURITY_RATE_LIMIT_LOGIN environment variable (e.g., '5 per 15 minutes'). Requires server restart.",
+ "editable": false,
"max_value": null,
"min_value": null,
"name": "Login Rate Limit",
"type": "APP",
"ui_element": "text",
"value": "5 per 15 minutes",
- "visible": true
+ "visible": false
},
"security.rate_limit_registration": {
"category": "security",
- "description": "Rate limit for registration attempts to prevent spam (e.g., '3 per hour').",
- "editable": true,
+ "description": "Rate limit for registration attempts to prevent spam. Configured via LDR_SECURITY_RATE_LIMIT_REGISTRATION environment variable (e.g., '3 per hour'). Requires server restart.",
+ "editable": false,
"max_value": null,
"min_value": null,
"name": "Registration Rate Limit",
"type": "APP",
"ui_element": "text",
"value": "3 per hour",
- "visible": true
+ "visible": false
+ },
+ "security.rate_limit_settings": {
+ "category": "security",
+ "description": "Rate limit for settings modification endpoints. Configured via LDR_SECURITY_RATE_LIMIT_SETTINGS environment variable. Requires server restart.",
+ "editable": false,
+ "max_value": null,
+ "min_value": null,
+ "name": "Settings Rate Limit",
+ "type": "APP",
+ "ui_element": "text",
+ "value": "30 per minute",
+ "visible": false
},
"security.session_remember_me_days": {
"category": "security",
diff --git a/src/local_deep_research/web/app.py b/src/local_deep_research/web/app.py
index bab10112e4..ca96a73aa6 100644
--- a/src/local_deep_research/web/app.py
+++ b/src/local_deep_research/web/app.py
@@ -37,8 +37,8 @@ def main():
# Create the Flask app and SocketIO instance
app, socket_service = create_app()
- # Get web server settings from configuration file or environment
- # This allows settings to be configured through the web UI
+ # Get web server settings from environment variables (LDR_WEB_HOST, etc.)
+ # These require a server restart to take effect
host = config["host"]
port = config["port"]
debug = config["debug"]
diff --git a/src/local_deep_research/web/routes/settings_routes.py b/src/local_deep_research/web/routes/settings_routes.py
index ac72aa8658..12bfca117b 100644
--- a/src/local_deep_research/web/routes/settings_routes.py
+++ b/src/local_deep_research/web/routes/settings_routes.py
@@ -71,7 +71,8 @@ from ..services.settings_service import (
set_setting,
)
from ..utils.templates import render_template_with_defaults
-from ..server_config import sync_from_settings
+
+
from ...security import safe_get
from ..warning_checks import calculate_warnings
@@ -497,26 +498,27 @@ def save_all_settings():
)
# Get all settings to return to the client for proper state update
- all_settings = []
+ all_settings = {}
for setting in db_session.query(Setting).all():
# Convert enum to string if present
setting_type = setting.type
if hasattr(setting_type, "value"):
setting_type = setting_type.value
- all_settings.append(
- {
- "key": setting.key,
- "value": setting.value,
- "name": setting.name,
- "description": setting.description,
- "type": setting_type,
- "category": setting.category,
- "ui_element": setting.ui_element,
- "editable": setting.editable,
- "options": setting.options,
- }
- )
+ all_settings[setting.key] = {
+ "value": setting.value,
+ "name": setting.name,
+ "description": setting.description,
+ "type": setting_type,
+ "category": setting.category,
+ "ui_element": setting.ui_element,
+ "editable": setting.editable,
+ "options": setting.options,
+ "visible": setting.visible,
+ "min_value": setting.min_value,
+ "max_value": setting.max_value,
+ "step": setting.step,
+ }
# Customize the success message based on what changed
success_message = ""
@@ -724,10 +726,6 @@ def save_settings():
"warning",
)
- # Sync server config
- settings_snapshot = settings_manager.get_settings_snapshot()
- sync_from_settings(settings_snapshot)
-
except Exception:
db_session.rollback()
logger.exception("Failed to commit settings")
@@ -887,11 +885,6 @@ def api_update_setting(key):
# Pass the db_session to avoid session lookup issues
success = set_setting(key, value, db_session=db_session)
if success:
- # Sync server config
- settings_manager = SettingsManager(db_session)
- settings_snapshot = settings_manager.get_settings_snapshot()
- sync_from_settings(settings_snapshot)
-
response_data = {
"message": f"Setting {key} updated successfully"
}
@@ -951,11 +944,6 @@ def api_update_setting(key):
)
if db_setting:
- # Sync server config
- settings_manager = SettingsManager(db_session)
- settings_snapshot = settings_manager.get_settings_snapshot()
- sync_from_settings(settings_snapshot)
-
return (
jsonify(
{
diff --git a/src/local_deep_research/web/server_config.py b/src/local_deep_research/web/server_config.py
index e9a8ad4afd..007296cb3f 100644
--- a/src/local_deep_research/web/server_config.py
+++ b/src/local_deep_research/web/server_config.py
@@ -1,71 +1,196 @@
"""Server configuration management for web app startup.
This module handles server configuration that needs to be available before
-Flask app context is established. It provides a bridge between environment
-variables and database settings.
+Flask app context is established. All settings are read from environment
+variables (LDR_* naming convention) with sensible defaults.
+
+During the deprecation period, legacy ``server_config.json`` files are read
+as a read-only fallback (env var > legacy file > default). No data is
+written back to the JSON file.
"""
import json
import os
from pathlib import Path
-from typing import Dict, Any
+from typing import Any, Dict
from loguru import logger
from ..config.paths import get_data_dir
from ..settings.manager import get_typed_setting_value
+# Maps legacy JSON keys → (setting_key, env_var_name, is_security_critical)
+_LEGACY_KEY_MAP: Dict[str, tuple] = {
+ "host": ("web.host", "LDR_WEB_HOST", False),
+ "port": ("web.port", "LDR_WEB_PORT", False),
+ "debug": ("app.debug", "LDR_APP_DEBUG", False),
+ "use_https": ("web.use_https", "LDR_WEB_USE_HTTPS", False),
+ "allow_registrations": (
+ "app.allow_registrations",
+ "LDR_APP_ALLOW_REGISTRATIONS",
+ True,
+ ),
+ "rate_limit_default": (
+ "security.rate_limit_default",
+ "LDR_SECURITY_RATE_LIMIT_DEFAULT",
+ False,
+ ),
+ "rate_limit_login": (
+ "security.rate_limit_login",
+ "LDR_SECURITY_RATE_LIMIT_LOGIN",
+ False,
+ ),
+ "rate_limit_registration": (
+ "security.rate_limit_registration",
+ "LDR_SECURITY_RATE_LIMIT_REGISTRATION",
+ False,
+ ),
+ "rate_limit_settings": (
+ "security.rate_limit_settings",
+ "LDR_SECURITY_RATE_LIMIT_SETTINGS",
+ False,
+ ),
+}
+
def get_server_config_path() -> Path:
- """Get the path to the server configuration file."""
+ """Return the path to the legacy server_config.json file."""
return Path(get_data_dir()) / "server_config.json"
+def _load_legacy_config() -> Dict[str, Any]:
+ """Read legacy server_config.json as a read-only migration fallback.
+
+ Returns a dict of ``{json_key: value}`` for recognized keys found in the
+ file. Returns ``{}`` when the file does not exist or is malformed.
+
+ Logs deprecation warnings so users know to migrate to env vars.
+ """
+ config_path = get_server_config_path()
+ if not config_path.exists():
+ return {}
+
+ try:
+ data = json.loads(config_path.read_text(encoding="utf-8"))
+ except (json.JSONDecodeError, OSError) as exc:
+ logger.warning(
+ f"Could not read legacy server_config.json at {config_path}: "
+ f"{exc}. Ignoring file."
+ )
+ return {}
+
+ if not isinstance(data, dict):
+ logger.warning(
+ f"Legacy server_config.json at {config_path} does not contain a "
+ f"JSON object. Ignoring file."
+ )
+ return {}
+
+ saved: Dict[str, Any] = {}
+ for json_key, (
+ setting_key,
+ env_var,
+ is_critical,
+ ) in _LEGACY_KEY_MAP.items():
+ if json_key not in data:
+ continue
+
+ saved[json_key] = data[json_key]
+
+ if is_critical:
+ logger.warning(
+ f"SECURITY: server_config.json contains '{json_key}={data[json_key]}'. "
+ f"This value will be honored during the deprecation period, but you "
+ f"should migrate to the environment variable {env_var} and delete "
+ f"server_config.json."
+ )
+ else:
+ logger.info(
+ f"Legacy server_config.json contains '{json_key}'. "
+ f"Migrate to environment variable {env_var}."
+ )
+
+ # Warn about unrecognized keys (likely typos)
+ unrecognized = set(data.keys()) - set(_LEGACY_KEY_MAP.keys())
+ if unrecognized:
+ logger.warning(
+ f"Legacy server_config.json contains unrecognized keys: "
+ f"{sorted(unrecognized)}. These will be ignored. "
+ f"Recognized keys: {sorted(_LEGACY_KEY_MAP.keys())}."
+ )
+
+ if saved:
+ logger.warning(
+ f"DEPRECATED: server_config.json found at {config_path}. "
+ f"Migrate settings to environment variables, then delete the file. "
+ f"Support for this file will be removed in a future release."
+ )
+
+ return saved
+
+
def load_server_config() -> Dict[str, Any]:
- """Load server configuration from file or environment variables.
+ """Load server configuration from environment variables.
+
+ During the deprecation period, values from a legacy ``server_config.json``
+ are used as fallbacks when the corresponding env var is not set.
+
+ Priority: environment variable > legacy JSON file > built-in default.
Returns:
- dict: Server configuration with keys: host, port, debug, use_https
+ dict: Server configuration with keys: host, port, debug, use_https,
+ allow_registrations, rate_limit_default, rate_limit_login,
+ rate_limit_registration, rate_limit_settings
"""
- config_path = get_server_config_path()
+ saved = _load_legacy_config()
- # Try to load from config file first
- saved_config = {}
- if config_path.exists():
- try:
- with open(config_path, "r") as f:
- saved_config = json.load(f)
- logger.debug(f"Loaded server config from {config_path}")
- except Exception as e:
- logger.warning(f"Failed to load server config: {e}")
-
- # Ensure correct typing and check environment variables.
config = {
"host": get_typed_setting_value(
- "web.host", saved_config.get("host"), "text", default="0.0.0.0"
+ "web.host", saved.get("host"), "text", default="0.0.0.0"
),
"port": get_typed_setting_value(
- "web.port", saved_config.get("port"), "number", default=5000
+ "web.port", saved.get("port"), "number", default=5000
),
"debug": get_typed_setting_value(
- "app.debug", saved_config.get("debug"), "checkbox", default=False
+ "app.debug", saved.get("debug"), "checkbox", default=False
),
"use_https": get_typed_setting_value(
- "web.use_https",
- saved_config.get("use_https"),
- "checkbox",
- default=True,
+ "web.use_https", saved.get("use_https"), "checkbox", default=True
),
"allow_registrations": get_typed_setting_value(
"app.allow_registrations",
- saved_config.get("allow_registrations"),
+ saved.get("allow_registrations"),
"checkbox",
default=True,
),
+ "rate_limit_default": get_typed_setting_value(
+ "security.rate_limit_default",
+ saved.get("rate_limit_default"),
+ "text",
+ default="5000 per hour;50000 per day",
+ ),
+ "rate_limit_login": get_typed_setting_value(
+ "security.rate_limit_login",
+ saved.get("rate_limit_login"),
+ "text",
+ default="5 per 15 minutes",
+ ),
+ "rate_limit_registration": get_typed_setting_value(
+ "security.rate_limit_registration",
+ saved.get("rate_limit_registration"),
+ "text",
+ default="3 per hour",
+ ),
+ "rate_limit_settings": get_typed_setting_value(
+ "security.rate_limit_settings",
+ saved.get("rate_limit_settings"),
+ "text",
+ default="30 per minute",
+ ),
}
- # Security: if LDR_APP_ALLOW_REGISTRATIONS is set to an unrecognized
- # value (e.g. "disabled", "nein", typos like "flase"), default to False
+ # Security: if allow_registrations is set to an unrecognized string value
+ # (e.g. "disabled", "nein", typos like "flase"), default to False
# (registrations disabled) rather than True. This "fail closed" approach
# prevents accidental open registration when an admin clearly intended to
# restrict it but used a non-standard boolean string.
@@ -79,6 +204,8 @@ def load_server_config() -> Dict[str, Any]:
"on",
"off",
}
+
+ # Guard for env var path
raw_reg_env = os.getenv("LDR_APP_ALLOW_REGISTRATIONS")
if raw_reg_env is not None:
normalized = raw_reg_env.lower().strip()
@@ -91,90 +218,22 @@ def load_server_config() -> Dict[str, Any]:
)
config["allow_registrations"] = False
- config.update(
- {
- # Rate limiting settings
- "rate_limit_default": get_typed_setting_value(
- "security.rate_limit_default",
- saved_config.get("rate_limit_default"),
- "text",
- default="5000 per hour;50000 per day",
- ),
- "rate_limit_login": get_typed_setting_value(
- "security.rate_limit_login",
- saved_config.get("rate_limit_login"),
- "text",
- default="5 per 15 minutes",
- ),
- "rate_limit_registration": get_typed_setting_value(
- "security.rate_limit_registration",
- saved_config.get("rate_limit_registration"),
- "text",
- default="3 per hour",
- ),
- }
- )
+ # Guard for legacy JSON path: if legacy JSON had a string value for
+ # allow_registrations (e.g. "disabled") and no env var overrides it,
+ # parse_boolean would treat any non-empty string as True (HTML checkbox
+ # semantics). Fail closed to prevent accidental open registration.
+ elif (
+ "allow_registrations" in saved
+ and isinstance(saved["allow_registrations"], str)
+ and saved["allow_registrations"].lower().strip()
+ not in _RECOGNIZED_BOOL_VALUES
+ ):
+ logger.warning(
+ f"Legacy server_config.json has allow_registrations="
+ f"'{saved['allow_registrations']}' which is not a recognized "
+ f"boolean value. Defaulting to FALSE (registrations disabled) "
+ f"for security."
+ )
+ config["allow_registrations"] = False
return config
-
-
-def save_server_config(config: Dict[str, Any]) -> None:
- """Save server configuration to file.
-
- This should be called when web.host or web.port settings are updated
- through the UI.
-
- Args:
- config: Server configuration dict
- """
- config_path = get_server_config_path()
-
- try:
- # Ensure directory exists
- config_path.parent.mkdir(parents=True, exist_ok=True)
-
- with open(config_path, "w") as f:
- json.dump(config, f, indent=2)
-
- logger.info(f"Saved server config to {config_path}")
- except Exception:
- logger.exception("Failed to save server config")
-
-
-def sync_from_settings(settings_snapshot: Dict[str, Any]) -> None:
- """Sync server config from settings snapshot.
-
- This should be called when settings are updated through the UI.
-
- Args:
- settings_snapshot: Settings snapshot containing web.host and web.port
- """
- config = load_server_config()
-
- # Update from settings if available
- if "web.host" in settings_snapshot:
- config["host"] = settings_snapshot["web.host"]
- if "web.port" in settings_snapshot:
- config["port"] = settings_snapshot["web.port"]
- if "app.debug" in settings_snapshot:
- config["debug"] = settings_snapshot["app.debug"]
- if "web.use_https" in settings_snapshot:
- config["use_https"] = settings_snapshot["web.use_https"]
- if "app.allow_registrations" in settings_snapshot:
- config["allow_registrations"] = settings_snapshot[
- "app.allow_registrations"
- ]
- if "security.rate_limit_default" in settings_snapshot:
- config["rate_limit_default"] = settings_snapshot[
- "security.rate_limit_default"
- ]
- if "security.rate_limit_login" in settings_snapshot:
- config["rate_limit_login"] = settings_snapshot[
- "security.rate_limit_login"
- ]
- if "security.rate_limit_registration" in settings_snapshot:
- config["rate_limit_registration"] = settings_snapshot[
- "security.rate_limit_registration"
- ]
-
- save_server_config(config)
diff --git a/src/local_deep_research/web/static/js/components/settings.js b/src/local_deep_research/web/static/js/components/settings.js
index 7792b4b6da..e84826ea8d 100644
--- a/src/local_deep_research/web/static/js/components/settings.js
+++ b/src/local_deep_research/web/static/js/components/settings.js
@@ -2572,7 +2572,7 @@
if (settingIndex !== -1 && data.settings) {
// Find the updated setting in the response
- const updatedSetting = data.settings.find(s => s.key === key);
+ const updatedSetting = data.settings[key];
if (updatedSetting) {
// Update the setting in our array
diff --git a/src/local_deep_research/web/utils/rate_limiter.py b/src/local_deep_research/web/utils/rate_limiter.py
index bcdecf76d8..72f688405c 100644
--- a/src/local_deep_research/web/utils/rate_limiter.py
+++ b/src/local_deep_research/web/utils/rate_limiter.py
@@ -2,8 +2,9 @@
Rate limiting utility for authentication endpoints.
Provides a global limiter instance that can be imported by blueprints.
-Rate limits are configurable via UI settings (security.rate_limit_*) and
-stored in server_config.json. Changes require server restart to take effect.
+Rate limits are configurable via environment variables (LDR_SECURITY_RATE_LIMIT_*).
+Legacy server_config.json values are honored during the deprecation period.
+Changes require server restart to take effect.
Note: This is designed for single-instance local deployments. For multi-worker
production deployments, configure Redis storage via RATELIMIT_STORAGE_URL.
@@ -23,7 +24,7 @@ DEFAULT_RATE_LIMIT = _config["rate_limit_default"]
LOGIN_RATE_LIMIT = _config["rate_limit_login"]
REGISTRATION_RATE_LIMIT = _config["rate_limit_registration"]
# Settings modification rate limit - prevent abuse of settings endpoints
-SETTINGS_RATE_LIMIT = _config.get("rate_limit_settings", "30 per minute")
+SETTINGS_RATE_LIMIT = _config["rate_limit_settings"]
def get_client_ip():
diff --git a/src/local_deep_research/web/warning_checks/__init__.py b/src/local_deep_research/web/warning_checks/__init__.py
index 27791fc20a..4dce3455fe 100644
--- a/src/local_deep_research/web/warning_checks/__init__.py
+++ b/src/local_deep_research/web/warning_checks/__init__.py
@@ -15,7 +15,12 @@ from .context import (
check_context_below_history,
check_context_truncation_history,
)
-from .hardware import LOCAL_PROVIDERS, check_high_context, check_model_mismatch
+from .hardware import (
+ LOCAL_PROVIDERS,
+ check_high_context,
+ check_legacy_server_config,
+ check_model_mismatch,
+)
def _safe_check(check_fn, *args, **kwargs):
@@ -60,6 +65,9 @@ def calculate_warnings() -> List[dict]:
dismiss_context_warning = settings_manager.get_setting(
"app.warnings.dismiss_context_reduced", False
)
+ dismiss_legacy_config = settings_manager.get_setting(
+ "app.warnings.dismiss_legacy_config", False
+ )
logger.debug(f"Starting warning calculation - provider={provider}")
@@ -85,6 +93,10 @@ def calculate_warnings() -> List[dict]:
if w:
warnings.append(w)
+ w = _safe_check(check_legacy_server_config, dismiss_legacy_config)
+ if w:
+ warnings.append(w)
+
# --- History-based checks (need DB queries) ---
if is_local and not dismiss_context_warning:
w = _safe_check(
diff --git a/src/local_deep_research/web/warning_checks/hardware.py b/src/local_deep_research/web/warning_checks/hardware.py
index 6a6bf84d37..9eaa65ba4f 100644
--- a/src/local_deep_research/web/warning_checks/hardware.py
+++ b/src/local_deep_research/web/warning_checks/hardware.py
@@ -59,3 +59,26 @@ def check_model_mismatch(
),
"dismissKey": "app.warnings.dismiss_model_mismatch",
}
+
+
+def check_legacy_server_config(dismissed: bool) -> Optional[dict]:
+ """Return a warning if the deprecated server_config.json file exists."""
+ from ..server_config import get_server_config_path
+
+ if dismissed:
+ return None
+ if not get_server_config_path().exists():
+ return None
+
+ return {
+ "type": "legacy_server_config",
+ "icon": "⚠️",
+ "title": "Legacy Configuration File Detected",
+ "message": (
+ "A server_config.json file was found and its values are being used "
+ "as fallback. Migrate settings to environment variables (LDR_WEB_HOST, "
+ "LDR_WEB_PORT, etc.) and delete the file. Support will be removed in "
+ "a future release."
+ ),
+ "dismissKey": "app.warnings.dismiss_legacy_config",
+ }
diff --git a/tests/settings/golden_master_settings.json b/tests/settings/golden_master_settings.json
index 9591a13c34..94b5f24dda 100644
--- a/tests/settings/golden_master_settings.json
+++ b/tests/settings/golden_master_settings.json
@@ -1,7 +1,7 @@
{
"app.allow_registrations": {
"category": "app_interface",
- "description": "Allow new user registrations through the web interface. This setting cannot be changed from the UI for security reasons. To disable registration on public-facing deployments, set the environment variable LDR_APP_ALLOW_REGISTRATIONS=false. Enabled by default so initial account creation works out of the box.",
+ "description": "Allow new user registrations through the web interface. Configured via LDR_APP_ALLOW_REGISTRATIONS environment variable. Set to 'false' to disable on public-facing deployments. Enabled by default so initial account creation works out of the box. Requires server restart.",
"editable": false,
"max_value": null,
"min_value": null,
@@ -11,11 +11,11 @@
"type": "APP",
"ui_element": "checkbox",
"value": true,
- "visible": true
+ "visible": false
},
"app.debug": {
"category": "app_interface",
- "description": "Produces more informative errors when something goes wrong, but may expose sensitive data. This setting cannot be changed from the UI for security reasons. To enable debug mode, set the environment variable LDR_APP_DEBUG=true or edit server_config.json.",
+ "description": "Produces more informative errors when something goes wrong, but may expose sensitive data. Configured via LDR_APP_DEBUG environment variable. Requires server restart.",
"editable": false,
"max_value": null,
"min_value": null,
@@ -25,7 +25,7 @@
"type": "APP",
"ui_element": "checkbox",
"value": false,
- "visible": true
+ "visible": false
},
"app.enable_file_logging": {
"category": "app_interface",
@@ -412,6 +412,20 @@
"value": false,
"visible": true
},
+ "app.warnings.dismiss_legacy_config": {
+ "category": "warnings",
+ "description": "Dismiss warnings about the deprecated server_config.json file",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Dismiss Legacy Config Warnings",
+ "options": null,
+ "step": null,
+ "type": "APP",
+ "ui_element": "checkbox",
+ "value": false,
+ "visible": true
+ },
"app.warnings.dismiss_model_mismatch": {
"category": "warnings",
"description": "Permanently hide the warning shown when using a large model (70B+ parameters) with a local provider and high context window, which may exceed available GPU memory.",
@@ -7540,39 +7554,51 @@
},
"security.rate_limit_default": {
"category": "security",
- "description": "Default rate limit for all HTTP endpoints. Multiple limits can be separated by semicolons (e.g., '5000 per hour;50000 per day'). Format: 'N per hour/minute/day'.",
- "editable": true,
+ "description": "Default rate limit for all HTTP endpoints. Configured via LDR_SECURITY_RATE_LIMIT_DEFAULT environment variable. Multiple limits can be separated by semicolons (e.g., '5000 per hour;50000 per day'). Format: 'N per hour/minute/day'. Requires server restart.",
+ "editable": false,
"max_value": null,
"min_value": null,
"name": "Default Rate Limit",
"type": "APP",
"ui_element": "text",
"value": "5000 per hour;50000 per day",
- "visible": true
+ "visible": false
},
"security.rate_limit_login": {
"category": "security",
- "description": "Rate limit for login attempts to prevent brute force attacks (e.g., '5 per 15 minutes').",
- "editable": true,
+ "description": "Rate limit for login attempts to prevent brute force attacks. Configured via LDR_SECURITY_RATE_LIMIT_LOGIN environment variable (e.g., '5 per 15 minutes'). Requires server restart.",
+ "editable": false,
"max_value": null,
"min_value": null,
"name": "Login Rate Limit",
"type": "APP",
"ui_element": "text",
"value": "5 per 15 minutes",
- "visible": true
+ "visible": false
},
"security.rate_limit_registration": {
"category": "security",
- "description": "Rate limit for registration attempts to prevent spam (e.g., '3 per hour').",
- "editable": true,
+ "description": "Rate limit for registration attempts to prevent spam. Configured via LDR_SECURITY_RATE_LIMIT_REGISTRATION environment variable (e.g., '3 per hour'). Requires server restart.",
+ "editable": false,
"max_value": null,
"min_value": null,
"name": "Registration Rate Limit",
"type": "APP",
"ui_element": "text",
"value": "3 per hour",
- "visible": true
+ "visible": false
+ },
+ "security.rate_limit_settings": {
+ "category": "security",
+ "description": "Rate limit for settings modification endpoints. Configured via LDR_SECURITY_RATE_LIMIT_SETTINGS environment variable. Requires server restart.",
+ "editable": false,
+ "max_value": null,
+ "min_value": null,
+ "name": "Settings Rate Limit",
+ "type": "APP",
+ "ui_element": "text",
+ "value": "30 per minute",
+ "visible": false
},
"security.session_remember_me_days": {
"category": "security",
@@ -7600,44 +7626,44 @@
},
"web.host": {
"category": null,
- "description": "The host address to listen on.",
- "editable": true,
+ "description": "The host address to listen on. Configured via LDR_WEB_HOST environment variable. Requires server restart.",
+ "editable": false,
"max_value": null,
"min_value": null,
"name": "Host",
"options": null,
"step": null,
- "type": "SEARCH",
+ "type": "APP",
"ui_element": "text",
"value": "0.0.0.0",
- "visible": true
+ "visible": false
},
"web.port": {
"category": null,
- "description": "The port to listen on.",
- "editable": true,
- "max_value": 0,
- "min_value": 65535,
+ "description": "The port to listen on. Configured via LDR_WEB_PORT environment variable. Requires server restart.",
+ "editable": false,
+ "max_value": 65535,
+ "min_value": 1,
"name": "Port",
"options": null,
"step": null,
- "type": "SEARCH",
+ "type": "APP",
"ui_element": "number",
"value": 5000,
- "visible": true
+ "visible": false
},
"web.use_https": {
"category": null,
- "description": "Whether to enable HTTPS for the web interface.",
- "editable": true,
+ "description": "Whether to enable HTTPS for the web interface. Configured via LDR_WEB_USE_HTTPS environment variable. Requires server restart.",
+ "editable": false,
"max_value": null,
"min_value": null,
"name": "Use HTTPS",
"options": null,
"step": null,
- "type": "SEARCH",
+ "type": "APP",
"ui_element": "checkbox",
"value": true,
- "visible": true
+ "visible": false
}
}
diff --git a/tests/settings/test_settings_defaults_integrity.py b/tests/settings/test_settings_defaults_integrity.py
index ed0ef05ad6..71158f9e92 100644
--- a/tests/settings/test_settings_defaults_integrity.py
+++ b/tests/settings/test_settings_defaults_integrity.py
@@ -68,10 +68,7 @@ KNOWN_SELECT_ISSUES = {
# Known numeric constraint data bugs in current JSON.
# ---------------------------------------------------------------------------
-KNOWN_NUMERIC_ISSUES = {
- # web.port has min_value=65535, max_value=0 (swapped).
- "web.port",
-}
+KNOWN_NUMERIC_ISSUES = set()
# ---------------------------------------------------------------------------
# Consumed settings that intentionally have no JSON default.
@@ -244,8 +241,9 @@ def _is_metadata_setting(key: str) -> bool:
def _is_web_consumed_setting(key: str) -> bool:
"""Settings consumed by web server/app factory, not via get_setting().
- These are read via server_config dict access, app_factory configuration,
- or auth route logic — patterns not caught by get_setting() regex.
+ These are read via env var access (load_server_config), app_factory
+ configuration, or auth route logic — patterns not caught by get_setting()
+ regex.
"""
return key in {
"app.allow_registrations",
diff --git a/tests/web/test_server_config.py b/tests/web/test_server_config.py
index d381f77b71..0f8c4b2b41 100644
--- a/tests/web/test_server_config.py
+++ b/tests/web/test_server_config.py
@@ -1,8 +1,9 @@
"""
Tests for server_config module.
-Covers server configuration management for web app startup including
-loading, saving, and syncing configuration settings.
+Covers server configuration management for web app startup.
+All settings are read from environment variables (LDR_* naming convention).
+Includes tests for the legacy server_config.json migration path.
"""
import json
@@ -14,36 +15,12 @@ import pytest
from local_deep_research.web.server_config import (
get_server_config_path,
load_server_config,
- save_server_config,
- sync_from_settings,
)
# ---------------------------------------------------------------------------
-# Shared fixture: redirect get_data_dir to a tmp directory
+# Shared fixture: mock get_typed_setting_value to return defaults
# ---------------------------------------------------------------------------
[email protected](autouse=True)
-def _mock_data_dir(tmp_path):
- """Redirect get_data_dir to tmp_path for every test."""
- with patch(
- "local_deep_research.web.server_config.get_data_dir",
- return_value=str(tmp_path),
- ):
- yield
-
-
-def _passthrough_typed_setting():
- """Mock get_typed_setting_value to return val if not None, else default."""
- with patch(
- "local_deep_research.web.server_config.get_typed_setting_value",
- side_effect=lambda key, val, typ, default: (
- val if val is not None else default
- ),
- ):
- yield
-
-
@pytest.fixture()
def _default_typed_setting():
"""Mock get_typed_setting_value to always return default."""
@@ -54,30 +31,26 @@ def _default_typed_setting():
yield
-# ===================================================================
-# get_server_config_path
-# ===================================================================
-class TestGetServerConfigPath:
- """Tests for get_server_config_path function."""
+def _env_typed_setting():
+ """Mock get_typed_setting_value to simulate env var override.
- def test_returns_path_object(self):
- """Should return a Path object."""
- result = get_server_config_path()
- assert isinstance(result, Path)
+ Stores overrides in a dict; returns the override if present, else default.
+ """
+ overrides = {}
- def test_ends_with_server_config_json(self):
- """Should end with 'server_config.json'."""
- result = get_server_config_path()
- assert result.name == "server_config.json"
+ def _side_effect(key, val, typ, default):
+ return overrides.get(key, default)
- def test_path_under_data_dir(self, tmp_path):
- """Should be directly under the data directory."""
- result = get_server_config_path()
- assert result.parent == tmp_path
+ with patch(
+ "local_deep_research.web.server_config.get_typed_setting_value",
+ side_effect=_side_effect,
+ ):
+ yield overrides
# ===================================================================
-# load_server_config
+# load_server_config — structure and defaults
# ===================================================================
class TestLoadServerConfig:
"""Tests for load_server_config function."""
@@ -103,6 +76,7 @@ class TestLoadServerConfig:
"rate_limit_default",
"rate_limit_login",
"rate_limit_registration",
+ "rate_limit_settings",
}
assert expected_keys.issubset(result.keys())
@@ -151,65 +125,90 @@ class TestLoadServerConfig:
"""Default rate_limit_registration value."""
assert load_server_config()["rate_limit_registration"] == "3 per hour"
- # -- loading from file ---------------------------------------------
-
- @pytest.mark.usefixtures("_passthrough_typed_setting")
- def test_loads_from_existing_file(self, tmp_path):
- """Should load config values from existing JSON file."""
- config_file = tmp_path / "server_config.json"
- config_data = {
- "host": "127.0.0.1",
- "port": 8080,
- "debug": True,
- "use_https": False,
- }
- config_file.write_text(json.dumps(config_data))
-
- result = load_server_config()
-
- assert result["host"] == "127.0.0.1"
- assert result["port"] == 8080
- assert result["debug"] is True
- assert result["use_https"] is False
-
@pytest.mark.usefixtures("_default_typed_setting")
- def test_returns_defaults_when_no_file(self, tmp_path):
- """Should return default config when file does not exist."""
- assert not (tmp_path / "server_config.json").exists()
+ def test_default_rate_limit_settings(self):
+ """Default rate_limit_settings value."""
+ assert load_server_config()["rate_limit_settings"] == "30 per minute"
+ @pytest.mark.usefixtures("_default_typed_setting")
+ def test_defaults_when_no_env_vars(self):
+ """Should return all defaults when no environment variables are set."""
result = load_server_config()
assert result["host"] == "0.0.0.0"
assert result["port"] == 5000
assert result["debug"] is False
assert result["use_https"] is True
+ assert result["allow_registrations"] is True
+ assert result["rate_limit_default"] == "5000 per hour;50000 per day"
+ assert result["rate_limit_login"] == "5 per 15 minutes"
+ assert result["rate_limit_registration"] == "3 per hour"
+ assert result["rate_limit_settings"] == "30 per minute"
- # -- corrupt JSON ---------------------------------------------------
+ # -- env var overrides -----------------------------------------------
- @pytest.mark.usefixtures("_default_typed_setting")
- def test_handles_corrupt_json(self, tmp_path):
- """Should fall back to defaults on corrupt JSON."""
- config_file = tmp_path / "server_config.json"
- config_file.write_text("{ invalid json }")
+ def test_env_var_overrides_host(self, _env_typed_setting):
+ """LDR_WEB_HOST env var should override default host."""
+ _env_typed_setting["web.host"] = "127.0.0.1"
+ result = load_server_config()
+ assert result["host"] == "127.0.0.1"
+ def test_env_var_overrides_port(self, _env_typed_setting):
+ """LDR_WEB_PORT env var should override default port."""
+ _env_typed_setting["web.port"] = 8080
result = load_server_config()
+ assert result["port"] == 8080
- assert result["host"] == "0.0.0.0"
- assert result["port"] == 5000
+ def test_env_var_overrides_debug(self, _env_typed_setting):
+ """LDR_APP_DEBUG env var should override default debug."""
+ _env_typed_setting["app.debug"] = True
+ result = load_server_config()
+ assert result["debug"] is True
- @pytest.mark.usefixtures("_default_typed_setting")
- def test_corrupt_json_logs_warning(self, tmp_path):
- """Should log a warning when config file is corrupt."""
- config_file = tmp_path / "server_config.json"
- config_file.write_text("not-json")
+ def test_env_var_overrides_use_https(self, _env_typed_setting):
+ """LDR_WEB_USE_HTTPS env var should override default use_https."""
+ _env_typed_setting["web.use_https"] = False
+ result = load_server_config()
+ assert result["use_https"] is False
- with patch(
- "local_deep_research.web.server_config.logger"
- ) as mock_logger:
- load_server_config()
- mock_logger.warning.assert_called_once()
+ def test_env_var_overrides_allow_registrations(self, _env_typed_setting):
+ """Env var override for allow_registrations should be reflected in config."""
+ _env_typed_setting["app.allow_registrations"] = False
+ result = load_server_config()
+ assert result["allow_registrations"] is False
- # -- LDR_APP_ALLOW_REGISTRATIONS env var ----------------------------
+ def test_env_var_overrides_rate_limit_default(self, _env_typed_setting):
+ """LDR_SECURITY_RATE_LIMIT_DEFAULT env var should override default."""
+ _env_typed_setting["security.rate_limit_default"] = "100 per hour"
+ result = load_server_config()
+ assert result["rate_limit_default"] == "100 per hour"
+
+ def test_env_var_overrides_rate_limit_login(self, _env_typed_setting):
+ """LDR_SECURITY_RATE_LIMIT_LOGIN env var should override default."""
+ _env_typed_setting["security.rate_limit_login"] = "10 per minute"
+ result = load_server_config()
+ assert result["rate_limit_login"] == "10 per minute"
+
+ def test_env_var_overrides_rate_limit_registration(
+ self, _env_typed_setting
+ ):
+ """LDR_SECURITY_RATE_LIMIT_REGISTRATION env var should override default."""
+ _env_typed_setting["security.rate_limit_registration"] = "1 per hour"
+ result = load_server_config()
+ assert result["rate_limit_registration"] == "1 per hour"
+
+ def test_env_var_overrides_rate_limit_settings(self, _env_typed_setting):
+ """LDR_SECURITY_RATE_LIMIT_SETTINGS env var should override default."""
+ _env_typed_setting["security.rate_limit_settings"] = "60 per minute"
+ result = load_server_config()
+ assert result["rate_limit_settings"] == "60 per minute"
+
+
+# ===================================================================
+# LDR_APP_ALLOW_REGISTRATIONS fail-closed logic
+# ===================================================================
+class TestAllowRegistrationsFailClosed:
+ """Tests for fail-closed behavior of LDR_APP_ALLOW_REGISTRATIONS."""
@pytest.mark.usefixtures("_default_typed_setting")
@pytest.mark.parametrize(
@@ -231,7 +230,7 @@ class TestLoadServerConfig:
@pytest.mark.usefixtures("_default_typed_setting")
@pytest.mark.parametrize(
- "value", ["disabled", "nein", "flase", "MAYBE", "2"]
+ "value", ["disabled", "nein", "flase", "MAYBE", "2", " "]
)
def test_unrecognized_allow_registrations_defaults_to_false(
self, value, monkeypatch
@@ -261,7 +260,7 @@ class TestLoadServerConfig:
@pytest.mark.usefixtures("_default_typed_setting")
def test_allow_registrations_env_not_set_uses_default(self, monkeypatch):
- """When env var is not set, allow_registrations should use saved/default value."""
+ """When env var is not set, allow_registrations should use default value."""
monkeypatch.delenv("LDR_APP_ALLOW_REGISTRATIONS", raising=False)
result = load_server_config()
@@ -269,213 +268,293 @@ class TestLoadServerConfig:
# Default is True
assert result["allow_registrations"] is True
- @pytest.mark.usefixtures("_passthrough_typed_setting")
- def test_allow_registrations_env_not_set_uses_saved_value(
- self, tmp_path, monkeypatch
+ @pytest.mark.usefixtures("_default_typed_setting")
+ def test_empty_string_allow_registrations_fails_closed(self, monkeypatch):
+ """Empty-string env var should trigger fail-closed (registrations=False)."""
+ monkeypatch.setenv("LDR_APP_ALLOW_REGISTRATIONS", "")
+
+ with patch(
+ "local_deep_research.web.server_config.logger"
+ ) as mock_logger:
+ result = load_server_config()
+
+ assert result["allow_registrations"] is False
+ warning_calls = [str(c) for c in mock_logger.warning.call_args_list]
+ assert any("recognized" in call for call in warning_calls), (
+ f"Expected fail-closed warning for empty string, got: {warning_calls}"
+ )
+
+
+# ===================================================================
+# Fixtures for legacy migration tests
+# ===================================================================
[email protected](autouse=True)
+def _mock_data_dir(tmp_path):
+ """Point get_data_dir to a temp directory for all tests in this module."""
+ with patch(
+ "local_deep_research.web.server_config.get_data_dir",
+ return_value=str(tmp_path),
):
- """When env var is not set and config file has a saved value, uses saved value."""
- monkeypatch.delenv("LDR_APP_ALLOW_REGISTRATIONS", raising=False)
+ yield tmp_path
- config_file = tmp_path / "server_config.json"
- config_file.write_text(json.dumps({"allow_registrations": False}))
- result = load_server_config()
[email protected](autouse=True)
+def _clean_allow_registrations_env(monkeypatch):
+ """Ensure LDR_APP_ALLOW_REGISTRATIONS is not set from the developer's shell.
+
+ The fail-closed logic reads this env var directly via os.getenv(),
+ bypassing mocks. If a developer has it set, tests could fail unexpectedly.
+ """
+ monkeypatch.delenv("LDR_APP_ALLOW_REGISTRATIONS", raising=False)
- assert result["allow_registrations"] is False
+
+def _passthrough_typed_setting():
+ """Mock get_typed_setting_value: returns val if not None, else default.
+
+ This simulates the priority logic without env var checks, so we can
+ verify that legacy file values are passed through correctly.
+ """
+ with patch(
+ "local_deep_research.web.server_config.get_typed_setting_value",
+ side_effect=lambda key, val, typ, default: val
+ if val is not None
+ else default,
+ ):
+ yield
# ===================================================================
-# save_server_config
+# get_server_config_path
# ===================================================================
-class TestSaveServerConfig:
- """Tests for save_server_config function."""
+class TestGetServerConfigPath:
+ """Tests for get_server_config_path function."""
- def test_saves_config_to_file(self, tmp_path):
- """Should save config as JSON to config path."""
- config = {"host": "localhost", "port": 3000}
- save_server_config(config)
+ def test_returns_path_object(self):
+ assert isinstance(get_server_config_path(), Path)
- config_file = tmp_path / "server_config.json"
- assert config_file.exists()
- saved_data = json.loads(config_file.read_text())
- assert saved_data["host"] == "localhost"
- assert saved_data["port"] == 3000
+ def test_filename_is_server_config_json(self):
+ assert get_server_config_path().name == "server_config.json"
- def test_creates_parent_directory(self, tmp_path):
- """Should create parent directory if it doesn't exist."""
- nested_path = tmp_path / "nested" / "dir"
+ def test_path_is_under_data_dir(self, _mock_data_dir):
+ assert get_server_config_path().parent == _mock_data_dir
- with patch(
- "local_deep_research.web.server_config.get_data_dir",
- return_value=str(nested_path),
- ):
- save_server_config({"host": "localhost"})
- config_file = nested_path / "server_config.json"
- assert config_file.exists()
+# ===================================================================
+# Legacy migration — _load_legacy_config via load_server_config
+# ===================================================================
+class TestLegacyMigration:
+ """Tests for legacy server_config.json migration path."""
+
+ def _write_legacy(self, tmp_path, data):
+ """Write a legacy server_config.json file."""
+ (tmp_path / "server_config.json").write_text(
+ json.dumps(data), encoding="utf-8"
+ )
@pytest.mark.usefixtures("_passthrough_typed_setting")
- def test_saved_config_can_be_loaded_back(self, tmp_path):
- """Saved config should be loadable via load_server_config."""
- config = {
- "host": "10.0.0.1",
- "port": 9999,
- "debug": True,
- "use_https": False,
- "allow_registrations": False,
- "rate_limit_default": "100 per hour",
- "rate_limit_login": "10 per minute",
- "rate_limit_registration": "1 per hour",
- }
- save_server_config(config)
+ def test_legacy_allow_registrations_false_honored(self, _mock_data_dir):
+ """Security-critical: allow_registrations=false from legacy file must be honored."""
+ self._write_legacy(_mock_data_dir, {"allow_registrations": False})
+ result = load_server_config()
+ assert result["allow_registrations"] is False
+
+ @pytest.mark.usefixtures("_passthrough_typed_setting")
+ def test_env_var_overrides_legacy_value(self, _mock_data_dir):
+ """Env var should take priority over legacy file value.
- loaded = load_server_config()
+ We use _env_typed_setting-style mock to simulate env override.
+ """
+ self._write_legacy(_mock_data_dir, {"port": 9999})
- assert loaded["host"] == "10.0.0.1"
- assert loaded["port"] == 9999
- assert loaded["debug"] is True
- assert loaded["use_https"] is False
+ # Simulate env var override: get_typed_setting_value returns env value
+ def _side_effect(key, val, typ, default):
+ if key == "web.port":
+ return 8080 # env var wins
+ return val if val is not None else default
- def test_handles_write_errors_gracefully(self, tmp_path):
- """Should not raise on write errors, but log exception."""
with patch(
- "builtins.open", side_effect=PermissionError("No write access")
+ "local_deep_research.web.server_config.get_typed_setting_value",
+ side_effect=_side_effect,
):
- with patch(
- "local_deep_research.web.server_config.logger"
- ) as mock_logger:
- # Should not raise
- save_server_config({"host": "localhost"})
+ result = load_server_config()
- mock_logger.exception.assert_called_once()
-
- def test_formats_json_with_indent(self, tmp_path):
- """Should format JSON with indentation for readability."""
- save_server_config({"host": "localhost", "port": 3000})
+ assert result["port"] == 8080
- config_file = tmp_path / "server_config.json"
- content = config_file.read_text()
- # Indented JSON has newlines
- assert "\n" in content
+ @pytest.mark.usefixtures("_passthrough_typed_setting")
+ def test_no_legacy_file_returns_defaults(self):
+ """Without a legacy file, defaults should be returned."""
+ result = load_server_config()
+ assert result["host"] == "0.0.0.0"
+ assert result["port"] == 5000
+ assert result["allow_registrations"] is True
- def test_logs_success(self, tmp_path):
- """Should log a success message after saving."""
+ @pytest.mark.usefixtures("_passthrough_typed_setting")
+ def test_corrupt_json_falls_back_to_defaults(self, _mock_data_dir):
+ """Corrupt JSON should log a warning and return defaults."""
+ (_mock_data_dir / "server_config.json").write_text(
+ "not valid json{{{", encoding="utf-8"
+ )
with patch(
"local_deep_research.web.server_config.logger"
) as mock_logger:
- save_server_config({"host": "localhost"})
+ result = load_server_config()
- mock_logger.info.assert_called_once()
- call_args = mock_logger.info.call_args[0][0]
- assert "saved" in call_args.lower()
+ assert result["host"] == "0.0.0.0"
+ assert result["allow_registrations"] is True
+ warning_calls = [str(c) for c in mock_logger.warning.call_args_list]
+ assert any("Could not read" in call for call in warning_calls)
+ @pytest.mark.usefixtures("_passthrough_typed_setting")
+ def test_non_dict_json_falls_back_to_defaults(self, _mock_data_dir):
+ """Non-dict JSON (e.g. array) should log a warning and return defaults."""
+ self._write_legacy(_mock_data_dir, [1, 2, 3])
+ with patch(
+ "local_deep_research.web.server_config.logger"
+ ) as mock_logger:
+ result = load_server_config()
-# ===================================================================
-# sync_from_settings
-# ===================================================================
-class TestSyncFromSettings:
- """Tests for sync_from_settings function."""
+ assert result["host"] == "0.0.0.0"
+ warning_calls = [str(c) for c in mock_logger.warning.call_args_list]
+ assert any("does not contain" in call for call in warning_calls)
@pytest.mark.usefixtures("_passthrough_typed_setting")
- def test_updates_host_from_snapshot(self, tmp_path):
- """Should update host from settings snapshot."""
- sync_from_settings({"web.host": "192.168.1.1"})
-
- config_file = tmp_path / "server_config.json"
- saved_data = json.loads(config_file.read_text())
- assert saved_data["host"] == "192.168.1.1"
+ def test_partial_legacy_file(self, _mock_data_dir):
+ """Partial legacy file: port from file, rest defaults."""
+ self._write_legacy(_mock_data_dir, {"port": 8080})
+ result = load_server_config()
+ assert result["port"] == 8080
+ assert result["host"] == "0.0.0.0"
+ assert result["allow_registrations"] is True
@pytest.mark.usefixtures("_passthrough_typed_setting")
- def test_updates_port_from_snapshot(self, tmp_path):
- """Should update port from settings snapshot."""
- sync_from_settings({"web.port": 9000})
+ def test_security_warning_logged_for_allow_registrations(
+ self, _mock_data_dir
+ ):
+ """Security warning with 'SECURITY' should be logged for allow_registrations."""
+ self._write_legacy(_mock_data_dir, {"allow_registrations": False})
+ with patch(
+ "local_deep_research.web.server_config.logger"
+ ) as mock_logger:
+ load_server_config()
- config_file = tmp_path / "server_config.json"
- saved_data = json.loads(config_file.read_text())
- assert saved_data["port"] == 9000
+ warning_calls = [str(c) for c in mock_logger.warning.call_args_list]
+ assert any("SECURITY" in call for call in warning_calls)
@pytest.mark.usefixtures("_passthrough_typed_setting")
- def test_updates_multiple_settings_at_once(self, tmp_path):
- """Should update all supported settings in a single call."""
- settings = {
- "web.host": "10.0.0.1",
- "web.port": 4000,
- "app.debug": True,
- "web.use_https": False,
- "app.allow_registrations": False,
- "security.rate_limit_default": "100 per hour",
- "security.rate_limit_login": "10 per minute",
- "security.rate_limit_registration": "1 per hour",
- }
- sync_from_settings(settings)
-
- config_file = tmp_path / "server_config.json"
- saved_data = json.loads(config_file.read_text())
+ def test_info_logged_for_non_security_settings(self, _mock_data_dir):
+ """Non-security settings should log at info level, not warning."""
+ self._write_legacy(_mock_data_dir, {"host": "127.0.0.1"})
+ with patch(
+ "local_deep_research.web.server_config.logger"
+ ) as mock_logger:
+ load_server_config()
- assert saved_data["host"] == "10.0.0.1"
- assert saved_data["port"] == 4000
- assert saved_data["debug"] is True
- assert saved_data["use_https"] is False
- assert saved_data["allow_registrations"] is False
- assert saved_data["rate_limit_default"] == "100 per hour"
- assert saved_data["rate_limit_login"] == "10 per minute"
- assert saved_data["rate_limit_registration"] == "1 per hour"
+ info_calls = [str(c) for c in mock_logger.info.call_args_list]
+ assert any("host" in call for call in info_calls)
@pytest.mark.usefixtures("_passthrough_typed_setting")
- def test_ignores_keys_not_in_snapshot(self, tmp_path):
- """Settings not present in snapshot should not appear as extra keys."""
- sync_from_settings(
- {
- "web.host": "localhost",
- "unknown.setting": "should be ignored",
- }
+ def test_unrecognized_keys_logged_as_warning(self, _mock_data_dir):
+ """Unrecognized keys in legacy file produce a warning listing them."""
+ self._write_legacy(
+ _mock_data_dir, {"unknown_key": "value", "another": 42}
)
+ with patch(
+ "local_deep_research.web.server_config.logger"
+ ) as mock_logger:
+ result = load_server_config()
+
+ warning_calls = [str(c) for c in mock_logger.warning.call_args_list]
+ # Should warn about unrecognized keys
+ assert any("unrecognized" in call.lower() for call in warning_calls)
+ # No DEPRECATED summary warning since no recognized keys
+ assert not any("DEPRECATED" in call for call in warning_calls)
+ # Defaults returned
+ assert result["host"] == "0.0.0.0"
- config_file = tmp_path / "server_config.json"
- saved_data = json.loads(config_file.read_text())
+ @pytest.mark.usefixtures("_passthrough_typed_setting")
+ def test_empty_dict_no_warnings(self, _mock_data_dir):
+ """Empty dict {} should produce no warnings and return defaults."""
+ self._write_legacy(_mock_data_dir, {})
+ with patch(
+ "local_deep_research.web.server_config.logger"
+ ) as mock_logger:
+ result = load_server_config()
- assert saved_data["host"] == "localhost"
- assert "unknown.setting" not in saved_data
- assert "unknown" not in saved_data
+ assert result["host"] == "0.0.0.0"
+ assert result["allow_registrations"] is True
+ warning_calls = [str(c) for c in mock_logger.warning.call_args_list]
+ assert not any("DEPRECATED" in call for call in warning_calls)
@pytest.mark.usefixtures("_passthrough_typed_setting")
- def test_saves_the_merged_config(self, tmp_path):
- """sync_from_settings should persist the merged config to disk."""
- sync_from_settings({"web.host": "saved-host"})
+ def test_deprecated_banner_logged_for_recognized_keys(self, _mock_data_dir):
+ """DEPRECATED banner should be logged when recognized keys are present."""
+ self._write_legacy(_mock_data_dir, {"port": 8080})
+ with patch(
+ "local_deep_research.web.server_config.logger"
+ ) as mock_logger:
+ load_server_config()
+ warning_calls = [str(c) for c in mock_logger.warning.call_args_list]
+ assert any("DEPRECATED" in call for call in warning_calls)
- config_file = tmp_path / "server_config.json"
- assert config_file.exists()
- saved_data = json.loads(config_file.read_text())
- assert saved_data["host"] == "saved-host"
- @pytest.mark.usefixtures("_passthrough_typed_setting")
- def test_preserves_existing_values(self, tmp_path):
- """Values not in the snapshot should be preserved from the existing config."""
- # Create initial config
- config_file = tmp_path / "server_config.json"
- initial_config = {
- "host": "original-host",
- "port": 1234,
- "debug": False,
- "use_https": True,
- }
- config_file.write_text(json.dumps(initial_config))
+class TestLegacyAllowRegistrationsFailClosed:
+ """Fail-closed for legacy JSON allow_registrations string values.
- # Only update host
- sync_from_settings({"web.host": "new-host"})
+ The guard fires when the legacy JSON has an unrecognized string for
+ allow_registrations and no env var overrides it.
+ """
- saved_data = json.loads(config_file.read_text())
+ @staticmethod
+ def _write_legacy(tmp_path, data):
+ (tmp_path / "server_config.json").write_text(
+ json.dumps(data), encoding="utf-8"
+ )
- assert saved_data["host"] == "new-host"
- assert saved_data["port"] == 1234 # Preserved
- assert saved_data["debug"] is False # Preserved
- assert saved_data["use_https"] is True # Preserved
+ @pytest.mark.usefixtures("_passthrough_typed_setting")
+ def test_unrecognized_string_defaults_to_false(self, _mock_data_dir):
+ """Legacy JSON 'allow_registrations': 'disabled' should fail closed."""
+ self._write_legacy(_mock_data_dir, {"allow_registrations": "disabled"})
+ result = load_server_config()
+ assert result["allow_registrations"] is False
- @pytest.mark.usefixtures("_default_typed_setting")
- def test_empty_settings_snapshot(self, tmp_path):
- """Should handle empty settings snapshot without error."""
- # Should not raise
- sync_from_settings({})
+ @pytest.mark.usefixtures("_passthrough_typed_setting")
+ def test_recognized_string_not_overridden(self, _mock_data_dir):
+ """Recognized boolean strings ('true', 'false', etc.) should not trigger the guard."""
+ for value in ("true", "false", "yes", "no", "1", "0", "on", "off"):
+ self._write_legacy(_mock_data_dir, {"allow_registrations": value})
+ result = load_server_config()
+ # Guard should NOT override to False for recognized values
+ assert result["allow_registrations"] != False or value in ( # noqa: E712
+ "false",
+ "no",
+ "0",
+ "off",
+ ), f"Guard incorrectly triggered for recognized value '{value}'"
- config_file = tmp_path / "server_config.json"
- assert config_file.exists()
+ @pytest.mark.usefixtures("_passthrough_typed_setting")
+ def test_native_bool_not_affected(self, _mock_data_dir):
+ """Native JSON bool should not trigger the string guard."""
+ self._write_legacy(_mock_data_dir, {"allow_registrations": False})
+ result = load_server_config()
+ assert result["allow_registrations"] is False
+
+ @pytest.mark.usefixtures("_passthrough_typed_setting")
+ def test_env_var_guard_takes_priority_over_legacy_guard(
+ self, _mock_data_dir, monkeypatch
+ ):
+ """When both env var and legacy JSON have bad values, the env var guard fires."""
+ self._write_legacy(_mock_data_dir, {"allow_registrations": "disabled"})
+ monkeypatch.setenv("LDR_APP_ALLOW_REGISTRATIONS", "nein")
+ with patch(
+ "local_deep_research.web.server_config.logger"
+ ) as mock_logger:
+ result = load_server_config()
+ assert result["allow_registrations"] is False
+ warning_calls = [str(c) for c in mock_logger.warning.call_args_list]
+ assert any(
+ "LDR_APP_ALLOW_REGISTRATIONS" in call for call in warning_calls
+ )
+ assert not any(
+ "Legacy server_config.json" in call for call in warning_calls
+ )
diff --git a/tests/web/warning_checks/test_hardware.py b/tests/web/warning_checks/test_hardware.py
index dcc9821354..cd7f0dff76 100644
--- a/tests/web/warning_checks/test_hardware.py
+++ b/tests/web/warning_checks/test_hardware.py
@@ -1,8 +1,11 @@
"""Pure-function tests for hardware warning checks — zero mocking needed."""
+from unittest.mock import patch
+
from local_deep_research.web.warning_checks.hardware import (
LOCAL_PROVIDERS,
check_high_context,
+ check_legacy_server_config,
check_model_mismatch,
)
@@ -163,3 +166,43 @@ class TestCheckModelMismatch:
"ollama", "llama3.1:70b", 16384, dismissed=False
)
assert result["dismissKey"] == "app.warnings.dismiss_model_mismatch"
+
+
+class TestCheckLegacyServerConfig:
+ """Tests for check_legacy_server_config."""
+
+ def test_no_warning_when_dismissed(self, tmp_path):
+ config_file = tmp_path / "server_config.json"
+ config_file.write_text("{}", encoding="utf-8")
+ with patch(
+ "local_deep_research.web.server_config.get_server_config_path",
+ return_value=config_file,
+ ):
+ assert check_legacy_server_config(dismissed=True) is None
+
+ def test_no_warning_when_file_missing(self, tmp_path):
+ config_file = tmp_path / "server_config.json"
+ with patch(
+ "local_deep_research.web.server_config.get_server_config_path",
+ return_value=config_file,
+ ):
+ assert check_legacy_server_config(dismissed=False) is None
+
+ def test_warns_when_file_exists(self, tmp_path):
+ config_file = tmp_path / "server_config.json"
+ config_file.write_text("{}", encoding="utf-8")
+ with patch(
+ "local_deep_research.web.server_config.get_server_config_path",
+ return_value=config_file,
+ ):
+ result = check_legacy_server_config(dismissed=False)
+ assert result is not None
+ assert result["type"] == "legacy_server_config"
+ assert result["dismissKey"] == "app.warnings.dismiss_legacy_config"
+ assert set(result.keys()) == {
+ "type",
+ "icon",
+ "title",
+ "message",
+ "dismissKey",
+ }
diff --git a/tests/web/warning_checks/test_orchestrator.py b/tests/web/warning_checks/test_orchestrator.py
index baaf2dbd59..ead4e4986e 100644
--- a/tests/web/warning_checks/test_orchestrator.py
+++ b/tests/web/warning_checks/test_orchestrator.py
@@ -16,6 +16,7 @@ def _make_settings_manager(overrides=None):
"app.warnings.dismiss_high_context": False,
"app.warnings.dismiss_model_mismatch": False,
"app.warnings.dismiss_context_reduced": False,
+ "app.warnings.dismiss_legacy_config": False,
}
if overrides:
defaults.update(overrides)
@@ -250,7 +251,7 @@ class TestCalculateWarningsMultipleWarnings:
assert "context_below_history" in types
assert "context_truncation_history" in types
- def test_all_four_warnings_simultaneously(self):
+ def test_all_hardware_and_context_warnings_simultaneously(self):
from local_deep_research.web.warning_checks import calculate_warnings
mock_db_session = Mock()
@@ -273,7 +274,11 @@ class TestCalculateWarningsMultipleWarnings:
}
)
with _patch_orchestrator(mgr, db_session=mock_db_session):
- warnings = calculate_warnings()
+ with patch(
+ "local_deep_research.web.server_config.get_server_config_path",
+ return_value=Mock(exists=Mock(return_value=False)),
+ ):
+ warnings = calculate_warnings()
types = {w["type"] for w in warnings}
assert types == {
@@ -361,8 +366,8 @@ class TestCalculateWarningsSingleSession:
mock_get_sm.assert_called_once_with(mock_db, "bob")
- def test_all_six_settings_read(self):
- """All 6 required settings are read from the manager."""
+ def test_all_seven_settings_read(self):
+ """All 7 required settings are read from the manager."""
from local_deep_research.web.warning_checks import calculate_warnings
mgr = _make_settings_manager()
@@ -377,6 +382,58 @@ class TestCalculateWarningsSingleSession:
assert "app.warnings.dismiss_high_context" in called_keys
assert "app.warnings.dismiss_model_mismatch" in called_keys
assert "app.warnings.dismiss_context_reduced" in called_keys
+ assert "app.warnings.dismiss_legacy_config" in called_keys
+
+
+class TestCalculateWarningsLegacyServerConfig:
+ """Orchestrator coverage for the legacy_server_config check."""
+
+ def test_legacy_server_config_warning_when_file_exists(self):
+ """If server_config.json exists on disk, warning appears in output."""
+ from local_deep_research.web.warning_checks import calculate_warnings
+
+ mgr = _make_settings_manager()
+ with _patch_orchestrator(mgr):
+ with patch(
+ "local_deep_research.web.server_config.get_server_config_path",
+ return_value=Mock(exists=Mock(return_value=True)),
+ ):
+ warnings = calculate_warnings()
+
+ types = {w["type"] for w in warnings}
+ assert "legacy_server_config" in types
+
+ def test_no_legacy_server_config_warning_when_file_absent(self):
+ """If server_config.json does not exist, no warning."""
+ from local_deep_research.web.warning_checks import calculate_warnings
+
+ mgr = _make_settings_manager()
+ with _patch_orchestrator(mgr):
+ with patch(
+ "local_deep_research.web.server_config.get_server_config_path",
+ return_value=Mock(exists=Mock(return_value=False)),
+ ):
+ warnings = calculate_warnings()
+
+ types = {w["type"] for w in warnings}
+ assert "legacy_server_config" not in types
+
+ def test_no_legacy_server_config_warning_when_dismissed(self):
+ """If dismissed, no warning even when file exists."""
+ from local_deep_research.web.warning_checks import calculate_warnings
+
+ mgr = _make_settings_manager(
+ {"app.warnings.dismiss_legacy_config": True}
+ )
+ with _patch_orchestrator(mgr):
+ with patch(
+ "local_deep_research.web.server_config.get_server_config_path",
+ return_value=Mock(exists=Mock(return_value=True)),
+ ):
+ warnings = calculate_warnings()
+
+ types = {w["type"] for w in warnings}
+ assert "legacy_server_config" not in types
class TestCalculateWarningsFailureIsolation: