~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(settings): remove unused bootstrap configuration (#6937)
LearningCircuit47a04ae7abcf
diff --git a/changelog.d/+remove-unused-bootstrap-settings.bugfix.md b/changelog.d/+remove-unused-bootstrap-settings.bugfix.mdnew file mode 100644index 0000000000..dde861d341--- /dev/null+++ b/changelog.d/+remove-unused-bootstrap-settings.bugfix.md@@ -0,0 +1 @@+Remove seven unused bootstrap environment settings from the registry and generated configuration reference, and make `/settings/api/data-location` report `is_custom` and `custom_env_value` from `LDR_DATA_DIR`, the variable that actually moves the data directory. Document the existing data-directory, file-logging and key-storage behavior so operators are not directed to ineffective configuration variables.diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.mdindex 0d9b80224d..466b87c236 100644--- a/docs/CONFIGURATION.md+++ b/docs/CONFIGURATION.md@@ -21,13 +21,6 @@ They are not available in the Web UI because they are needed to start the applic| Environment Variable | Type | Default | Required | Constraints | Description | Category | Deprecated Alias ||----------------------|------|---------|----------|-------------|-------------|----------|------------------|| `LDR_BOOTSTRAP_ALLOW_UNENCRYPTED` | Boolean | `False` | No | | Allow plaintext SQLite for isolated local development when SQLCipher is unavailable or nonfunctional. Working SQLCipher still takes priority; the fallback does not verify account passwords. | Bootstrap | LDR_ALLOW_UNENCRYPTED |-| `LDR_BOOTSTRAP_CONFIG_DIR` | Path | `None` | No | | Configuration directory path | Bootstrap | |-| `LDR_BOOTSTRAP_DATABASE_URL` | String | `None` | No | | Database connection URL | Bootstrap | |-| `LDR_BOOTSTRAP_DATA_DIR` | Path | `None` | No | | Data directory path | Bootstrap | |-| `LDR_BOOTSTRAP_ENABLE_FILE_LOGGING` | Boolean | `False` | No | | Enable logging to file | Bootstrap | |-| `LDR_BOOTSTRAP_ENCRYPTION_KEY` | Secret | `None` | No | | Database encryption key | Bootstrap | |-| `LDR_BOOTSTRAP_LOG_DIR` | Path | `None` | No | | Log directory path | Bootstrap | |-| `LDR_BOOTSTRAP_SECRET_KEY` | Secret | `None` | No | | Application secret key for session encryption | Bootstrap | || `LDR_DB_CONFIG_BUSY_TIMEOUT_MS` | Integer | `30000` | No | 100..300000 | SQLite busy_timeout in milliseconds -- how long a writer waits for the database lock before giving up with 'database is locked'. Set above the p99 latency of in-flight transactions (the background document scheduler can hold a session across multi-second PDF downloads; 30s gives the rate-limit tracker and other short writers enough headroom to land their commit instead of swallowing the error). | Db Config | LDR_DB_BUSY_TIMEOUT_MS || `LDR_DB_CONFIG_CACHE_SIZE_MB` | Integer | `64` | No | 1..10000 | SQLite cache size in MB | Db Config | LDR_DB_CACHE_SIZE_MB || `LDR_DB_CONFIG_CIPHER_MEMORY_SECURITY` | Enum | `'OFF'` | No | OFF, ON | SQLCipher memory security (ON=clear memory after use + mlock, OFF=faster). ON requires IPC_LOCK in Docker. | Db Config | |diff --git a/docs/env_configuration.md b/docs/env_configuration.mdindex 1b0c9dbe19..c4ec8a6de2 100644--- a/docs/env_configuration.md+++ b/docs/env_configuration.md@@ -259,6 +259,20 @@ All application data will be organized under this directory:- `$LDR_DATA_DIR/cache/` - Cached data- `$LDR_DATA_DIR/logs/` - Application logs+### Removed Bootstrap Variables++The following variables were previously listed in the configuration reference but did not change the behavior they described. They have been removed from the environment-setting registry:++- `LDR_BOOTSTRAP_ENCRYPTION_KEY`+- `LDR_BOOTSTRAP_SECRET_KEY`+- `LDR_BOOTSTRAP_DATABASE_URL`+- `LDR_BOOTSTRAP_DATA_DIR`+- `LDR_BOOTSTRAP_CONFIG_DIR`+- `LDR_BOOTSTRAP_LOG_DIR`+- `LDR_BOOTSTRAP_ENABLE_FILE_LOGGING`++User databases use password-derived encryption keys. The session-signing key is persisted in `.secret_key` inside the data directory. Use `LDR_DATA_DIR` to choose that directory and `LDR_ENABLE_FILE_LOGGING=true` to enable file logging (only the word `true`, in any letter case, enables it; `1` and `yes` do not). These existing mechanisms are unchanged.+### Debug Logging (`LDR_APP_DEBUG` and `LDR_LOGURU_DIAGNOSE`)`LDR_APP_DEBUG=true` raises the log level to `DEBUG` for more informative output. It does **not**, on its own, enable Loguru's `diagnose` mode, which renders the `repr()` of every local variable in every traceback frame on exceptions and can materialise credentials (API keys, the SQLCipher master password, `Authorization` headers) into your logs.diff --git a/src/local_deep_research/config/paths.py b/src/local_deep_research/config/paths.pyindex 939736a1af..db6e008a6e 100644--- a/src/local_deep_research/config/paths.py+++ b/src/local_deep_research/config/paths.py@@ -63,6 +63,25 @@ def get_data_directory() -> Path:return data_dir+def get_custom_data_directory() -> Path | None:+ """+ Get the data directory that ``LDR_DATA_DIR`` selects, if it is set.++ ``None`` means ``LDR_DATA_DIR`` is unset or empty, so+ :func:`get_data_directory` uses the platform default. Otherwise the result+ is exactly what :func:`get_data_directory` returns, including its+ validation errors. ``LDR_DATA_DIR`` is the only environment variable that+ moves the data directory, so this is what a status report should show+ when it says the location is custom.++ Returns:+ Path selected by ``LDR_DATA_DIR``, or ``None`` for the platform default+ """+ if not os.getenv("LDR_DATA_DIR"):+ return None+ return get_data_directory()++def _ensure_dir(subdir: str, label: str | None = None, mode: int | None = None) -> Path:diff --git a/src/local_deep_research/settings/env_definitions/bootstrap.py b/src/local_deep_research/settings/env_definitions/bootstrap.pyindex df07c8bb73..a0f5d96a0d 100644--- a/src/local_deep_research/settings/env_definitions/bootstrap.py+++ b/src/local_deep_research/settings/env_definitions/bootstrap.py@@ -1,35 +1,9 @@-"""-Bootstrap environment settings.+"""Bootstrap settings read before database initialization."""-These settings are required early in the application lifecycle,-before database initialization and other core systems.-"""+from ..env_settings import BooleanSetting-from ..env_settings import (- BooleanSetting,- StringSetting,- PathSetting,- SecretSetting,-)--# Bootstrap settings required before DB initBOOTSTRAP_SETTINGS = [- # Security and encryption- SecretSetting(- key="bootstrap.encryption_key",- description="Database encryption key",- required=False, # Not required if allow_unencrypted is True- ),- SecretSetting(- key="bootstrap.secret_key",- description="Application secret key for session encryption",- ),- # Database- StringSetting(- key="bootstrap.database_url",- description="Database connection URL",- ),BooleanSetting(key="bootstrap.allow_unencrypted",description=(@@ -40,26 +14,4 @@ BOOTSTRAP_SETTINGS = [default=False,deprecated_env_var="LDR_ALLOW_UNENCRYPTED",),- # System paths- PathSetting(- key="bootstrap.data_dir",- description="Data directory path",- create_if_missing=True,- ),- PathSetting(- key="bootstrap.config_dir",- description="Configuration directory path",- create_if_missing=True,- ),- PathSetting(- key="bootstrap.log_dir",- description="Log directory path",- create_if_missing=True,- ),- # Logging- BooleanSetting(- key="bootstrap.enable_file_logging",- description="Enable logging to file",- default=False,- ),]diff --git a/src/local_deep_research/settings/env_settings.py b/src/local_deep_research/settings/env_settings.pyindex a4aa6c397c..f4dec440cb 100644--- a/src/local_deep_research/settings/env_settings.py+++ b/src/local_deep_research/settings/env_settings.py@@ -9,7 +9,7 @@ These settings are:They are accessed through SettingsManager but always read from environment variables.Why some settings must be environment-only:-- Bootstrap settings (paths, encryption keys) are needed to initialize the database itself+- Bootstrap settings (the plaintext-SQLite fallback policy) are needed to initialize the database itself- Database configuration settings must be available before connecting to the database- Testing flags need to be checked before any database operations occur- CI/CD variables control build-time behavior before the application startsdiff --git a/src/local_deep_research/web/routers/settings.py b/src/local_deep_research/web/routers/settings.pyindex 83f24439ac..a464c6033e 100644--- a/src/local_deep_research/web/routers/settings.py+++ b/src/local_deep_research/web/routers/settings.py@@ -69,7 +69,11 @@ from loguru import loggerfrom sqlalchemy.orm import Sessionfrom ...config.constants import DEFAULT_OLLAMA_URL-from ...config.paths import get_data_directory, get_encrypted_database_path+from ...config.paths import (+ get_custom_data_directory,+ get_data_directory,+ get_encrypted_database_path,+)from ...constants import DEFAULT_SEARCH_TOOLfrom ...database.models.rate_limiting import RateLimitEstimatefrom ...database.models.settings import Setting, SettingType@@ -4471,11 +4475,9 @@ def api_get_data_location(# Get the encrypted databases pathencrypted_db_path = get_encrypted_database_path()- # Check if LDR_DATA_DIR environment variable is set- from local_deep_research.settings.manager import SettingsManager-- settings_manager = SettingsManager()- custom_data_dir = settings_manager.get_setting("bootstrap.data_dir")+ # LDR_DATA_DIR is the only variable that moves the data directory, so+ # it alone decides whether the location is custom.+ custom_data_dir = get_custom_data_directory()# Get platform-specific default location infoplatform_info = {@@ -4508,7 +4510,9 @@ def api_get_data_location("encrypted_database_path": str(encrypted_db_path),"is_custom": custom_data_dir is not None,"custom_env_var": "LDR_DATA_DIR",- "custom_env_value": custom_data_dir,+ "custom_env_value": (+ str(custom_data_dir) if custom_data_dir is not None else None+ ),"platform": current_platform,"platform_default": platform_info.get(current_platform, str(data_dir)diff --git a/tests/config/test_bootstrap_high_value.py b/tests/config/test_bootstrap_high_value.pyindex 1230ab0105..0ed2a02d8f 100644--- a/tests/config/test_bootstrap_high_value.py+++ b/tests/config/test_bootstrap_high_value.py@@ -1,19 +1,13 @@"""High-value tests for settings/env_definitions/bootstrap.py.-Tests the BOOTSTRAP_SETTINGS list: SecretSetting, StringSetting,-BooleanSetting, PathSetting instances, their keys, defaults, and types.+Tests the supported bootstrap encryption policy setting."""-import pytest-from local_deep_research.settings.env_definitions.bootstrap import (BOOTSTRAP_SETTINGS,)from local_deep_research.settings.env_settings import (BooleanSetting,- StringSetting,- PathSetting,- SecretSetting,SettingsRegistry,)@@ -31,7 +25,7 @@ class TestBootstrapRegistry:def test_setting_count(self):"""BOOTSTRAP_SETTINGS has the expected number of entries."""- assert len(BOOTSTRAP_SETTINGS) == 8+ assert len(BOOTSTRAP_SETTINGS) == 1def test_all_keys_start_with_bootstrap(self):"""Every key uses the 'bootstrap.' prefix."""@@ -46,35 +40,6 @@ class TestBootstrapRegistry:assert registry.is_env_only(s.key)-class TestEncryptionKey:- """Tests for bootstrap.encryption_key."""-- def test_is_secret_setting(self):- s = _find("bootstrap.encryption_key")- assert isinstance(s, SecretSetting)-- def test_not_required(self):- """encryption_key is not required (allow_unencrypted may be True)."""- s = _find("bootstrap.encryption_key")- assert s.required is False---class TestSecretKey:- """Tests for bootstrap.secret_key."""-- def test_is_secret_setting(self):- s = _find("bootstrap.secret_key")- assert isinstance(s, SecretSetting)---class TestDatabaseUrl:- """Tests for bootstrap.database_url."""-- def test_is_string_setting(self):- s = _find("bootstrap.database_url")- assert isinstance(s, StringSetting)--class TestAllowUnencrypted:"""Tests for bootstrap.allow_unencrypted."""@@ -106,52 +71,3 @@ class TestAllowUnencrypted:s = _find("bootstrap.allow_unencrypted")monkeypatch.setenv(s.env_var, "false")assert s.get_value() is False---class TestPathSettings:- """Tests for bootstrap path settings."""-- @pytest.mark.parametrize(- "key",- [- "bootstrap.data_dir",- "bootstrap.config_dir",- "bootstrap.log_dir",- ],- )- def test_is_path_setting(self, key):- s = _find(key)- assert isinstance(s, PathSetting)-- @pytest.mark.parametrize(- "key",- [- "bootstrap.data_dir",- "bootstrap.config_dir",- "bootstrap.log_dir",- ],- )- def test_create_if_missing_is_true(self, key):- """Path settings should create directories if missing."""- s = _find(key)- assert s.create_if_missing is True---class TestEnableFileLogging:- """Tests for bootstrap.enable_file_logging."""-- def test_is_boolean_setting(self):- s = _find("bootstrap.enable_file_logging")- assert isinstance(s, BooleanSetting)-- def test_default_is_false(self, monkeypatch):- """Default value is False."""- s = _find("bootstrap.enable_file_logging")- monkeypatch.delenv(s.env_var, raising=False)- assert s.get_value() is False-- def test_set_to_true(self, monkeypatch):- """Can be enabled via env var."""- s = _find("bootstrap.enable_file_logging")- monkeypatch.setenv(s.env_var, "true")- assert s.get_value() is Truediff --git a/tests/config/test_paths_behavior.py b/tests/config/test_paths_behavior.pyindex 21621e63b4..11d3d271c9 100644--- a/tests/config/test_paths_behavior.py+++ b/tests/config/test_paths_behavior.py@@ -7,6 +7,8 @@ and structural invariants (all subdirs under data dir).import re+import pytest+class TestDataDirectoryEnvOverride:"""Tests for LDR_DATA_DIR environment variable handling."""@@ -37,6 +39,56 @@ class TestDataDirectoryEnvOverride:result = get_data_directory()assert "local-deep-research" in str(result)+ def test_custom_data_directory_is_the_env_override(+ self, tmp_path, monkeypatch+ ):+ """With LDR_DATA_DIR set, the custom directory is the data directory."""+ from local_deep_research.config.paths import (+ get_custom_data_directory,+ get_data_directory,+ )++ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path / "custom_data"))+ assert get_custom_data_directory() == tmp_path / "custom_data"+ assert get_custom_data_directory() == get_data_directory()++ @pytest.mark.parametrize("value", [None, ""])+ def test_custom_data_directory_is_none_when_unset_or_empty(+ self, monkeypatch, value+ ):+ """Unset and empty LDR_DATA_DIR both mean the platform default."""+ from local_deep_research.config.paths import get_custom_data_directory++ if value is None:+ monkeypatch.delenv("LDR_DATA_DIR", raising=False)+ else:+ monkeypatch.setenv("LDR_DATA_DIR", value)+ assert get_custom_data_directory() is None++ def test_bootstrap_data_dir_variable_moves_nothing(+ self, tmp_path, monkeypatch+ ):+ """Only LDR_DATA_DIR selects the directory; a lookalike is ignored."""+ from local_deep_research.config.paths import (+ get_custom_data_directory,+ get_data_directory,+ )++ monkeypatch.delenv("LDR_DATA_DIR", raising=False)+ baseline = get_data_directory()+ monkeypatch.setenv("LDR_BOOTSTRAP_DATA_DIR", str(tmp_path / "decoy"))++ assert get_data_directory() == baseline+ assert get_custom_data_directory() is None++ def test_custom_data_directory_rejects_a_relative_path(self, monkeypatch):+ """The helper keeps get_data_directory's validation, not its own."""+ from local_deep_research.config.paths import get_custom_data_directory++ monkeypatch.setenv("LDR_DATA_DIR", "relative/data")+ with pytest.raises(ValueError, match="absolute"):+ get_custom_data_directory()+def test_custom_dir_propagates_to_all_subdirectories(self, tmp_path, monkeypatch):diff --git a/tests/security/test_flask_secret_key_gate.py b/tests/security/test_flask_secret_key_gate.pyindex 2e81e2afbe..37315ecfb1 100644--- a/tests/security/test_flask_secret_key_gate.py+++ b/tests/security/test_flask_secret_key_gate.py@@ -174,9 +174,12 @@ def _flags(content: str, tmp_path: Path) -> bool:# exists to prevent.'JWT_SECRET_KEY = "super-secret-jwt-value-123"','FLASK_SECRET_KEY = "super-secret-flask-value1"',- # This project's own session-secret env var names -- the single most- # likely place a real leak would show up, and the pair that a- # `JWT_`/`FLASK_`-only allowlist is blind to.+ # LDR_-prefixed spellings of the same shape. The application reads+ # neither from the environment (the session-signing key lives in+ # `<data_dir>/.secret_key`), but they are the names an operator would+ # most plausibly try, so they are the most likely place a real leak+ # would show up -- and the pair that a `JWT_`/`FLASK_`-only+ # allowlist is blind to.'LDR_SECRET_KEY = "super-secret-ldr-value-123"','LDR_BOOTSTRAP_SECRET_KEY = "super-secret-boot-value-1"','APP_SECRET_KEY = "super-secret-app-value-123"',diff --git a/tests/security/test_secure_logging_writes.py b/tests/security/test_secure_logging_writes.pyindex 2bc2faa4d7..a78a557d28 100644--- a/tests/security/test_secure_logging_writes.py+++ b/tests/security/test_secure_logging_writes.py@@ -12,11 +12,11 @@ Surfaces pinned:import-time ``logs`` dir creation (~:27-28), the control-char patcher(~:689-692), and the file sink's ``diagnose=False`` (~:781).* ``config/paths.py`` — ``get_logs_directory()`` derives strictly from- ``LDR_DATA_DIR``. Neither a hostile ``LDR_LOG_DIR`` env var nor the- registered-but-unread ``bootstrap.log_dir`` setting- (``LDR_BOOTSTRAP_LOG_DIR``, ``settings/env_definitions/bootstrap.py``)- can move the sink: the same containment contract as- ``test_settings_path_escape.py`` (battery B).+ ``LDR_DATA_DIR``. Neither a hostile ``LDR_LOG_DIR`` env var nor+ ``LDR_BOOTSTRAP_LOG_DIR`` (the variable of a ``bootstrap.log_dir`` setting+ that nothing ever read and that has been removed from the registry;+ operators may still export it) can move the sink: the same containment+ contract as ``test_settings_path_escape.py`` (battery B).* ``security/log_sanitizer.py`` — the sanctioned dual-scrub keeps knownsecrets off disk. The file sink also redacts raw credential fields;``test_raw_sensitive_fields_are_redacted_before_disk_write`` pins that@@ -187,10 +187,11 @@ class TestLogDirContainment:def test_hostile_log_dir_env_cannot_move_log_file(self, tmp_path, attack):"""LDR_LOG_DIR / LDR_BOOTSTRAP_LOG_DIR cannot relocate the sink.- ``bootstrap.log_dir`` is registered in- ``settings/env_definitions/bootstrap.py`` but nothing in the write- path consumes it, and no code reads ``LDR_LOG_DIR`` — the sink- location is derived only from ``LDR_DATA_DIR``+ ``LDR_BOOTSTRAP_LOG_DIR`` was the variable of a ``bootstrap.log_dir``+ setting that nothing ever read and that has been removed from+ ``settings/env_definitions/bootstrap.py``; operators may still+ export it. No code reads it or ``LDR_LOG_DIR`` — the sink location+ is derived only from ``LDR_DATA_DIR``(``config/paths.py::get_logs_directory``)."""outside = tmp_path / "outside"diff --git a/tests/settings/env_vars/test_env_auto_generation.py b/tests/settings/env_vars/test_env_auto_generation.pyindex d8b0de0939..87594ff618 100644--- a/tests/settings/env_vars/test_env_auto_generation.py+++ b/tests/settings/env_vars/test_env_auto_generation.py@@ -23,7 +23,7 @@ class TestEnvVarAutoGeneration:"""Test basic key to env var conversion."""test_cases = [("testing.test_mode", "LDR_TESTING_TEST_MODE"),- ("bootstrap.data_dir", "LDR_BOOTSTRAP_DATA_DIR"),+ ("bootstrap.allow_unencrypted", "LDR_BOOTSTRAP_ALLOW_UNENCRYPTED"),("db_config.cache_size", "LDR_DB_CONFIG_CACHE_SIZE"),("app.debug", "LDR_APP_DEBUG"),("search.max_results", "LDR_SEARCH_MAX_RESULTS"),@@ -197,9 +197,7 @@ class TestBackwardCompatibility:# These are the env vars that existing code might depend onexpected_mappings = [("testing.test_mode", "LDR_TESTING_TEST_MODE"),- ("bootstrap.encryption_key", "LDR_BOOTSTRAP_ENCRYPTION_KEY"),- ("bootstrap.database_url", "LDR_BOOTSTRAP_DATABASE_URL"),- ("bootstrap.data_dir", "LDR_BOOTSTRAP_DATA_DIR"),+ ("bootstrap.allow_unencrypted", "LDR_BOOTSTRAP_ALLOW_UNENCRYPTED"),("db_config.cache_size_mb", "LDR_DB_CONFIG_CACHE_SIZE_MB"),]diff --git a/tests/settings/test_env_definitions_behavior.py b/tests/settings/test_env_definitions_behavior.pyindex ee1092c407..dfc3e5345e 100644--- a/tests/settings/test_env_definitions_behavior.py+++ b/tests/settings/test_env_definitions_behavior.py@@ -277,10 +277,8 @@ class TestEnvSettingBase:"""Env var is generated from key with LDR_ prefix."""from local_deep_research.settings.env_settings import BooleanSetting- setting = BooleanSetting(- key="bootstrap.encryption_key", description="desc"- )- assert setting.env_var == "LDR_BOOTSTRAP_ENCRYPTION_KEY"+ setting = BooleanSetting(key="test.enabled", description="desc")+ assert setting.env_var == "LDR_TEST_ENABLED"def test_is_set_returns_false_when_not_set(self):"""is_set returns False when env var not present."""diff --git a/tests/settings/test_env_registry_extended.py b/tests/settings/test_env_registry_extended.pyindex b375c58dc6..118ea40816 100644--- a/tests/settings/test_env_registry_extended.py+++ b/tests/settings/test_env_registry_extended.py@@ -308,10 +308,9 @@ class TestRegistryGlobalInstance:"""Test that registry has bootstrap category registered."""settings = registry.get_category_settings("bootstrap")- assert len(settings) >= 7+ assert len(settings) == 1keys = [s.key for s in settings]- assert "bootstrap.encryption_key" in keys- assert "bootstrap.data_dir" in keys+ assert "bootstrap.allow_unencrypted" in keysdef test_registry_has_db_config_category(self):"""Test that registry has db_config category registered."""@@ -327,7 +326,7 @@ class TestRegistryGlobalInstance:bootstrap_vars = registry.get_bootstrap_vars()# Should include both bootstrap and db_config- assert "LDR_BOOTSTRAP_ENCRYPTION_KEY" in bootstrap_vars+ assert "LDR_BOOTSTRAP_ALLOW_UNENCRYPTED" in bootstrap_varsassert "LDR_DB_CONFIG_CACHE_SIZE_MB" in bootstrap_varsdef test_registry_get_testing_vars(self):diff --git a/tests/settings/test_env_settings.py b/tests/settings/test_env_settings.pyindex 13a1cf7200..21dc449576 100644--- a/tests/settings/test_env_settings.py+++ b/tests/settings/test_env_settings.py@@ -10,6 +10,11 @@ from local_deep_research.settings.env_registry import (is_test_mode,is_ci_environment,)+from local_deep_research.settings.env_settings import (+ PathSetting,+ SecretSetting,+ SettingsRegistry,+)from local_deep_research.settings.manager import SettingsManager@@ -45,7 +50,7 @@ class TestEnvRegistry:all_settings = registry.list_all_settings()assert len(all_settings) > 0, "Registry should have settings"assert "testing.test_mode" in all_settings- assert "bootstrap.encryption_key" in all_settings+ assert "bootstrap.allow_unencrypted" in all_settingsassert "db_config.cache_size_mb" in all_settingsdef test_categories(self):@@ -118,31 +123,36 @@ class TestEnvRegistry:journal_mode = get_env_setting("db_config.journal_mode")assert journal_mode == "WAL" # Default value- def test_path_setting(self):+ def test_path_setting(self, tmp_path):"""Test path setting expansion."""- test_path = "/tmp/test_ldr_path"- os.environ["LDR_BOOTSTRAP_DATA_DIR"] = test_path- data_dir = get_env_setting("bootstrap.data_dir")+ isolated_registry = SettingsRegistry()+ isolated_registry.register_category(+ "test", [PathSetting(key="test.path", description="Test path")]+ )++ test_path = str(tmp_path.resolve() / "ldr_path")+ os.environ["LDR_TEST_PATH"] = test_path+ data_dir = isolated_registry.get("test.path")assert data_dir == test_path# Test home expansion- os.environ["LDR_BOOTSTRAP_DATA_DIR"] = "~/test_path"- data_dir = get_env_setting("bootstrap.data_dir")+ os.environ["LDR_TEST_PATH"] = "~/test_path"+ data_dir = isolated_registry.get("test.path")assert data_dir.startswith(str(Path.home()))assert "test_path" in data_dirdef test_secret_setting(self):- """Test secret setting hides values."""- os.environ["LDR_BOOTSTRAP_ENCRYPTION_KEY"] = "secret_key_123"- setting_obj = registry.get_setting_object("bootstrap.encryption_key")+ """Secret values remain readable without appearing in representations."""+ os.environ["LDR_TEST_SECRET"] = "secret_key_123"+ setting_obj = SecretSetting(+ key="test.secret", description="Test secret"+ )+ isolated_registry = SettingsRegistry()+ isolated_registry.register_category("test", [setting_obj])- # Value should be hidden in string representationassert "secret_key_123" not in str(setting_obj)assert "SET" in str(setting_obj)-- # But value should still be retrievable- value = get_env_setting("bootstrap.encryption_key")- assert value == "secret_key_123"+ assert isolated_registry.get("test.secret") == "secret_key_123"class TestSettingsManagerIntegration:@@ -178,7 +188,7 @@ class TestSettingsManagerIntegration:# These should be env-onlyassert sm.is_env_only_setting("testing.test_mode")- assert sm.is_env_only_setting("bootstrap.encryption_key")+ assert sm.is_env_only_setting("bootstrap.allow_unencrypted")assert sm.is_env_only_setting("db_config.cache_size_mb")# These should NOT be env-only (regular settings)@@ -193,9 +203,7 @@ class TestSettingsManagerIntegration:bootstrap_vars = sm.get_bootstrap_env_vars()# Should include bootstrap settings- assert "LDR_BOOTSTRAP_ENCRYPTION_KEY" in bootstrap_vars- assert "LDR_BOOTSTRAP_DATA_DIR" in bootstrap_vars- assert "LDR_BOOTSTRAP_CONFIG_DIR" in bootstrap_vars+ assert "LDR_BOOTSTRAP_ALLOW_UNENCRYPTED" in bootstrap_vars# Should include db_config settingsassert "LDR_DB_CONFIG_CACHE_SIZE_MB" in bootstrap_vars@@ -209,9 +217,8 @@ class TestSettingsManagerIntegration:sm = SettingsManager(db_session=None)# Bootstrap vars- assert sm.is_bootstrap_env_var("LDR_BOOTSTRAP_ENCRYPTION_KEY")+ assert sm.is_bootstrap_env_var("LDR_BOOTSTRAP_ALLOW_UNENCRYPTED")assert sm.is_bootstrap_env_var("LDR_DB_CONFIG_PAGE_SIZE")- assert sm.is_bootstrap_env_var("LDR_BOOTSTRAP_DATA_DIR")# Testing vars are in ALL_ENV_ONLY_VARS but not specifically bootstrap# They are allowed by the pre-commit hook but not considered bootstrap vars@@ -231,8 +238,8 @@ class TestEnvVarMapping:registry.get_env_var("testing.test_mode") == "LDR_TESTING_TEST_MODE")assert (- registry.get_env_var("bootstrap.encryption_key")- == "LDR_BOOTSTRAP_ENCRYPTION_KEY"+ registry.get_env_var("bootstrap.allow_unencrypted")+ == "LDR_BOOTSTRAP_ALLOW_UNENCRYPTED")assert (registry.get_env_var("db_config.cache_size_mb")@@ -249,7 +256,7 @@ class TestEnvVarMapping:# Should include key variablesassert "LDR_TESTING_TEST_MODE" in all_env_vars- assert "LDR_BOOTSTRAP_ENCRYPTION_KEY" in all_env_vars+ assert "LDR_BOOTSTRAP_ALLOW_UNENCRYPTED" in all_env_vars# CI and TESTING are external vars, not in registry anymoredef test_category_specific_vars(self):@@ -262,8 +269,7 @@ class TestEnvVarMapping:# Bootstrap vars (includes db_config)bootstrap_vars = registry.get_bootstrap_vars()assert len(bootstrap_vars) >= 10- assert "LDR_BOOTSTRAP_ENCRYPTION_KEY" in bootstrap_vars- assert "LDR_BOOTSTRAP_DATA_DIR" in bootstrap_vars+ assert "LDR_BOOTSTRAP_ALLOW_UNENCRYPTED" in bootstrap_varsassert "LDR_DB_CONFIG_CACHE_SIZE_MB" in bootstrap_varsassert "LDR_DB_CONFIG_JOURNAL_MODE" in bootstrap_vars@@ -271,7 +277,7 @@ class TestEnvVarMapping:"""Test checking if a setting is env-only."""# These should be env-onlyassert registry.is_env_only("testing.test_mode")- assert registry.is_env_only("bootstrap.encryption_key")+ assert registry.is_env_only("bootstrap.allow_unencrypted")assert registry.is_env_only("db_config.cache_size_mb")# These should not exist in env registrydiff --git a/tests/settings/test_generate_config_docs.py b/tests/settings/test_generate_config_docs.pyindex 9eb41a0fe6..b5ed0374fd 100644--- a/tests/settings/test_generate_config_docs.py+++ b/tests/settings/test_generate_config_docs.py@@ -134,11 +134,11 @@ class TestGetEnvOnlySettings:f"Setting '{s.get('key', '?')}' is missing fields: {missing}")- def test_bootstrap_encryption_key_present(self):- """The bootstrap encryption key should be discovered."""+ def test_bootstrap_encryption_policy_present(self):+ """The supported bootstrap encryption policy should be discovered."""settings = get_env_only_settings()keys = {s["key"] for s in settings}- assert "bootstrap.encryption_key" in keys+ assert "bootstrap.allow_unencrypted" in keysdef test_db_config_has_constraints(self):"""db_config settings should have min/max values extracted."""diff --git a/tests/settings/test_settings_defaults_integrity.py b/tests/settings/test_settings_defaults_integrity.pyindex 4fdfd3980e..569ea75b43 100644--- a/tests/settings/test_settings_defaults_integrity.py+++ b/tests/settings/test_settings_defaults_integrity.py@@ -103,8 +103,6 @@ KNOWN_SNAPSHOT_DIVERGENCES = {# ---------------------------------------------------------------------------KNOWN_MISSING_DEFAULTS = {- # Env-only bootstrap settings- "bootstrap.data_dir",# Runtime/programmatic settings (created by SettingsManager, not JSON)"app.version","document_scheduler.last_run",diff --git a/tests/settings/test_settings_manager.py b/tests/settings/test_settings_manager.pyindex e13efa6425..c75cee2ba7 100644--- a/tests/settings/test_settings_manager.py+++ b/tests/settings/test_settings_manager.py@@ -1194,13 +1194,12 @@ class TestSettingsManagerStaticMethods:result = SettingsManager.get_bootstrap_env_vars()assert isinstance(result, dict)- assert "LDR_BOOTSTRAP_ENCRYPTION_KEY" in result- assert "LDR_BOOTSTRAP_DATA_DIR" in result+ assert "LDR_BOOTSTRAP_ALLOW_UNENCRYPTED" in resultdef test_is_bootstrap_env_var_true(self):"""Test is_bootstrap_env_var returns True for bootstrap vars."""assert SettingsManager.is_bootstrap_env_var(- "LDR_BOOTSTRAP_ENCRYPTION_KEY"+ "LDR_BOOTSTRAP_ALLOW_UNENCRYPTED")assert SettingsManager.is_bootstrap_env_var("LDR_DB_CONFIG_CACHE_SIZE_MB"@@ -1214,7 +1213,9 @@ class TestSettingsManagerStaticMethods:def test_is_env_only_setting_true(self):"""Test is_env_only_setting returns True for env-only settings."""assert SettingsManager.is_env_only_setting("testing.test_mode")- assert SettingsManager.is_env_only_setting("bootstrap.encryption_key")+ assert SettingsManager.is_env_only_setting(+ "bootstrap.allow_unencrypted"+ )def test_is_env_only_setting_false(self):"""Test is_env_only_setting returns False for DB settings."""diff --git a/tests/settings/test_shipped_defaults_contracts.py b/tests/settings/test_shipped_defaults_contracts.pyindex 1605e6625c..ae7b92f409 100644--- a/tests/settings/test_shipped_defaults_contracts.py+++ b/tests/settings/test_shipped_defaults_contracts.py@@ -84,6 +84,11 @@ DEFAULTS_DIR = SRC_DIR / "defaults"MIN_DEFAULT_FILES = 25MIN_DEFAULT_KEYS = 550MIN_SRC_FILES_SWEPT = 400+# Floor on the env-only registry: guards against mass removal or a registry+# that failed to load, not a count. 30 are registered, so 27 absorbs a few+# deliberate removals but trips when a whole category (security 11,+# db_config 10, server 4) is lost.+MIN_ENV_SETTINGS = 27# Keys that must exist for the corpus to be considered loaded at all. One# per shipped file family, chosen because each is load-bearing somewhere@@ -590,7 +595,7 @@ class TestSecureByDefault:for group in ALL_SETTINGS.values()for setting in group}- assert len(by_key) >= 30+ assert len(by_key) >= MIN_ENV_SETTINGS# Encryption must not be optional by default.assert by_key["bootstrap.allow_unencrypted"].default is False@@ -1390,27 +1395,11 @@ def _is_referenced(key: str) -> bool:class TestRegistryConsistency:- @pytest.mark.xfail(- strict=True,- reason=(- "DEFECT: six environment-only settings are registered and "- "published in docs/CONFIGURATION.md but read by nothing in "- "src/ -- bootstrap.encryption_key, bootstrap.secret_key, "- "bootstrap.database_url, bootstrap.config_dir, "- "bootstrap.log_dir, bootstrap.enable_file_logging. Two are "- "security-relevant: an operator who sets "- "LDR_BOOTSTRAP_SECRET_KEY to pin the session-signing key is "- "silently ignored (fastapi_app._load_secret_key generates and "- "persists its own), and LDR_BOOTSTRAP_ENCRYPTION_KEY does not "- "supply the database encryption key. Fix by wiring them up or "- "by deleting the definitions and their doc rows."- ),- )def test_every_env_registry_key_is_read_somewhere(self):registered = [setting for group in ALL_SETTINGS.values() for setting in group]- assert len(registered) >= 30, (+ assert len(registered) >= MIN_ENV_SETTINGS, (f"only {len(registered)} env settings registered; the registry "f"did not load")diff --git a/tests/test_config_env_var_contracts.py b/tests/test_config_env_var_contracts.pyindex 3df7c35b65..120e477c34 100644--- a/tests/test_config_env_var_contracts.py+++ b/tests/test_config_env_var_contracts.py@@ -36,12 +36,15 @@ inventory test that discovers zero items and passes is worse than no test."""import ast+import importlib+import pkgutilfrom pathlib import Pathimport pytest+from local_deep_research.settings import env_definitionsfrom local_deep_research.settings.env_registry import registry as env_registry-from local_deep_research.settings.env_settings import BooleanSetting+from local_deep_research.settings.env_settings import BooleanSetting, EnvSettingfrom local_deep_research.settings.manager import (check_env_setting,get_typed_setting_value,@@ -151,6 +154,11 @@ def _collect_env_reads():ENV_READS = _collect_env_reads()LDR_VARS_READ = {name for _, name, _ in ENV_READS if name.startswith("LDR_")}+# Floor against mass removal or a registry that failed to load, not a count+# of today's keys: 30 are registered, so 27 absorbs a few deliberate removals+# but trips when a whole category (security 11, db_config 10, server 4) is lost.+MIN_REGISTRY_SETTINGS = 27+# ---------------------------------------------------------------------------# 1. Inventory -- with minimum-count guards so it cannot pass vacuously@@ -194,8 +202,9 @@ def test_registry_inventory_is_populated_and_holds_the_security_gates():here disappears from the documentation in the same commit."""declared = set(env_registry.get_all_env_vars())- assert len(declared) >= 30, (- f"registry declares only {len(declared)} env vars; expected ~35"+ assert len(declared) >= MIN_REGISTRY_SETTINGS, (+ f"registry declares only {len(declared)} env vars; expected at "+ f"least {MIN_REGISTRY_SETTINGS}")for gate in ("LDR_NOTIFICATIONS_ALLOW_OUTBOUND",@@ -409,24 +418,6 @@ def test_undocumented_security_relevant_env_vars_match_the_known_gap():# 3. Declared-but-never-read settings (silently dropped keys, inbound)# ----------------------------------------------------------------------------# Registry keys nothing in src/ reads. Each is nonetheless published to-# operators as a supported variable by the generated docs/CONFIGURATION.md,-# so setting one is a silent no-op: no effect, no warning, no error.-_KNOWN_DEAD_REGISTRY_KEYS = {- "bootstrap.config_dir",- "bootstrap.database_url",- "bootstrap.enable_file_logging",- "bootstrap.encryption_key",- "bootstrap.log_dir",- "bootstrap.secret_key",- # Read directly via TRUSTED_PROXY_COUNT.get_value() at- # web/dependencies/rate_limit.py import time (must be resolved before- # SettingsManager exists, like TRUST_PROXY_HEADERS above), never- # through a SettingsManager/registry lookup by string key -- so the- # generic "is this key ever read" scan can't see it.- "server.trusted_proxy_count",-}-def _docstring_constant_ids(tree):"""ids of the ``ast.Constant`` nodes that are docstrings, not code."""@@ -448,12 +439,117 @@ def _docstring_constant_ids(tree):return ids-def _registry_keys_without_a_consumer():- """Registry keys that appear in no *code* string literal outside the- registry.+def _setting_objects():+ """``{dotted path: registry key}`` for each setting object that+ ``settings/env_definitions`` binds to a module-level name.++ ``TRUSTED_PROXY_COUNT`` is defined that way so that+ ``web/dependencies/rate_limit.py`` can import it and read it at import+ time, before any settings manager exists. Its key string never appears+ outside ``env_definitions``, so a scan for string literals cannot see+ that read.+ """+ found = {}+ for info in pkgutil.iter_modules(env_definitions.__path__):+ module = importlib.import_module(+ f"{env_definitions.__name__}.{info.name}"+ )+ for name, value in vars(module).items():+ if isinstance(value, EnvSetting):+ found[f"{module.__name__}.{name}"] = value.key+ return found+++def _dotted_name(node):+ """``"a.b.c"`` for a ``Name`` / ``Attribute`` chain, else ``None``."""+ parts = []+ while isinstance(node, ast.Attribute):+ parts.append(node.attr)+ node = node.value+ if not isinstance(node, ast.Name):+ return None+ parts.append(node.id)+ return ".".join(reversed(parts))+++def _imported_paths(rel, tree):+ """``{local name: dotted path it refers to}`` for the imports in *tree*.++ *rel* is the file's path below the package; it fixes what a relative+ import means.+ """+ package = [SRC_PKG.name, *rel.parent.parts]+ bound = {}+ for node in ast.walk(tree):+ if isinstance(node, ast.Import):+ for alias in node.names:+ if alias.asname:+ bound[alias.asname] = alias.name+ else: # ``import a.b.c`` binds only the root name ``a``+ root = alias.name.split(".")[0]+ bound[root] = root+ elif isinstance(node, ast.ImportFrom):+ # Level 1 is the importing file's own package.+ keep = max(len(package) - max(node.level - 1, 0), 0)+ anchor = package[:keep] if node.level else []+ base = ".".join([*anchor, *([node.module] if node.module else [])])+ for alias in node.names:+ bound[alias.asname or alias.name] = f"{base}.{alias.name}"+ return bound+++def _keys_read_through_setting_objects(rel, tree, objects):+ """Registry keys *tree* reads as ``<setting object>.get_value()``.++ The object must come from an ``env_definitions`` module, imported by+ name (``from ...env_definitions.server import NAME [as ALIAS]``) or+ reached through the module (``server.NAME``). A same-named local, an+ object imported from anywhere else, an import that is never called and+ any other member (``NAME.is_set``) read nothing.+ """+ bound = _imported_paths(rel, tree)+ keys = set()+ for node in ast.walk(tree):+ if not (+ isinstance(node, ast.Call)+ and isinstance(node.func, ast.Attribute)+ and node.func.attr == "get_value"+ ):+ continue+ dotted = _dotted_name(node.func.value)+ if dotted is None:+ continue+ root, _, rest = dotted.partition(".")+ if root not in bound:+ continue+ path = f"{bound[root]}.{rest}" if rest else bound[root]+ if path in objects:+ keys.add(objects[path])+ return keys+++def _consumer_trees():+ """``(path below the package, tree)`` for each production file that could+ consume a setting, which is every one but the definitions themselves."""+ for path in _iter_source_files():+ rel = path.relative_to(SRC_PKG)+ if "env_definitions" in rel.parts:+ continue+ tree = _parse(path)+ if tree is not None:+ yield rel, tree+- Deliberately narrow on two axes, because both looser forms produce- false negatives here:+def _registry_keys_without_a_consumer(trees=None):+ """Registry keys that nothing outside the registry definitions consumes.++ A key is consumed when it appears as a *code* string literal, or when+ the setting object it is defined as is imported and read with+ ``.get_value()``. A genuine string consumer passes the key verbatim to+ ``get_env_setting`` / ``get_setting`` / ``get_typed_setting_value``.++ The literal scan is deliberately narrow on two axes, because both+ looser forms produce false negatives here:* AST constants, not raw text -- several gates are named in commentsexplaining when an operator would set them@@ -463,16 +559,16 @@ def _registry_keys_without_a_consumer():match over docstrings would call a key "consumed" on the strength ofdocumentation alone.- A genuine consumer passes the key verbatim to ``get_env_setting`` /- ``get_setting`` / ``get_typed_setting_value``.+ The object scan is narrow in the same way; see+ ``_keys_read_through_setting_objects``. *trees* replaces the production+ tree with ``(path below the package, tree)`` pairs, for negative+ controls."""- constants = set()- for path in _iter_source_files():- if "env_definitions" in path.relative_to(SRC_PKG).parts:- continue- tree = _parse(path)- if tree is None:- continue+ if trees is None:+ trees = _consumer_trees()+ objects = _setting_objects()+ consumed = set()+ for rel, tree in trees:docstrings = _docstring_constant_ids(tree)for node in ast.walk(tree):if (@@ -480,58 +576,130 @@ def _registry_keys_without_a_consumer():and isinstance(node.value, str)and id(node) not in docstrings):- constants.add(node.value)+ consumed.add(node.value)+ consumed |= _keys_read_through_setting_objects(rel, tree, objects)return {- key for key in env_registry.list_all_settings() if key not in constants+ key for key in env_registry.list_all_settings() if key not in consumed}-def test_registry_settings_declared_but_never_read_match_the_known_set():- """A declared setting with no consumer is a documented no-op.-- ``LDR_BOOTSTRAP_SECRET_KEY`` is the one that reads worst: the registry- describes it as "Application secret key for session encryption" and- ``docs/CONFIGURATION.md`` publishes it, but ``_load_secret_key()`` in- ``web/fastapi_app.py`` only ever reads/creates ``<data_dir>/.secret_key``- -- it never consults the environment. An operator pinning the session- signing key across replicas gets a per-host random key and no warning.- The same shape applies to ``LDR_BOOTSTRAP_ENCRYPTION_KEY`` and- ``LDR_BOOTSTRAP_DATABASE_URL``.- """+def test_every_registry_setting_has_a_consumer():+ """Documented environment settings must be read by application code."""dead = _registry_keys_without_a_consumer()total = len(env_registry.list_all_settings())- assert total >= 30, f"registry shrank to {total} settings unexpectedly"- assert dead == _KNOWN_DEAD_REGISTRY_KEYS, (- "the set of declared-but-unread registry settings changed.\n"- f" newly dead: {sorted(dead - _KNOWN_DEAD_REGISTRY_KEYS)}\n"- f" now wired up (remove from the known list): "- f"{sorted(_KNOWN_DEAD_REGISTRY_KEYS - dead)}"+ assert total >= MIN_REGISTRY_SETTINGS, (+ f"registry shrank to {total} settings unexpectedly")+ assert not dead, (+ f"documented environment settings without consumers: {sorted(dead)}"+ )+++_PROBE_DEFINITIONS = "local_deep_research.settings.env_definitions.server"++_OBJECT_READ_PROBE = f"""+import {_PROBE_DEFINITIONS} as defs+from local_deep_research.settings.env_definitions import server+from {_PROBE_DEFINITIONS} import DIRECT, IMPORTED_ONLY, OTHER_METHOD+from {_PROBE_DEFINITIONS} import ALIASED as renamed+from local_deep_research.settings.env_definitions.security import WRONG_MODULE+from ...settings.env_definitions.server import RELATIVE+from ..settings.env_definitions.server import WRONG_LEVEL+from somewhere_else import LOOKALIKE++LOCAL = object()++COUNTED = [+ DIRECT.get_value(),+ renamed.get_value(),+ server.QUALIFIED.get_value(),+ defs.VIA_MODULE_ALIAS.get_value(),+ RELATIVE.get_value(),+]+NOT_COUNTED = [+ OTHER_METHOD.describe(),+ WRONG_MODULE.get_value(),+ WRONG_LEVEL.get_value(),+ LOOKALIKE.get_value(),+ LOCAL.get_value(),+ {_PROBE_DEFINITIONS}.UNIMPORTED.get_value(),+]+__all__ = ["IMPORTED_ONLY"]+"""++_PROBE_OBJECTS = {+ f"{_PROBE_DEFINITIONS}.{name}": f"probe.{name.lower()}"+ for name in (+ "DIRECT",+ "ALIASED",+ "QUALIFIED",+ "VIA_MODULE_ALIAS",+ "RELATIVE",+ "IMPORTED_ONLY",+ "OTHER_METHOD",+ "WRONG_MODULE",+ "WRONG_LEVEL",+ "LOOKALIKE",+ "LOCAL",+ "UNIMPORTED",+ "FULL_CHAIN",+ )+}-def test_data_dir_settings_api_reports_the_variable_it_does_not_read():- """``/settings/api/data-location`` names one var and reads another.+def test_object_read_scanner_counts_imported_setting_objects_and_only_those():+ """Negative controls for the scanner that spares ``TRUSTED_PROXY_COUNT``.- ``web/routers/settings.py`` returns ``"custom_env_var": "LDR_DATA_DIR"``- while sourcing ``custom_env_value`` / ``is_custom`` from the- ``bootstrap.data_dir`` setting, whose env var is- ``LDR_BOOTSTRAP_DATA_DIR``. Only ``LDR_DATA_DIR`` actually relocates- the data directory (``config/paths.py::get_data_directory``), so the two- halves of that response describe different variables.+ Without them a scanner that over-counts would mask a dead setting+ silently: any read of any object, or a bare import, would clear it.+ """+ probe = Path("web/dependencies/probe.py")+ reads = _keys_read_through_setting_objects(+ probe, ast.parse(_OBJECT_READ_PROBE), _PROBE_OBJECTS+ )+ assert reads == {+ "probe.direct",+ "probe.aliased",+ "probe.qualified",+ "probe.via_module_alias",+ "probe.relative",+ }+ # ``import a.b.c`` binds the root ``a``, so the full chain below it is+ # reachable; the aliased import in the probe above binds only the alias.+ plain = (+ f"import {_PROBE_DEFINITIONS}\n"+ f"{_PROBE_DEFINITIONS}.FULL_CHAIN.get_value()\n"+ )+ assert _keys_read_through_setting_objects(+ probe, ast.parse(plain), _PROBE_OBJECTS+ ) == {"probe.full_chain"}+++def test_data_dir_settings_api_reports_the_variable_that_moves_the_directory():+ """``/settings/api/data-location`` reports ``LDR_DATA_DIR`` and no other.++ Only ``LDR_DATA_DIR`` relocates the data directory+ (``config/paths.py::get_data_directory``). The response used to name+ ``LDR_DATA_DIR`` while sourcing ``custom_env_value`` / ``is_custom`` from+ a registered ``bootstrap.data_dir`` setting (``LDR_BOOTSTRAP_DATA_DIR``),+ so a variable that moved nothing changed the report and the one that+ mattered did not. That setting is gone; the response now asks+ ``get_custom_data_directory``, which sits beside the only reader of+ ``LDR_DATA_DIR``."""source = (SRC_PKG / "web" / "routers" / "settings.py").read_text(encoding="utf-8")assert '"custom_env_var": "LDR_DATA_DIR"' in source- assert 'get_setting("bootstrap.data_dir")' in source- assert env_registry.get_env_var("bootstrap.data_dir") == (- "LDR_BOOTSTRAP_DATA_DIR"- )+ assert "get_custom_data_directory()" in source+ assert "bootstrap.data_dir" not in source+ assert env_registry.get_env_var("bootstrap.data_dir") is None+ assert "LDR_BOOTSTRAP_DATA_DIR" not in env_registry.get_all_env_vars()paths_source = (SRC_PKG / "config" / "paths.py").read_text(encoding="utf-8")assert 'os.getenv("LDR_DATA_DIR")' in paths_sourceassert "LDR_BOOTSTRAP_DATA_DIR" not in paths_source, (- "if paths.py learned to read LDR_BOOTSTRAP_DATA_DIR this mismatch "- "is fixed -- update the test"+ "paths.py learned to read LDR_BOOTSTRAP_DATA_DIR -- document it in "+ "docs/env_configuration.md and re-register the setting")@@ -1145,18 +1313,16 @@ def test_unencrypted_database_still_warns_at_app_startup():def test_secret_key_load_fails_loudly_rather_than_going_ephemeral():"""An unreadable or empty ``.secret_key`` aborts the process.- Note the flip side, asserted in- ``test_registry_settings_declared_but_never_read_match_the_known_set``:- this function is also the reason ``LDR_BOOTSTRAP_SECRET_KEY`` is inert- -- the key comes from a file and only from a file.+ The signing key is persisted in the data directory; there is no+ environment override for its value."""source = (SRC_PKG / "web" / "fastapi_app.py").read_text(encoding="utf-8")assert "Cannot read SECRET_KEY file at" in sourceassert "is empty. " in sourceassert "SECRET_KEY = _load_secret_key()" in sourceassert "LDR_BOOTSTRAP_SECRET_KEY" not in source, (- "_load_secret_key learned about the env var -- update the dead-key "- "inventory above"+ "_load_secret_key learned about an environment override -- update "+ "the documented signing-key behavior")diff --git a/tests/web/routers/test_settings_routes_corrupted_coverage_port.py b/tests/web/routers/test_settings_routes_corrupted_coverage_port.pyindex 88ddf0af4d..92572b0095 100644--- a/tests/web/routers/test_settings_routes_corrupted_coverage_port.py+++ b/tests/web/routers/test_settings_routes_corrupted_coverage_port.py@@ -462,16 +462,10 @@ class TestApiGetDataLocationPlatform:api_get_data_location,)- mock_sm = MagicMock()- mock_sm.get_setting.return_value = None-with (patch(f"{S}.get_data_directory", return_value="/data"),+ patch(f"{S}.get_custom_data_directory", return_value=None),patch(f"{S}.get_encrypted_database_path", return_value="/data/db"),- patch(- "local_deep_research.settings.manager.SettingsManager",- return_value=mock_sm,- ),patch(f"{S}.platform") as mock_platform,patch(f"{S}.db_manager") as mock_db_mgr,):diff --git a/tests/web/routers/test_settings_routes_coverage_port.py b/tests/web/routers/test_settings_routes_coverage_port.pyindex c369b996f5..d5de72e805 100644--- a/tests/web/routers/test_settings_routes_coverage_port.py+++ b/tests/web/routers/test_settings_routes_coverage_port.py@@ -1181,6 +1181,7 @@ class TestApiGetDataLocation:f"{MODULE}.get_data_directory",return_value="/tmp/data", # noqa: S108),+ patch(f"{MODULE}.get_custom_data_directory", return_value=None),patch(f"{MODULE}.platform", mock_platform),patch("local_deep_research.database.sqlcipher_utils"diff --git a/tests/web/routers/test_settings_routes_deep_coverage2_port.py b/tests/web/routers/test_settings_routes_deep_coverage2_port.pyindex 3265fbec31..4eea6a6b71 100644--- a/tests/web/routers/test_settings_routes_deep_coverage2_port.py+++ b/tests/web/routers/test_settings_routes_deep_coverage2_port.py@@ -1017,19 +1017,13 @@ class TestApiGetDataLocationEncrypted:mock_dbm = MagicMock()mock_dbm.has_encryption = True- sm = _unlocked_manager()- sm.get_setting.return_value = None-with (patch(f"{S}.db_manager", mock_dbm),patch(f"{S}.get_data_directory", return_value="/data"),+ patch(f"{S}.get_custom_data_directory", return_value=None),patch(f"{S}.get_encrypted_database_path", return_value="/data/db.enc"),- patch(- "local_deep_research.settings.manager.SettingsManager",- return_value=sm,- ),patch("local_deep_research.database.sqlcipher_utils.get_sqlcipher_settings",return_value={"cipher": "AES-256"},diff --git a/tests/web/routers/test_settings_routes_gaps_coverage_port.py b/tests/web/routers/test_settings_routes_gaps_coverage_port.pyindex 573534689d..d408a267fd 100644--- a/tests/web/routers/test_settings_routes_gaps_coverage_port.py+++ b/tests/web/routers/test_settings_routes_gaps_coverage_port.py@@ -60,6 +60,7 @@ possible: httpx follows by default where Flask's client did not.import asynciofrom contextlib import contextmanager+from pathlib import Pathfrom unittest.mock import MagicMock, Mock, patchimport pytest@@ -494,20 +495,14 @@ class TestApiGetDataLocation:the 500 arm are unpinned on the branch."""def test_returns_data_location_info(self, client):- mock_sm = Mock()- mock_sm.get_setting.return_value = None # No custom data dir-with (patch(f"{S}.get_data_directory", return_value="/data/ldr"),+ patch(f"{S}.get_custom_data_directory", return_value=None),patch(f"{S}.get_encrypted_database_path",return_value="/data/ldr/encrypted",),patch(f"{S}.db_manager", Mock(has_encryption=True)),- patch(- "local_deep_research.settings.manager.SettingsManager",- return_value=mock_sm,- ),patch("local_deep_research.database.sqlcipher_utils.get_sqlcipher_settings",return_value={"kdf_iterations": 256000},@@ -519,30 +514,71 @@ class TestApiGetDataLocation:data = resp.json()assert data["data_directory"] == "/data/ldr"assert data["is_custom"] is False+ assert data["custom_env_value"] is Noneassert data["security_notice"]["encrypted"] is Truedef test_returns_unencrypted_warning(self, client):- mock_sm = Mock()- mock_sm.get_setting.return_value = "/custom/dir"-with (patch(f"{S}.get_data_directory", return_value="/data/ldr"),+ patch(+ f"{S}.get_custom_data_directory",+ return_value=Path("/custom/dir"),+ ),patch(f"{S}.get_encrypted_database_path",return_value="/data/ldr/db",),patch(f"{S}.db_manager", Mock(has_encryption=False)),- patch(- "local_deep_research.settings.manager.SettingsManager",- return_value=mock_sm,- ),):resp = client.get("/settings/api/data-location")data = resp.json()assert data["is_custom"] is True+ assert data["custom_env_value"] == str(Path("/custom/dir"))assert data["security_notice"]["encrypted"] is False+ def test_ldr_data_dir_marks_the_location_custom(+ self, client, tmp_path, monkeypatch+ ):+ """``LDR_DATA_DIR`` moves the data directory, so it is what the+ response reports as the custom location."""+ custom = tmp_path / "custom-data"+ monkeypatch.setenv("LDR_DATA_DIR", str(custom))++ with patch(f"{S}.db_manager", Mock(has_encryption=False)):+ resp = client.get("/settings/api/data-location")++ assert resp.status_code == 200+ data = resp.json()+ assert data["is_custom"] is True+ assert data["custom_env_var"] == "LDR_DATA_DIR"+ assert data["custom_env_value"] == str(custom.resolve())+ assert data["data_directory"] == data["custom_env_value"]++ def test_bootstrap_data_dir_variable_does_not_mark_the_location_custom(+ self, client, tmp_path, monkeypatch+ ):+ """``LDR_BOOTSTRAP_DATA_DIR`` moves nothing, so it must neither mark+ the location custom nor make the settings page create its directory."""+ platform_default = tmp_path / "platform-default"+ decoy = tmp_path / "decoy"+ monkeypatch.delenv("LDR_DATA_DIR", raising=False)+ monkeypatch.setenv("LDR_BOOTSTRAP_DATA_DIR", str(decoy))+ monkeypatch.setattr(+ "platformdirs.user_data_dir",+ lambda *_args, **_kwargs: str(platform_default),+ )++ with patch(f"{S}.db_manager", Mock(has_encryption=False)):+ resp = client.get("/settings/api/data-location")++ assert resp.status_code == 200+ data = resp.json()+ assert data["data_directory"] == str(platform_default)+ assert data["is_custom"] is False+ assert data["custom_env_value"] is None+ assert not decoy.exists()+def test_exception_returns_500(self, client):with patch(f"{S}.get_data_directory", side_effect=RuntimeError("fail")):resp = client.get("/settings/api/data-location")diff --git a/tests/web/test_security_headers_matrix.py b/tests/web/test_security_headers_matrix.pyindex 06effb640b..6550608065 100644--- a/tests/web/test_security_headers_matrix.py+++ b/tests/web/test_security_headers_matrix.py@@ -722,7 +722,6 @@ class TestCookieSurface:env.pop(key, None)env.update(LDR_DATA_DIR=str(tmp_path),- LDR_BOOTSTRAP_DATA_DIR=str(tmp_path),LDR_EXPOSE_DOCS="true",LDR_BOOTSTRAP_ALLOW_UNENCRYPTED="true",**test_env,