Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

fix(security): enforce typed API access toggle (#7002)

LearningCircuita9e5e8a5aa80
diff --git a/changelog.d/+api-toggle-typed-write.security.md b/changelog.d/+api-toggle-typed-write.security.md
new file mode 100644
index 0000000000..65802b3e98
--- /dev/null
+++ b/changelog.d/+api-toggle-typed-write.security.md
@@ -0,0 +1 @@
+Make `app.enable_api=false` reliably disable authenticated REST API access, including when an older setting row was stored as text.
diff --git a/src/local_deep_research/web/routers/api_v1.py b/src/local_deep_research/web/routers/api_v1.py
index 51d96b0913..1d9f2b7bcd 100644
--- a/src/local_deep_research/web/routers/api_v1.py
+++ b/src/local_deep_research/web/routers/api_v1.py
@@ -737,7 +737,7 @@ async def require_api_access(
with get_user_db_session(username) as db_session:
sm = get_settings_manager(db_session, username)
return (
- sm.get_setting("app.enable_api", True),
+ sm.get_bool_setting("app.enable_api", True),
sm.get_setting("app.api_rate_limit", API_RATE_LIMIT_DEFAULT),
)
diff --git a/src/local_deep_research/web/routers/settings.py b/src/local_deep_research/web/routers/settings.py
index 6043ec8d6c..55add60587 100644
--- a/src/local_deep_research/web/routers/settings.py
+++ b/src/local_deep_research/web/routers/settings.py
@@ -96,6 +96,7 @@ from ...utilities.type_utils import unwrap_setting
from ...utilities.url_utils import normalize_url
from ...settings.manager import (
+ _infer_ui_element,
check_env_setting,
get_typed_setting_value,
is_operator_only_setting,
@@ -1405,8 +1406,8 @@ def _reconciled_container_value_for_write(
as sensitive (#6201: this is exactly how the original fix for this
function turned a data-loss bug into a disclosure one). A row's
``ui_element`` can disagree with its actual stored shape -- e.g. a
- ``PUT``-created key with no ``ui_element`` defaults to "text"
- (``models/settings.py``) even when its value is a dict -- so the
+ legacy row or a ``PUT``-created key with explicit ``ui_element="text"``
+ can hold a dict, even though new dict values now infer "json" -- so the
submitted VALUE's shape, once reconciliation has happened, is what
decides whether coercion is safe to run, not the row's declared type.
``coerce_setting_for_write``'s "json"/"multiselect" converters already
@@ -5024,10 +5025,17 @@ def _api_update_setting_sync(data, key, username):
# would flatten it to its Python repr and disclose a
# just-restored secret as a plain string (#6201).
if not _is_reconciled_container:
+ # Infer from the raw JSON type before text coercion.
+ # Otherwise a legacy text row turns False into the
+ # truthy string "False" before set_setting can repair
+ # its checkbox metadata.
+ effective_ui_element = _infer_ui_element(
+ value, db_setting.ui_element
+ )
value = coerce_setting_for_write(
key=db_setting.key,
value=value,
- ui_element=db_setting.ui_element,
+ ui_element=effective_ui_element,
)
# A reconciled secret-bearing container skips
@@ -5208,6 +5216,12 @@ def _api_update_setting_sync(data, key, username):
if field in data:
setting_dict[field] = data[field]
+ # New keys have no registered metadata. Preserve JSON scalar
+ # types so a false API toggle is stored as a checkbox, not a
+ # text row whose "False" value remains truthy on reads.
+ if "ui_element" not in setting_dict:
+ setting_dict["ui_element"] = _infer_ui_element(value)
+
# Creation has no prior value, so the sentinel cannot mean
# "keep the stored secret" the way it does on the update path —
# every occurrence of it, exact match included, is a corrupted
diff --git a/tests/security/test_settings_egress_and_secrets_fastapi.py b/tests/security/test_settings_egress_and_secrets_fastapi.py
index 0747b2a585..47812712b4 100644
--- a/tests/security/test_settings_egress_and_secrets_fastapi.py
+++ b/tests/security/test_settings_egress_and_secrets_fastapi.py
@@ -1115,11 +1115,9 @@ class TestBulkSecretWriteBackAndEcho:
dict-shaped submission did before #6201's original fix, just
through a different encoding of the identical payload.
- The setting must be explicitly ``ui_element="json"`` for the
- string-to-dict coercion (and therefore this bug) to engage at all;
- the sibling test above lets the key default to ``ui_element="text"``,
- under which a JSON string is stored as a literal string and never
- becomes a container.
+ This test explicitly sets ``ui_element="json"`` to keep the
+ string-to-dict coercion premise stable. A text-typed row would store
+ the JSON string literally, rather than decoding a container.
"""
client, username, password = settings_user
key = f"llm.probe_{uuid.uuid4().hex[:6]}.model_kwargs"
@@ -1697,10 +1695,9 @@ class TestBulkSecretWriteBackAndEcho:
the previous round's fix for this exact scenario converted a data
LOSS bug into a secret DISCLOSURE bug.
- A ``PUT``-created key with no ``ui_element`` defaults to "text"
- (``models/settings.py``) -- exactly the row this test creates, the
- same shape ``test_nested_json_leaf_sentinel_round_trip_is_a_noop``
- above uses for its pure round-trip. This test instead performs a
+ An explicitly text-typed row can still hold a dict (for example,
+ legacy metadata); new dict settings now infer ``ui_element="json"``.
+ This test creates the text-typed row and performs a
GENUINE EDIT (one leaf changes, the sibling stays masked), which is
the shape that actually reaches the coercion call: a pure no-op
round-trip short-circuits before it. Every write-back call site ran
@@ -1730,9 +1727,11 @@ class TestBulkSecretWriteBackAndEcho:
assert not DataSanitizer.is_sensitive_setting(PLAIN_SIBLING_LEAF)
assert DataSanitizer.is_sensitive_setting("stop_token")
try:
- # No ui_element supplied -> defaults to "text".
+ # Preserve the legacy text metadata premise despite newer
+ # inference of "json" for newly created dict settings.
create = client.put(
- f"/settings/api/{key}", json={"value": real_value}
+ f"/settings/api/{key}",
+ json={"value": real_value, "ui_element": "text"},
)
assert create.status_code == 201, create.text[:300]
@@ -1880,8 +1879,8 @@ class TestBulkSecretWriteBackAndEcho:
``_save_all_settings_sync`` with an unconditional
``coerce_setting_for_write(key=..., value=value,
ui_element=current_setting.ui_element)``. The row here is
- ``ui_element="text"`` (the default for a PUT-created key with no
- ``ui_element``), whose converter IS ``str``, so the reverted call
+ ``ui_element="text"`` (explicit metadata on this PUT-created key),
+ whose converter IS ``str``, so the reverted call
flattens the just-merged dict to its Python repr and persists the
restored secret as a plain string under a key nothing downstream
treats as sensitive -- which ``redact_value`` then ships back
@@ -1902,9 +1901,10 @@ class TestBulkSecretWriteBackAndEcho:
assert not DataSanitizer.is_sensitive_setting(PLAIN_SIBLING_LEAF)
assert DataSanitizer.is_sensitive_setting("stop_token")
try:
- # No ui_element supplied -> defaults to "text" (str converter).
+ # Keep the str-converter premise with explicit text metadata.
create = client.put(
- f"/settings/api/{key}", json={"value": real_value}
+ f"/settings/api/{key}",
+ json={"value": real_value, "ui_element": "text"},
)
assert create.status_code == 201, create.text[:300]
meta = client.get(f"/settings/api/{key}").json()
@@ -2110,7 +2110,8 @@ class TestBulkSecretWriteBackAndEcho:
real_value = {"stop_token": real_secret, PLAIN_SIBLING_LEAF: "d"}
try:
create = client.put(
- f"/settings/api/{key}", json={"value": real_value}
+ f"/settings/api/{key}",
+ json={"value": real_value, "ui_element": "text"},
)
if create.status_code != 201:
pytest.fail(f"premise: create failed: {create.text[:300]}")
diff --git a/tests/web/routers/test_settings_api.py b/tests/web/routers/test_settings_api.py
index c6dac5d01e..761377ab60 100644
--- a/tests/web/routers/test_settings_api.py
+++ b/tests/web/routers/test_settings_api.py
@@ -146,6 +146,57 @@ class TestSettingsAPI:
json={"value": original_value},
)
+ def test_false_api_setting_blocks_authenticated_api(self, auth_client):
+ """A boolean PUT must reach the API gate as False, not a string."""
+ setting_url = "/settings/api/app.enable_api"
+ previous = auth_client.get(setting_url)
+ original_value = (
+ previous.json().get("value")
+ if previous.status_code == 200
+ else None
+ )
+
+ assert auth_client.get("/api/v1/").status_code == 200
+ try:
+ written = auth_client.put(setting_url, json={"value": False})
+ assert written.status_code in (200, 201), written.text
+ stored = auth_client.get(setting_url)
+ assert stored.status_code == 200
+ assert stored.json()["value"] is False
+ assert stored.json()["ui_element"] == "checkbox"
+ disabled = auth_client.get("/api/v1/")
+ assert disabled.status_code == 403, disabled.text
+ finally:
+ if previous.status_code == 200:
+ auth_client.put(setting_url, json={"value": original_value})
+ else:
+ auth_client.delete(setting_url)
+
+ assert auth_client.get("/api/v1/").status_code == 200
+
+ def test_legacy_text_api_toggle_is_retyped(self, auth_client):
+ """Updating a legacy text row must repair its boolean metadata."""
+ setting_url = "/settings/api/app.enable_api"
+ assert auth_client.get("/api/v1/").status_code == 200
+ try:
+ created = auth_client.put(
+ setting_url, json={"value": "False", "ui_element": "text"}
+ )
+ assert created.status_code == 201, created.text
+ assert auth_client.get(setting_url).json()["ui_element"] == "text"
+ assert auth_client.get("/api/v1/").status_code == 403
+
+ updated = auth_client.put(setting_url, json={"value": False})
+ assert updated.status_code == 200, updated.text
+ stored = auth_client.get(setting_url).json()
+ assert stored["value"] is False
+ assert stored["ui_element"] == "checkbox"
+ assert auth_client.get("/api/v1/").status_code == 403
+ finally:
+ auth_client.delete(setting_url)
+
+ assert auth_client.get("/api/v1/").status_code == 200
+
def test_sensitive_setting_get_is_redacted_and_roundtrip_safe(
self, auth_client
):
diff --git a/tests/web/test_rate_limit_coverage.py b/tests/web/test_rate_limit_coverage.py
index 565d19b824..34c741d0f7 100644
--- a/tests/web/test_rate_limit_coverage.py
+++ b/tests/web/test_rate_limit_coverage.py
@@ -128,8 +128,10 @@ class TestRequireApiAccess:
from local_deep_research.web.routers import api_v1
sm = Mock()
- sm.get_setting.side_effect = lambda key, default=None: {
+ sm.get_bool_setting.side_effect = lambda key, default=None: {
"app.enable_api": enable_api,
+ }.get(key, default)
+ sm.get_setting.side_effect = lambda key, default=None: {
"app.api_rate_limit": rate_limit_value,
}.get(key, default)