~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(ui,llm): LM Studio model detection + auto-discovery credential leak (#3800) (#3942)
LearningCircuit6fa39e94b1ce
diff --git a/changelog.d/3800.bugfix.md b/changelog.d/3800.bugfix.mdnew file mode 100644index 0000000000..0b8db2db5b--- /dev/null+++ b/changelog.d/3800.bugfix.md@@ -0,0 +1 @@+Fix the model dropdown in Settings to populate for every auto-discovered LLM provider, not just Ollama / OpenAI / Anthropic / OpenAI-Compatible-Endpoint. LM Studio, Llama.cpp, Google Gemini, xAI, OpenRouter, and IONOS were silently dropped by the frontend (`processModelData`) even when the backend returned their models correctly.diff --git a/changelog.d/3800.security.md b/changelog.d/3800.security.mdnew file mode 100644index 0000000000..b1710e9813--- /dev/null+++ b/changelog.d/3800.security.md@@ -0,0 +1 @@+Fix LM Studio model detection (#3800) — the settings dropdown was silently dropping models for every auto-discovered provider except Ollama / OpenAI / Anthropic / OpenAI-Compatible-Endpoint, including LM Studio, Llama.cpp, Google Gemini, xAI, OpenRouter, and IONOS. While investigating, also fixed a separate credential-leak class where the route's auto-discovery loop sent every other provider's configured API key in the `Authorization` header to the local LM Studio / llama-server endpoint on every settings-page load.diff --git a/src/local_deep_research/llm/providers/openai_base.py b/src/local_deep_research/llm/providers/openai_base.pyindex 9a45d0c1b6..72ea69ba62 100644--- a/src/local_deep_research/llm/providers/openai_base.py+++ b/src/local_deep_research/llm/providers/openai_base.py@@ -260,6 +260,18 @@ class OpenAICompatibleProvider(BaseLLMProvider):List of model dictionaries with 'value' and 'label' keys"""try:+ # Defense-in-depth: never send a non-string credential to the SDK.+ # The OpenAI client coerces the api_key into "Authorization: Bearer+ # <repr(api_key)>" — passing a dict would leak its contents to the+ # endpoint we're listing models from.+ if api_key is not None and not isinstance(api_key, str):+ logger.error(+ f"{cls.provider_name}.list_models_for_api received "+ f"non-string api_key of type {type(api_key).__name__}; "+ f"refusing to send."+ )+ return []+# Check if auth is requiredif cls.requires_auth_for_models():if not api_key:diff --git a/src/local_deep_research/web/routes/settings_routes.py b/src/local_deep_research/web/routes/settings_routes.pyindex d2bd18f962..75786a4e82 100644--- a/src/local_deep_research/web/routes/settings_routes.py+++ b/src/local_deep_research/web/routes/settings_routes.py@@ -145,8 +145,20 @@ def _is_allowed_new_setting_key(key: str) -> bool:return False-def _get_setting_from_session(key: str, default=None):- """Helper to get a setting using the current session context."""+def _get_setting_from_session(key: str | None, default=None):+ """Helper to get a setting using the current session context.++ A ``None`` key returns ``default``. ``SettingsManager.get_setting``+ treats ``key=None`` as "return all settings" (a real feature used by+ ``get_all_settings`` for enumeration); this route helper is for+ fetching one named setting and must not inherit that bulk-read+ semantic. Without the guard, callers like the auto-discovered+ model-listing loop would receive a dict of every setting (including+ other providers' API keys) when a provider declares+ ``api_key_setting = None`` (LM Studio, Llama.cpp).+ """+ if key is None:+ return defaultusername = session.get("username")with get_user_db_session(username) as db_session:if db_session:diff --git a/src/local_deep_research/web/static/js/components/settings.js b/src/local_deep_research/web/static/js/components/settings.jsindex 809d86d9aa..f9d55178b8 100644--- a/src/local_deep_research/web/static/js/components/settings.js+++ b/src/local_deep_research/web/static/js/components/settings.js@@ -3289,62 +3289,28 @@SafeLogger.log('Found provider options:', data.provider_options.length);}- // Check for Ollama models- if (data.providers && data.providers.ollama_models && data.providers.ollama_models.length > 0) {- const ollama_models = data.providers.ollama_models;- SafeLogger.log('Found Ollama models:', ollama_models.length);-- // Add provider information to each model- ollama_models.forEach(model => {- formattedModels.push({- value: model.value,- label: model.label,- provider: 'OLLAMA' // Ensure provider field is added- });- });- }-- // Add OpenAI models if available- if (data.providers && data.providers.openai_models && data.providers.openai_models.length > 0) {- const openai_models = data.providers.openai_models;- SafeLogger.log('Found OpenAI models:', openai_models.length);-- // Add provider information to each model- openai_models.forEach(model => {- formattedModels.push({- value: model.value,- label: model.label,- provider: 'OPENAI' // Ensure provider field is added- });- });- }-- // Add Anthropic models if available- if (data.providers && data.providers.anthropic_models && data.providers.anthropic_models.length > 0) {- const anthropic_models = data.providers.anthropic_models;- SafeLogger.log('Found Anthropic models:', anthropic_models.length);-- // Add provider information to each model- anthropic_models.forEach(model => {- formattedModels.push({- value: model.value,- label: model.label,- provider: 'ANTHROPIC' // Ensure provider field is added- });- });- }-- // Add OpenAI-Compatible Endpoint models if available- if (data.providers && data.providers.openai_endpoint_models && data.providers.openai_endpoint_models.length > 0) {- const openai_endpoint_models = data.providers.openai_endpoint_models;- SafeLogger.log('Found OpenAI Endpoint models:', openai_endpoint_models.length);-- // Add provider information to each model- openai_endpoint_models.forEach(model => {- formattedModels.push({- value: model.value,- label: model.label,- provider: 'OPENAI_ENDPOINT' // Ensure provider field is added+ // Lift every <provider>_models array the backend returned. Each+ // auto-discovered provider stores results under+ // f"{normalize_provider(provider_key)}_models" (lowercase) at+ // settings_routes.py:1513, so the key suffix is always+ // "_models". Derive the provider tag by stripping that suffix+ // and uppercasing — matches the backend's uppercase+ // provider_key convention (LMSTUDIO, LLAMACPP, OPENAI_ENDPOINT,+ // …) used elsewhere in the frontend.+ if (data.providers) {+ const SUFFIX = '_models';+ Object.keys(data.providers).forEach(key => {+ if (!key.endsWith(SUFFIX)) return;+ const models = data.providers[key];+ if (!Array.isArray(models) || models.length === 0) return;+ const providerTag = key.slice(0, -SUFFIX.length).toUpperCase();+ SafeLogger.log(`Found ${providerTag} models:`, models.length);+ models.forEach(model => {+ formattedModels.push({+ value: model.value,+ label: model.label,+ provider: providerTag,+ });});});}diff --git a/tests/js/components/settings-model-data.test.js b/tests/js/components/settings-model-data.test.jsnew file mode 100644index 0000000000..cd27753105--- /dev/null+++ b/tests/js/components/settings-model-data.test.js@@ -0,0 +1,197 @@+/**+ * Regression tests for processModelData in components/settings.js+ *+ * Issue #3800: LM Studio model dropdown was empty because the frontend's+ * processModelData had hardcoded if-blocks for only ollama_models,+ * openai_models, anthropic_models, and openai_endpoint_models. The fix+ * (PR #3942) replaces the four hardcoded blocks with a generic loop+ * that lifts every <provider>_models array.+ *+ * Strategy+ * --------+ * processModelData is defined inside an IIFE in settings.js and never+ * exposed on window, so we cannot import settings.js and call it. Instead+ * we read the file as text, locate the loop block (the chunk between+ * `if (data.providers) {` and its matching `}`), and execute that exact+ * source against a synthetic `data` object inside a new Function. This+ * tests the literal shipped code, not a re-implementation.+ *+ * If the loop block can't be located (e.g. someone refactors the function+ * shape later), the locator throws and every test fails loudly — that is+ * the intended failure mode, not a fallback.+ */+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';++const SETTINGS_PATH = resolve(+ __dirname,+ '../../../src/local_deep_research/web/static/js/components/settings.js',+);++/**+ * Extract the full `if (data.providers) { ... }` statement (guard+ * included) from settings.js by brace-matching. We need the guard so+ * that the missing-providers test exercises the same null-safety as+ * production.+ */+function extractProvidersLoop(source) {+ const marker = 'if (data.providers) {';+ const start = source.indexOf(marker);+ if (start < 0) {+ throw new Error(+ 'Could not find `if (data.providers) {` in settings.js — ' ++ 'the fix may have been refactored. Update this test.',+ );+ }+ const openBrace = start + marker.length - 1; // index of `{`+ let depth = 0;+ let i = openBrace;+ for (; i < source.length; i++) {+ const ch = source[i];+ if (ch === '{') depth++;+ else if (ch === '}') {+ depth--;+ if (depth === 0) break;+ }+ }+ if (depth !== 0) {+ throw new Error('Brace mismatch when extracting providers loop.');+ }+ // Return the whole statement including the `if (...)` guard.+ return source.slice(start, i + 1);+}++const SOURCE = readFileSync(SETTINGS_PATH, 'utf8');+const LOOP_BODY = extractProvidersLoop(SOURCE);++/**+ * Run the extracted loop body against `data`, returning the populated+ * formattedModels array. Mirrors the surrounding processModelData+ * scaffolding (formattedModels declaration, SafeLogger stub).+ */+function runLoop(data) {+ const formattedModels = [];+ const SafeLogger = { log: () => {}, warn: () => {}, error: () => {} };+ // The loop body references `data`, `formattedModels`, and `SafeLogger`.+ // eslint-disable-next-line no-new-func+ const fn = new Function(+ 'data', 'formattedModels', 'SafeLogger',+ LOOP_BODY,+ );+ fn(data, formattedModels, SafeLogger);+ return formattedModels;+}++describe('processModelData providers loop (issue #3800)', () => {+ it('lifts lmstudio_models tagged as LMSTUDIO (the bug)', () => {+ const data = {+ providers: {+ lmstudio_models: [+ { value: 'qwen-7b', label: 'qwen-7b' },+ { value: 'phi-3', label: 'Phi 3' },+ ],+ },+ };+ const out = runLoop(data);+ expect(out).toHaveLength(2);+ expect(out[0]).toEqual({+ value: 'qwen-7b',+ label: 'qwen-7b',+ provider: 'LMSTUDIO',+ });+ expect(out[1].provider).toBe('LMSTUDIO');+ });++ it('lifts llamacpp_models tagged as LLAMACPP', () => {+ const data = {+ providers: {+ llamacpp_models: [+ { value: 'llama-3-8b.gguf', label: 'Llama 3 8B' },+ ],+ },+ };+ const out = runLoop(data);+ expect(out).toEqual([+ {+ value: 'llama-3-8b.gguf',+ label: 'Llama 3 8B',+ provider: 'LLAMACPP',+ },+ ]);+ });++ it('still handles ollama_models (backwards compat)', () => {+ const data = {+ providers: {+ ollama_models: [{ value: 'llama3', label: 'Llama 3' }],+ },+ };+ const out = runLoop(data);+ expect(out).toEqual([+ { value: 'llama3', label: 'Llama 3', provider: 'OLLAMA' },+ ]);+ });++ it('preserves OPENAI_ENDPOINT casing (underscore in tag)', () => {+ const data = {+ providers: {+ openai_endpoint_models: [+ { value: 'gpt-x', label: 'gpt-x' },+ ],+ },+ };+ const out = runLoop(data);+ expect(out[0].provider).toBe('OPENAI_ENDPOINT');+ });++ it('lifts multiple providers in one response', () => {+ const data = {+ providers: {+ ollama_models: [{ value: 'llama3', label: 'Llama 3' }],+ lmstudio_models: [{ value: 'qwen-7b', label: 'qwen-7b' }],+ openai_models: [{ value: 'gpt-4', label: 'GPT-4' }],+ },+ };+ const out = runLoop(data);+ const providers = out.map(m => m.provider).sort();+ expect(providers).toEqual(['LMSTUDIO', 'OLLAMA', 'OPENAI']);+ expect(out).toHaveLength(3);+ });++ it('handles empty providers dict without errors', () => {+ const out = runLoop({ providers: {} });+ expect(out).toEqual([]);+ });++ it('handles missing providers (undefined) without errors', () => {+ const out = runLoop({});+ expect(out).toEqual([]);+ });++ it('skips empty arrays', () => {+ const out = runLoop({ providers: { lmstudio_models: [] } });+ expect(out).toEqual([]);+ });++ it('skips non-array values (defensive)', () => {+ const out = runLoop({+ providers: {+ lmstudio_models: 'not an array',+ ollama_models: [{ value: 'a', label: 'A' }],+ },+ });+ expect(out).toHaveLength(1);+ expect(out[0].provider).toBe('OLLAMA');+ });++ it('ignores keys without _models suffix', () => {+ const out = runLoop({+ providers: {+ some_other_key: [{ value: 'x', label: 'x' }],+ lmstudio_models: [{ value: 'qwen', label: 'qwen' }],+ },+ });+ expect(out).toHaveLength(1);+ expect(out[0].provider).toBe('LMSTUDIO');+ });+});diff --git a/tests/llm_providers/test_openai_base_coverage.py b/tests/llm_providers/test_openai_base_coverage.pyindex 04a4ef1417..fa072c69fb 100644--- a/tests/llm_providers/test_openai_base_coverage.py+++ b/tests/llm_providers/test_openai_base_coverage.py@@ -234,6 +234,28 @@ class TestListModelsForApi:result = _NoKeyProvider.list_models_for_api(api_key="dummy")assert result == []+ @pytest.mark.parametrize(+ "bad_key",+ [+ {"llm.openai.api_key": "sk-leaked"}, # the issue #3800 case+ 123,+ b"bytes-not-string",+ ["list", "of", "things"],+ ],+ ids=["dict", "int", "bytes", "list"],+ )+ def test_rejects_non_string_api_key_without_calling_sdk(self, bad_key):+ """Defense-in-depth (issue #3800): a non-string api_key would land+ in ``Authorization: Bearer <repr>`` and leak its contents to the+ endpoint. The provider must refuse before constructing the client.+ """+ with patch("openai.OpenAI") as mock_openai:+ result = _NoKeyProvider.list_models_for_api(+ api_key=bad_key, base_url="http://localhost:1234/v1"+ )+ assert result == []+ mock_openai.assert_not_called()+# ---------------------------------------------------------------------------# list_models()diff --git a/tests/web/routes/test_settings_routes_deep_coverage2.py b/tests/web/routes/test_settings_routes_deep_coverage2.pyindex 4355762d2b..be0d389ed7 100644--- a/tests/web/routes/test_settings_routes_deep_coverage2.py+++ b/tests/web/routes/test_settings_routes_deep_coverage2.py@@ -1111,3 +1111,161 @@ class TestGetBulkSettingsPerSettingError:assert "llm.model" in data["settings"]assert data["settings"]["llm.model"]["exists"] is Falseassert "error" in data["settings"]["llm.model"]+++# ---------------------------------------------------------------------------+# _get_setting_from_session - guard against key=None+# ---------------------------------------------------------------------------+++class TestGetSettingFromSessionNoneKey:+ """_get_setting_from_session must short-circuit when key is None.++ Regression for issue #3800: providers like LM Studio and Llama.cpp+ declare ``api_key_setting = None``. Without the guard, the helper+ would delegate to ``SettingsManager.get_setting(None, ...)``, which+ treats None as "return all settings" — leaking every other provider's+ API key into the auto-discovery loop's ``api_key`` argument.+ """++ def test_none_key_returns_default_without_db_call(self):+ """With key=None, return default and never touch SettingsManager."""+ from local_deep_research.web.routes.settings_routes import (+ _get_setting_from_session,+ )++ app = _create_test_app()+ with _authenticated_client(app) as (client, _):+ with client.session_transaction() as sess:+ sess["username"] = "testuser"+ with app.test_request_context("/"):+ from flask import session as flask_session++ flask_session["username"] = "testuser"+ with patch(f"{MODULE}.get_settings_manager") as mock_get_sm:+ result = _get_setting_from_session(None, "fallback")+ assert result == "fallback"+ mock_get_sm.assert_not_called()+++# ---------------------------------------------------------------------------+# api_get_available_models - api_key_setting=None must not poison api_key+# ---------------------------------------------------------------------------+++class TestApiGetAvailableModelsApiKeySettingNone:+ """Auto-discovered providers with api_key_setting=None get api_key="".++ Regression for issue #3800: LMStudioProvider and LlamaCppProvider+ declare ``api_key_setting = None``. The route must not pass a dict+ of all settings to ``list_models_for_api`` — that would build+ ``Authorization: Bearer <full-settings-dict>`` and leak every cloud+ provider's API key to the local LM Studio/llama-server endpoint.+ """++ def test_none_api_key_setting_passes_empty_string_not_dict(self):+ """When api_key_setting=None, list_models_for_api gets api_key=''.++ This test mocks ``get_settings_manager`` (one layer below the+ helper) rather than ``_get_setting_from_session`` itself. That+ way the production helper actually runs and the ``key is None``+ guard is exercised. The mocked manager simulates the original+ bug — ``get_setting(None, ...)`` returns a settings dict — so+ if the guard were removed, the dict would propagate and the+ final ``isinstance(api_key, str)`` assertion would fail.+ """+ app = _create_test_app()++ mock_provider_class = MagicMock()+ mock_provider_class.api_key_setting = None+ mock_provider_class.url_setting = "llm.lmstudio.url"+ mock_provider_class.list_models_for_api.return_value = [+ {"value": "local-model", "label": "Local Model"}+ ]++ mock_provider_info = MagicMock()+ mock_provider_info.provider_name = "LM Studio"+ mock_provider_info.provider_class = mock_provider_class++ mock_cache_query = MagicMock()+ mock_cache_query.filter.return_value.all.return_value = []++ # Build a mock SettingsManager that simulates the buggy+ # ``SettingsManager.get_setting(None, ...) → full settings dict``+ # behavior. With the helper guard in place, this branch is never+ # reached; without the guard, the dict would leak through.+ buggy_dict = {+ "llm.openai.api_key": "sk-leaked-openai-key",+ "llm.anthropic.api_key": "sk-ant-leaked-key",+ }++ def _sm_get_setting(key, default=None, *_args, **_kwargs):+ if key is None:+ return buggy_dict+ if key == "llm.lmstudio.url":+ return "http://localhost:1234/v1"+ return default if default is not None else ""++ mock_sm = MagicMock()+ mock_sm.get_setting.side_effect = _sm_get_setting++ with _authenticated_client(app) as (client, mock_session):+ mock_session.query.return_value = mock_cache_query+ mock_session.query.return_value.delete.return_value = 0++ with patch(+ "local_deep_research.llm.providers.get_discovered_provider_options",+ return_value=[],+ ):+ with patch(+ f"{MODULE}.get_settings_manager", return_value=mock_sm+ ):+ with patch(f"{MODULE}.safe_get") as mock_safe_get:+ mock_ollama_resp = MagicMock()+ mock_ollama_resp.status_code = 200+ mock_ollama_resp.text = '{"models": []}'+ mock_ollama_resp.json.return_value = {"models": []}+ mock_safe_get.return_value = mock_ollama_resp++ with patch(+ "local_deep_research.llm.providers.discover_providers",+ return_value={"lmstudio": mock_provider_info},+ ):+ resp = client.get(+ f"{SETTINGS_PREFIX}/api/available-models?force_refresh=true"+ )+ assert resp.status_code == 200+ # Critical assertions: api_key reaching the provider is a string,+ # not the buggy settings dict that would leak other providers' keys.+ mock_provider_class.list_models_for_api.assert_called_once()+ call_args = mock_provider_class.list_models_for_api.call_args+ passed_api_key = (+ call_args.args[0]+ if call_args.args+ else call_args.kwargs.get("api_key")+ )+ assert isinstance(passed_api_key, str), (+ f"api_key must be a string, got {type(passed_api_key).__name__}"+ )+ assert not isinstance(passed_api_key, dict)+ assert passed_api_key != buggy_dict+ # Confirm the production helper ran (was not silently mocked away):+ # for the URL setting it must have reached the mock manager.+ assert any(+ call.args and call.args[0] == "llm.lmstudio.url"+ for call in mock_sm.get_setting.call_args_list+ ), (+ "Expected the production helper to call "+ "SettingsManager.get_setting('llm.lmstudio.url', ...); "+ "the mock manager was never invoked, so the test isn't "+ "exercising the production code path."+ )+ # Conversely, the helper must NOT have called get_setting(None, ...)+ # — the guard short-circuits that branch before delegating.+ assert not any(+ call.args and call.args[0] is None+ for call in mock_sm.get_setting.call_args_list+ ), (+ "The helper guard at _get_setting_from_session must short-circuit "+ "key=None to default; instead it delegated to the manager."+ )