~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
"""
Settings Routes Module
This module handles all settings-related HTTP endpoints for the application.
CHECKBOX HANDLING PATTERN:
--------------------------
This module supports TWO submission modes to handle checkboxes correctly:
**MODE 1: AJAX/JSON Submission (Primary - /save_all_settings)**
- JavaScript intercepts form submission with e.preventDefault()
- Checkbox values read directly from DOM via checkbox.checked
- Data sent as JSON: {"setting.key": true/false}
- Hidden fallback inputs are managed but NOT used in this mode
- Provides better UX with instant feedback and validation
**MODE 2: Traditional POST Submission (Fallback - /save_settings)**
- Used when JavaScript is disabled (accessibility/no-JS environments)
- Browser submits form data naturally via request.form
- Hidden fallback pattern CRITICAL here:
* Checked checkbox: Submits checkbox value, hidden input disabled
* Unchecked checkbox: Submits hidden input value "false"
- Ensures unchecked checkboxes are captured (HTML limitation workaround)
**Implementation Details:**
1. Each checkbox has `data-hidden-fallback` attribute → hidden input ID
2. checkbox_handler.js manages hidden input disabled state
3. AJAX mode: settings.js reads checkbox.checked directly (lines 2233-2240)
4. POST mode: Flask reads request.form including enabled hidden inputs
5. Both modes use convert_setting_value() for consistent boolean conversion
**Why Both Patterns?**
- AJAX: Better UX, immediate validation, no page reload
- Traditional POST: Accessibility, progressive enhancement, JavaScript-free operation
- Hidden inputs: Only meaningful for traditional POST, ignored in AJAX mode
This dual-mode approach ensures the app works for all users while providing
optimal experience when JavaScript is available.
"""
from fastapi import APIRouter, Depends, HTTPException, Request
from fastapi.responses import JSONResponse, RedirectResponse
from ..dependencies.auth import (
require_auth,
)
from ..dependencies.rate_limit import (
SETTINGS_RATE_LIMIT,
_user_key,
limiter,
settings_limit,
)
from ..dependencies.threadpool import run_db_sync, run_model_discovery_sync
from ..template_config import templates
from .notes import _log_value_preview
import asyncio
import json
import math
import platform
import re
import threading
import time
from types import SimpleNamespace
from typing import Any, Optional, Tuple, Annotated
from datetime import UTC, datetime, timedelta, timezone
import requests
from loguru import logger
from sqlalchemy.orm import Session
from ...config.constants import DEFAULT_OLLAMA_URL
from ...config.paths import (
get_custom_data_directory,
get_data_directory,
get_encrypted_database_path,
)
from ...constants import DEFAULT_SEARCH_TOOL
from ...database.models.rate_limiting import RateLimitEstimate
from ...database.models.settings import Setting, SettingType
from ...database.session_context import get_user_db_session
from ...database.encrypted_db import db_manager
from ...database.sqlcipher_utils import retry_on_db_lock
from ...defaults import get_default_theme
from ...llm.providers.base import normalize_provider
from ...security.egress.policy import (
DEFAULT_EGRESS_SCOPE,
Decision,
EgressContext,
EgressScope,
PolicyDeniedError,
coerce_policy_bool,
context_from_snapshot,
effective_scope_for_display,
evaluate_llm_endpoint,
parse_user_egress_scope,
resolve_run_primary_engine,
unprotected_egress_allowed,
)
from ...security.egress.validators import (
first_egress_validation_error,
)
from ...utilities.db_utils import get_settings_manager
from ...utilities.type_utils import to_positive_int, unwrap_setting
from ...utilities.url_utils import normalize_url
from ...settings.exceptions import SettingsValueError
from ...settings.manager import (
UI_ELEMENT_TO_SETTING_TYPE,
_infer_ui_element,
check_env_setting,
get_typed_setting_value,
is_operator_only_setting,
is_valid_setting_key,
parse_boolean,
)
from ..services.settings_service import (
create_or_update_setting,
invalidate_settings_caches,
reschedule_document_jobs_if_needed,
reschedule_zotero_jobs_if_needed,
set_setting,
)
from ...security import safe_get
# ``_is_empty_value`` is deliberately imported private (#6201): it is HALF
# of the predicate ``redact_value`` gates masking on -- the other half is
# ``is_sensitive_setting(key, ...)`` (``data_sanitizer.py``), which the
# write-back merge below does NOT consult. The merge must restore a masked
# leaf from at least the set of stored values that got masked in the first
# place -- a merge rule NARROWER than the mask rule's emptiness half turns
# an untouched GET-then-PUT round-trip into an unsatisfiable 400. Sharing
# this one predicate instead of re-deriving it keeps that emptiness half in
# lockstep; it does NOT make the merge equivalent to the mask rule as a
# whole, since the merge restores on the submitted leaf being the sentinel
# regardless of whether that leaf's own sub-key is sensitive -- e.g. a
# stored ``{"port": 19530}`` is never masked (``port`` is not sensitive),
# but a submitted ``{"port": "[REDACTED]"}`` over it is still restored to
# ``19530``. Narrowing ``DEFAULT_SENSITIVE_KEYS`` / ``is_sensitive_setting``
# therefore does NOT narrow what this merge will restore.
from ...security.data_sanitizer import DataSanitizer, _is_empty_value
from ..warning_checks import calculate_warnings
from ..dependencies.json_body import json_body_error, read_json_dict
# Create the router for settings
router = APIRouter(prefix="/settings", tags=["settings"])
# NOTE: Routes use username (not .get()) intentionally.
# Depends(require_auth) guarantees the key exists; direct access fails
# fast if the dependency is ever removed.
# Settings with dynamically populated options (excluded from validation)
DYNAMIC_SETTINGS = ["llm.provider", "llm.model", "search.tool"]
# Settings whose changes trigger a warning recalculation.
WARNING_AFFECTING_KEYS = frozenset(
[
"llm.provider",
"search.tool",
"search.iterations",
"search.questions_per_iteration",
"llm.local_context_window_size",
"llm.context_window_unrestricted",
"llm.context_window_size",
"policy.egress_scope",
"llm.require_local_endpoint",
"embeddings.require_local",
]
)
def _shape_egress_scope_setting(key: str, metadata: Any) -> Any:
"""Gate the operator-disabled "unprotected" escape hatch out of the
egress-scope setting's ``options`` and normalise its displayed
``value`` wherever ``policy.egress_scope`` metadata is served to the
settings UI.
Ports the option-filtering / display-normalisation half of main's
``web/routes/settings_routes.py::_shape_egress_scope_metadata``
(87537d9ec, "fix(security): operator-gate unprotected egress and
harden policy-sensitive consumers", #5148). Without this, the select's
``options`` list (sourced from ``defaults/default_settings.json``,
which unconditionally lists "unprotected") is served to the browser
as-is, so the settings dashboard would offer the escape hatch even
when the operator never set ``LDR_POLICY_ALLOW_UNPROTECTED_EGRESS``.
NOTE: main's ``_shape_egress_scope_metadata`` also overlays an env-var
lock onto ``value``/``editable`` for the setting (a presentation cue
for *any* environment-overridden setting). That is a separate, much
broader feature — this branch's ``SettingsManager.get_all_settings()``
(see ``settings/manager.py``, ~line 977) already overlays
``LDR_*`` env values onto ``value``/``editable`` uniformly for every
setting key, including ``policy.egress_scope`` — so it is intentionally
NOT duplicated here; doing so would just re-apply the same override a
second time.
"""
if key != "policy.egress_scope" or not isinstance(metadata, dict):
return metadata
shaped = dict(metadata)
options = shaped.get("options")
if isinstance(options, list) and not unprotected_egress_allowed():
shaped["options"] = [
option
for option in options
if str(option.get("value") if isinstance(option, dict) else option)
.strip()
.lower()
!= EgressScope.UNPROTECTED.value
]
shaped["value"] = effective_scope_for_display(shaped.get("value"))
return shaped
def _shape_pdf_storage_mode_setting(key: str, metadata: Any) -> Any:
"""Hide the operator-gated unencrypted 'filesystem' PDF storage option.
Ports main's ``_shape_pdf_storage_mode_metadata``
(web/routes/settings_routes.py, fb49985aa, "operator-gate unprotected
egress and harden policy-sensitive consumers", #5148). Mirrors
``_shape_egress_scope_setting``: when the operator gate
``research_library.allow_filesystem_pdf_storage`` is off (the default),
the ``filesystem`` choice is stripped from the
``research_library.pdf_storage_mode`` options served to the settings UI,
leaving the encrypted ``database`` default and ``none``.
Consumption-site coercion (``resolve_pdf_storage_mode``) is the actual
protection; this just keeps a disabled option out of the dropdown so a
user doesn't pick a value that is silently coerced away later.
"""
if key != "research_library.pdf_storage_mode" or not isinstance(
metadata, dict
):
return metadata
options = metadata.get("options")
if not isinstance(options, list):
return metadata
# Lazy import to avoid pulling the research_library package in at
# settings-router module load time.
from ...research_library.services.pdf_storage_manager import (
filesystem_pdf_storage_allowed,
)
if filesystem_pdf_storage_allowed():
return metadata
shaped = dict(metadata)
shaped["options"] = [
option
for option in options
if str(option.get("value") if isinstance(option, dict) else option)
.strip()
.lower()
!= "filesystem"
]
return shaped
def _apply_env_override(
settings_manager, key: str, value: Any, editable: bool
) -> Tuple[Any, bool]:
"""Overlay the LDR_* env-var value/editable state onto a single-key
lookup.
Reuses ``SettingsManager.get_all_settings()`` — the exact overlay
``GET /settings/api`` and ``GET /settings/api/bulk`` already apply via
``check_env_setting``/``get_typed_setting_value`` (see
``settings/manager.py``, ~line 977) — instead of reimplementing that
logic here. Without this, ``GET /settings/api/{key}`` (single-key)
returned the stale DB value with ``editable=True`` for a setting an
operator had pinned via an LDR_* env var, while the bulk endpoints
correctly reported the effective value and ``editable=False`` for the
same key. This is a read/display fix only: writes to an env-locked
setting were already rejected server-side by
``SettingsManager._is_environment_locked`` regardless of this bug.
"""
effective = settings_manager.get_all_settings().get(key)
if effective is None:
return value, editable
return (
effective.get("value", value),
effective.get("editable", editable),
)
def _filter_editable_settings(form_data: dict, db_session: Session) -> dict:
"""Remove operator-locked and non-editable keys from *form_data* in place.
Operator-locked means an ``LDR_*`` environment variable pins the key
(``check_env_setting``). ``SettingsManager.set_setting`` refuses those
writes anyway, but it reports the refusal as a plain ``False``, which
the bulk write paths count as a *failed* save — so any ``LDR_*``
variable made every no-JS form POST flash "Saved with N setting(s)
failing" even though every editable key saved fine. Main dropped them
here instead; this restores that (#5978).
Returns a dict of *all* ``{key: Setting}`` records from the database
so callers can reuse it for further validation (e.g. egress-policy checks).
"""
all_db_settings = {
setting.key: setting for setting in db_session.query(Setting).all()
}
non_editable_keys = [
key
for key in form_data.keys()
if is_operator_only_setting(key)
or check_env_setting(key) is not None
or (key in all_db_settings and not all_db_settings[key].editable)
]
if non_editable_keys:
logger.bind(policy_audit=True).warning(
"Skipping operator-locked or non-editable settings: {}",
non_editable_keys,
)
for key in non_editable_keys:
del form_data[key]
return all_db_settings
def _resolve_model_discovery_policy(
username: str,
) -> tuple[EgressContext, dict[str, Any]]:
"""Resolve the current egress policy before model cache or network access.
Ported from main's ``web/routes/settings_routes.py`` (87537d9ec,
"fix(security): operator-gate unprotected egress and harden
policy-sensitive consumers", #5148); the Flask module was deleted by
the FastAPI migration and this gate came across as a failing test only.
Fails CLOSED: any settings failure (or a non-dict snapshot) raises
``PolicyDeniedError`` instead of falling back to "allow". The previous
``_model_list_local_only`` helper returned False (allow) on error, so a
settings outage silently downgraded a local-only user to "list every
cloud provider" — which reads their stored API key and sends it to the
provider's model-listing endpoint.
"""
settings_snapshot = None
try:
with get_user_db_session(username) as db_session:
if db_session:
settings_manager = get_settings_manager(db_session, username)
settings_snapshot = settings_manager.get_settings_snapshot(
strict=True
)
except PolicyDeniedError:
raise
except Exception:
logger.bind(policy_audit=True).warning(
"available-model policy settings unavailable"
)
raise PolicyDeniedError(
Decision(False, "settings_unavailable"),
target="available_models",
) from None
if not isinstance(settings_snapshot, dict):
raise PolicyDeniedError(
Decision(False, "settings_unavailable"),
target="available_models",
)
scope_raw = check_env_setting("policy.egress_scope")
if scope_raw is None:
scope_raw = settings_snapshot.get(
"policy.egress_scope", DEFAULT_EGRESS_SCOPE
)
if str(scope_raw).strip().lower() == EgressScope.BOTH.value:
scope_raw = EgressScope.ADAPTIVE.value
parse_user_egress_scope(scope_raw)
primary = resolve_run_primary_engine(
settings_snapshot, default=DEFAULT_SEARCH_TOOL
)
return (
context_from_snapshot(
settings_snapshot,
primary,
username=username,
),
settings_snapshot,
)
def _model_discovery_provider_decision(
provider: str,
policy_context: EgressContext,
settings_snapshot: dict[str, Any],
) -> Decision:
"""Return the policy decision for a provider's configured endpoint."""
if not policy_context.require_local_llm:
return Decision(True, "no_local_requirement")
decision = evaluate_llm_endpoint(
normalize_provider(provider),
policy_context,
settings_snapshot=settings_snapshot,
)
if not decision.allowed:
logger.bind(policy_audit=True).info(
"available-model provider denied by egress policy",
provider=normalize_provider(provider),
reason=decision.reason,
)
return decision
def _model_discovery_provider_allowed(
provider: str,
policy_context: EgressContext,
settings_snapshot: dict[str, Any],
) -> bool:
"""Return whether a provider's configured endpoint is allowed to list models."""
return _model_discovery_provider_decision(
provider, policy_context, settings_snapshot
).allowed
# Maps the policy's internal denial reason onto a short phrase describing
# what the user would have to change. Anything unmapped falls back to the
# control clause alone rather than leaking a raw reason token into the UI.
_PROVIDER_DENIAL_CAUSES = {
"provider_cloud_only": "cloud-only provider",
"provider_url_unset": "no endpoint URL configured",
"url_malformed": "endpoint URL is malformed",
"provider_remote": "endpoint URL is not local",
}
def _configured_egress_scope(
settings_snapshot: dict[str, Any] | None,
) -> EgressScope | None:
"""Return the scope the user actually selected, or None if unknown.
``EgressContext.scope`` is the RESOLVED scope: ``context_from_snapshot``
runs ``_resolve_adaptive_scope``, so the default ``adaptive`` selection
is stored as ``PRIVATE_ONLY`` whenever the primary search engine is
local. Naming that resolved value in the UI sends the user to a control
they never touched — their Egress Scope select still reads "Adaptive".
The configured value survives only on the settings snapshot, so read it
back from there, env-first — the same precedence
``_resolve_model_discovery_policy`` and ``context_from_snapshot`` use
for this setting.
"""
raw = check_env_setting("policy.egress_scope")
if raw is None:
if not isinstance(settings_snapshot, dict):
return None
raw = unwrap_setting(
settings_snapshot.get("policy.egress_scope", DEFAULT_EGRESS_SCOPE)
)
# Retired `both` is coerced to the protective default, as every other
# reader of this setting does (see context_from_snapshot).
if str(raw).strip().lower() == EgressScope.BOTH.value:
raw = EgressScope.ADAPTIVE.value
try:
return parse_user_egress_scope(raw, disabled_unprotected="adaptive")
except PolicyDeniedError:
return None
def _provider_disabled_reason(
decision: Decision,
policy_context: EgressContext,
settings_snapshot: dict[str, Any] | None,
) -> str:
"""Build the user-facing reason a provider is greyed out in the dropdown.
``require_local_llm`` has three possible origins and the UI has to name
the right one, or the user goes hunting for a control that won't help:
an operator env lock, the ``private_only`` egress scope (which forces
the flag on at ``context_from_snapshot``), or the user's own
"Require Local LLM Endpoint" checkbox.
The scope arm has a fourth case hiding inside it: ``private_only`` may be
what ``adaptive`` RESOLVED to rather than what the user chose, so the
message is built from ``settings_snapshot`` — the same snapshot the
context was built from — and names the selection the user can actually
see. The parameter is required rather than defaulted: a caller with no
snapshot must say so with an explicit ``None`` (falling back to the
resolved scope) instead of silently getting the wrong control named.
"""
env_value = check_env_setting("llm.require_local_endpoint")
# Truthiness must match what the policy enforces, not HTML-checkbox
# semantics: parse_boolean() calls "enabled" / "T" / "y" True, while
# context_from_snapshot() computes require_local_llm with the policy's
# own {"true","1","yes","on"} vocabulary. The looser parser reported a
# server lock that was not actually in force.
env_locked = env_value is not None and coerce_policy_bool(env_value)
notes = []
if not env_locked and policy_context.scope == EgressScope.PRIVATE_ONLY:
if _configured_egress_scope(settings_snapshot) == EgressScope.ADAPTIVE:
control = 'Blocked by egress scope "Adaptive"'
notes.append(
"resolved to Private only from your primary search engine"
)
else:
control = 'Blocked by egress scope "Private only"'
else:
control = 'Blocked by "Require Local LLM Endpoint"'
cause = _PROVIDER_DENIAL_CAUSES.get(decision.reason)
if cause:
notes.append(cause)
if env_locked:
notes.append("locked by the server")
return f"{control} ({'; '.join(notes)})" if notes else control
def _provider_options_for_snapshot(options, policy_context, policy_snapshot):
"""Describe provider availability without fetching models or credentials."""
provider_options = []
for option in options:
entry = dict(option)
decision = _model_discovery_provider_decision(
option["value"], policy_context, policy_snapshot
)
entry["disabled"] = not decision.allowed
entry["disabled_reason"] = (
_provider_disabled_reason(decision, policy_context, policy_snapshot)
if not decision.allowed
else None
)
provider_options.append(entry)
return provider_options
def _get_setting_from_session(key: str | None, username: str, 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"; this route helper fetches
a single named setting and must not inherit that bulk-read semantic.
Without the guard, callers iterating providers that declare
``api_key_setting = None`` (LM Studio, Llama.cpp) would receive a dict
of every setting — leaking other providers' API keys.
"""
if key is None:
return default
with get_user_db_session(username) as db_session:
if db_session:
settings_manager = get_settings_manager(db_session, username)
return settings_manager.get_setting(key, default)
return default
def _model_discovery_settings_unchanged(db_session, fetched_settings):
"""Compare discovery inputs with fresh rows in the cache write transaction."""
if not fetched_settings:
return True
rows = (
db_session.query(Setting)
.filter(Setting.key.in_(fetched_settings))
.populate_existing()
.all()
)
settings = {row.key: row for row in rows}
for key, fetched_value in fetched_settings.items():
row = settings.get(key)
current_value = get_typed_setting_value(
key,
row.value if row is not None else None,
str(row.ui_element) if row is not None else "text",
default="",
check_env=True,
)
if current_value != fetched_value:
return False
return True
def validate_setting(
setting: Setting, value: Any
) -> Tuple[bool, Optional[str]]:
"""
Validate a setting value based on its type and constraints.
Args:
setting: The Setting object to validate against
value: The value to validate
Returns:
Tuple of (is_valid, error_message)
"""
if setting.key == "search.fetch.summary_input_max_length":
try:
to_positive_int(value)
except ValueError:
return False, "Value must be a positive integer"
# Validate the exact summary integer before generic number conversion
# or the blank-input handling for other optional numeric settings.
raw_value = value
numeric_ui = setting.ui_element in ("number", "slider", "range")
# Blank form inputs explicitly clear optional numeric settings; they are
# normalized to None on write, not used as a fallback for bad numbers.
if numeric_ui and (
raw_value is None
or (isinstance(raw_value, str) and not raw_value.strip())
):
return True, None
try:
value = get_typed_setting_value(
key=str(setting.key),
value=value,
ui_element=str(setting.ui_element),
default=None,
check_env=False,
)
except SettingsValueError as error:
if numeric_ui:
return False, "Value must be a number"
if setting.ui_element == "checkbox":
return False, "Value must be a boolean"
return False, error.reason
# Validate based on UI element type
if setting.ui_element == "checkbox":
# After conversion, should be boolean
if not isinstance(value, bool):
return False, "Value must be a boolean"
elif setting.ui_element in ("number", "slider", "range"):
# After conversion, should be numeric
if (
isinstance(raw_value, bool)
or isinstance(value, bool)
or not isinstance(value, (int, float))
or (isinstance(value, float) and not math.isfinite(value))
):
return False, "Value must be a number"
# Check min/max constraints if defined
if setting.min_value is not None and value < setting.min_value:
return False, f"Value must be at least {setting.min_value}"
if setting.max_value is not None and value > setting.max_value:
return False, f"Value must be at most {setting.max_value}"
elif setting.ui_element == "select":
# Check if value is in the allowed options
if setting.options:
# Skip options validation for dynamically populated dropdowns
if setting.key not in DYNAMIC_SETTINGS:
allowed_values = [
opt.get("value") if isinstance(opt, dict) else opt
for opt in list(setting.options) # type: ignore[arg-type]
]
if value not in allowed_values:
return (
False,
f"Value must be one of: {', '.join(str(v) for v in allowed_values)}",
)
# All checks passed
return True, None
def _strict_read_rejection(key: str, value: Any, ui_element: Any) -> str | None:
"""Return why a strict settings read would reject this row, or None.
A write must not store a row that every effective read of the account
then refuses with ``SettingsValueError``. This applies the read's own
rules: the type must be supported and the value must convert to it.
Pass the value and the ui_element exactly as they will be stored. The
reason never contains the value.
"""
try:
get_typed_setting_value(
key=key,
value=value,
ui_element=ui_element,
default=None,
check_env=False,
)
except SettingsValueError as error:
return error.reason
return None
def coerce_setting_for_write(key: str, value: Any, ui_element: str) -> Any:
"""Coerce an incoming value to the correct type before writing to the DB.
All web routes that save settings should use this function to ensure
consistent type conversion.
No JSON pre-parsing (``json.loads``) is needed here because:
- ``get_typed_setting_value`` already parses JSON strings internally
via ``_parse_json_value`` (for ``ui_element="json"``) and
``_parse_multiselect`` (for ``ui_element="multiselect"``).
- For JSON API endpoints, ``await request.json()`` already delivers
dicts/lists as native Python objects.
- For ``ui_element="text"``, pre-parsing would corrupt data: a JSON
string like ``'{"k": "v"}'`` would become a dict, then ``str()``
would produce ``"{'k': 'v'}"`` (Python repr, not valid JSON).
"""
if key == "search.fetch.summary_input_max_length":
try:
return to_positive_int(value)
except ValueError:
# Preserve invalid input for validate_setting to reject, rather
# than losing a fractional part or treating it as optional/null.
return value
# check_env=False: we are persisting a user-supplied value, not reading
# from an environment variable override. check_env=True (the default)
# would silently replace the user's value with an env var, which is
# incorrect on the write path.
numeric_ui = ui_element in ("number", "slider", "range")
if numeric_ui and isinstance(value, str) and not value.strip():
return None
if numeric_ui and isinstance(value, bool):
# bool is an int subclass, so float(True) would otherwise become 1 and
# erase the evidence validate_setting needs to reject type confusion.
return value
try:
coerced = get_typed_setting_value(
key=key,
value=value,
ui_element=ui_element,
default=None,
check_env=False,
)
except SettingsValueError:
# Preserve the submitted input so validate_setting can return the
# route's normal validation error. Never replace it with None/default,
# which would turn a malformed value into an accepted optional value.
return value
# Canonicalise the egress scope on the write path: the select options
# are exact lowercase strings, so a value arriving with surrounding
# whitespace or different casing (" STRICT ") would otherwise be
# rejected by validate_setting instead of being stored as "strict".
if key == "policy.egress_scope" and isinstance(coerced, str):
return coerced.strip().lower()
return coerced
# Namespace validation for new setting creation via the web API (ported
# from main's Flask settings_routes). Keys starting with any ALLOWED
# prefix may be created; any prefix in BLOCKED takes precedence and is
# rejected even if it also matches an allowed prefix. Existing keys
# (updates) bypass this check — it only applies to creation of new DB
# rows through the three write routes.
ALLOWED_SETTING_PREFIXES = frozenset(
{
"app.",
"backup.",
"benchmark.",
"chat.",
"database.",
"document_scheduler.",
"embeddings.",
"focused_iteration.",
"general.",
"langgraph_agent.",
"llm.",
"local_search_",
"news.",
"notifications.",
"rag.",
"rate_limiting.",
"report.",
"research_library.",
"search.",
"ui.",
"web.",
"zotero.",
}
)
BLOCKED_SETTING_PREFIXES = frozenset(
{
"auth.",
"bootstrap.",
"db_config.",
"security.",
"server.",
"testing.",
}
)
# Recursion cap for EVERY container helper below -- the sentinel/depth
# scanners, the merge, the positional-rebinding gate
# (``_non_sentinel_fields_match``) and the type-aware equality it bottoms
# out in (``_values_equal``). A helper in this family without the cap is
# a 500 waiting to happen even when the others have it, because
# ``_container_embeds_sentinel`` answers True unconditionally past its own
# cap and therefore KEEPS the callers walking a too-deep value (#6201
# round 7). json.loads accepts
# JSON nested roughly 900 levels deep, but these helpers recurse once per
# nesting level and hit Python's own call-stack RecursionError somewhere
# between depth ~499 and ~600 (exact threshold depends on what else is on
# the stack) -- well short of what a malicious/malformed payload can hand
# them. A real setting's JSON value is never more than a handful of levels
# deep, so a cap far below the crash point (and far above any legitimate
# value) lets a too-deep payload be rejected cleanly by the callers below
# instead of surfacing as an opaque 500 through the routes' broad
# ``except Exception``.
_MAX_CONTAINER_DEPTH = 64
def _container_embeds_sentinel(
value: object, redaction_text: str, _depth: int = 0
) -> bool:
"""True when a dict/list contains the redaction sentinel as a substring
of ANY string leaf, exact-leaf-match or partially spliced into one.
Recursion counterpart of the ``str`` guards' ``redaction_text in value``
check, used for a container value under a setting that only matches the
broadened suffix arm (see ``_force_redact_strings``, which is what
produces such a container on the read side: every non-empty string leaf
becomes the bare sentinel, regardless of its own sub-key name). bool/int/
None leaves are never masked and so can never embed it.
Past ``_MAX_CONTAINER_DEPTH`` levels this conservatively returns True
(see ``_MAX_CONTAINER_DEPTH``'s comment) rather than recursing further:
a value nested that deep cannot be proven safe, and every caller here
treats "embeds the sentinel" as the signal to reject the write with a
400, which is the outcome we want for a pathological payload too.
"""
if _depth > _MAX_CONTAINER_DEPTH:
return True
if isinstance(value, str):
return redaction_text in value
if isinstance(value, dict):
return any(
_container_embeds_sentinel(sub_val, redaction_text, _depth + 1)
for sub_val in value.values()
)
if isinstance(value, list):
return any(
_container_embeds_sentinel(item, redaction_text, _depth + 1)
for item in value
)
return False
def _container_exceeds_max_depth(value: object, _depth: int = 0) -> bool:
"""True when *value* nests a dict/list deeper than
``_MAX_CONTAINER_DEPTH``, independent of whether it contains the
redaction sentinel anywhere.
Checked ahead of the sentinel guards so a too-deep payload with NO
sentinel in it gets its own error instead of
``_redaction_sentinel_error``'s "contains the redaction placeholder"
message. ``_container_embeds_sentinel`` and ``_merge_redacted_container``
both conservatively treat anything past the cap as "embeds it" /
"unresolvable" regardless of actual content -- the right call for
deciding to reject a payload that can't be proven safe, but the wrong
reason to report when nothing in it actually matched the sentinel.
"""
if _depth > _MAX_CONTAINER_DEPTH:
return True
if isinstance(value, dict):
return any(
_container_exceeds_max_depth(sub_val, _depth + 1)
for sub_val in value.values()
)
if isinstance(value, list):
return any(
_container_exceeds_max_depth(item, _depth + 1) for item in value
)
return False
def _container_too_deep_error() -> str:
"""Explain the 400 raised when a dict/list value nests deeper than
``_MAX_CONTAINER_DEPTH`` -- a distinct condition from embedding the
redaction sentinel and reported with its own message (see
``_container_exceeds_max_depth``), instead of the misleading
"contains the redaction placeholder" wording a too-deep payload with
no sentinel in it used to get by reusing ``_redaction_sentinel_error``.
"""
return (
"Value is nested too deeply to validate "
f"(max {_MAX_CONTAINER_DEPTH} levels) — flatten it before saving."
)
def _container_rejection_error(ui_element: str | None, value: object) -> str:
"""Pick the right 400 message for a rejected dict/list write: the
depth-cap message when *value* nests past ``_MAX_CONTAINER_DEPTH``
(the cap itself is why it was rejected, whether or not it happens to
also contain the sentinel), otherwise the usual
redaction-sentinel message.
"""
if isinstance(value, (dict, list)) and _container_exceeds_max_depth(value):
return _container_too_deep_error()
return _redaction_sentinel_error(ui_element)
def _values_equal(a: object, b: object, _depth: int = 0) -> bool:
"""Type-aware equality for comparing a submitted/merged value against
its stored counterpart.
Plain ``==`` treats ``1 == True`` as equal (``bool`` is an ``int``
subclass), so a checkbox submitted as ``1`` over a stored ``True`` --
or ``{"enabled": 1}`` over a stored ``{"enabled": True}`` -- would
look byte-for-byte identical to
``_resolve_container_secret_write``'s no-op check and silently
discard a genuine type change instead of persisting it (#6201).
``bool`` is therefore checked FIRST, before the numeric case, because
it IS an ``int``; dict/list are walked structurally rather than
compared with their own ``==`` so a type mismatch nested inside a
container is caught too, not just at the top level.
``int`` vs ``float`` is deliberately NOT a difference. This predicate
also decides ``_non_sentinel_fields_match``, the gate that must see
every visible field of a list item unchanged before a masked secret
is restored by position -- and requiring ``type(a) is type(b)`` there
made an ordinary browser round-trip UNSATISFIABLE. A stored
``[{"url": "a", "api_key": ..., "timeout": 30.0}, {...}]`` is served
to the client with both keys masked; JavaScript has no ``30.0`` (its
only number type is a double that serializes as ``30``), and
``settings.js`` additionally ``parseInt``s a decimal-free numeric
before submitting. The client therefore CANNOT echo back a value
``type(a) is type(b)`` accepts, so every edit to a >=2-item list
carrying a masked secret 400'd with "contains the redaction
placeholder" no matter what the user did (#6201 round 5). Comparing
numerics by value costs nothing the guard actually relies on: an
attacker cannot use "same number, other numeric type" to disguise a
reorder, because two list entries that differ ONLY in whether a
number is stored as ``30`` or ``30.0`` are indistinguishable to any
JSON client to begin with.
Depth-capped like the other container walkers (see
``_MAX_CONTAINER_DEPTH``): past the cap this answers "not equal"
rather than recursing into a stack overflow. That is the fail-closed
answer for both callers -- ``_non_sentinel_fields_match`` treats it as
"cannot prove this position is unchanged" (so a positional secret
restore is refused) and ``_resolve_container_secret_write`` treats it
as "not a no-op" (so nothing is silently swallowed). Without the cap a
~7 KB payload nested ~1000 levels deep against a stored value of the
same shape raised an uncaught ``RecursionError`` that the write routes'
broad ``except Exception`` turned into a 500 (#6201 round 7).
"""
if _depth > _MAX_CONTAINER_DEPTH:
return False
if isinstance(a, dict) or isinstance(b, dict):
if not (isinstance(a, dict) and isinstance(b, dict)):
return False
if a.keys() != b.keys():
return False
return all(_values_equal(a[k], b[k], _depth + 1) for k in a)
if isinstance(a, list) or isinstance(b, list):
if not (isinstance(a, list) and isinstance(b, list)):
return False
if len(a) != len(b):
return False
return all(_values_equal(x, y, _depth + 1) for x, y in zip(a, b))
# bool BEFORE the numeric case: `bool` is an `int`, so a plain `==`
# here would call `1` unchanged from a stored `True`.
if isinstance(a, bool) or isinstance(b, bool):
return type(a) is type(b) and a == b
# Neither side is a bool by now, so `int`/`float` compare by VALUE:
# `30 == 30.0` is the same number, and a JSON client has no way to
# tell the two apart (see the docstring).
return a == b
def _non_sentinel_fields_match(
value: object,
stored_value: object,
redaction_text: str,
_depth: int = 0,
) -> bool:
"""True when every leaf of *value* that is NOT the redaction sentinel
equals ``stored_value``'s leaf at the same path -- i.e. nothing
visible changed except the masked leaf(s).
Used ONLY to gate positional secret restoration inside a LIST (see the
list branch of ``_merge_redacted_container``): a same-length
permutation of a list of dicts is indistinguishable from an in-place
edit by position alone -- ``zip()`` pairs each submitted item with
whatever stored item shares its index, not with the item it actually
came from. Given stored ``[{url:a,api_key:K1},{url:b,api_key:K2}]``, a
client that reorders the two entries and resubmits both with their
(masked) ``api_key`` untouched would otherwise have K1 silently
rebound to ``b`` and K2 to ``a`` -- restoring the WRONG secret under
each url, not the one it actually belonged to (#6201). Requiring every
visible field at that index to match before trusting the position
catches this: a genuine in-place edit leaves everything but the
secret leaf(s) unchanged, so it still matches; a reorder does not.
This deliberately does NOT extend the "edit a sibling next to a
restored secret" allowance ``_merge_redacted_container`` documents for
a single dict/object -- that allowance is safe there because there is
only one candidate object to restore into. Inside a list, the same
allowance would make a sibling edit indistinguishable from a reorder,
which is exactly the hole this closes. The accepted consequence: an
ordinary edit to a NON-secret sibling field of a list item that also
carries an untouched masked secret at the same index is rejected
along with a genuine reorder -- the caller must split that into two
writes (clear/replace the secret first, or edit the sibling via a
request that doesn't also carry the sentinel) rather than combining
them in one PUT.
Depth-capped like every other container walker here (see
``_MAX_CONTAINER_DEPTH``). Past the cap this answers False -- "nothing
proves this position still holds the same entry" -- which makes the
caller reject the item rather than positionally rebind a secret into
a container it could not finish inspecting. This helper and
``_values_equal`` were the last two in the merge path without a cap,
and ``_merge_redacted_container``'s list branch called this one with
no depth at all: a ~7 KB list whose first item nested ~1000 levels
deep against a stored list of the same shape raised an uncaught
``RecursionError`` and surfaced as a 500 through the write routes'
broad ``except Exception`` -- the exact outcome ``_MAX_CONTAINER_DEPTH``
exists to prevent (#6201 round 7). Note the depth cap alone does not
end the walk: ``_container_embeds_sentinel`` answers True
unconditionally past its own cap, so this gate is still consulted for
a too-deep item and must terminate on its own.
"""
if _depth > _MAX_CONTAINER_DEPTH:
return False
if isinstance(value, str) and value == redaction_text:
return True
if isinstance(value, dict):
if not isinstance(stored_value, dict):
return False
# The submitted item's visible keys must exactly match the stored
# item's keys, not just be a subset of them. A subset check lets a
# client RENAME or DROP a visible field (e.g. resubmit ``url`` as
# ``endpoint``, or omit it) to make an otherwise-mismatched item
# look like a match: the renamed/added key isn't in ``stored_value``
# so a subset walk would skip it, and the dropped key is simply
# never visited from ``value.items()``. Either way position gets
# trusted with nothing left to disprove it -- the exact bypass this
# function exists to close (#6201 round 3 follow-up). Requiring
# equal key sets also matches this module's own rule that adding a
# field to a list item alongside a masked secret must be split into
# two writes, rather than silently letting the extra field ride
# along as if it always existed at this position.
if value.keys() != stored_value.keys():
return False
for sub_key, sub_val in value.items():
if not _non_sentinel_fields_match(
sub_val, stored_value[sub_key], redaction_text, _depth + 1
):
return False
return True
if isinstance(value, list):
if not isinstance(stored_value, list) or len(stored_value) != len(
value
):
return False
return all(
_non_sentinel_fields_match(
sub_val, sub_stored, redaction_text, _depth + 1
)
for sub_val, sub_stored in zip(value, stored_value)
)
return _values_equal(value, stored_value, _depth)
def _merge_redacted_container(
value: object, stored_value: object, redaction_text: str, _depth: int = 0
) -> Tuple[object, bool]:
"""Merge a dict/list write against its stored counterpart, restoring
the real secret under every leaf that is EXACTLY the redaction
sentinel while keeping every other leaf's submitted value as-is -- so
editing a non-secret sibling (or leaving a DIFFERENT secret leaf
untouched) is saved instead of the whole container being rejected.
``redact_value`` (``security/data_sanitizer.py``) masks a container by
SUB-KEY: in a MIXED container -- e.g. ``{"api_key": "sk-...",
"description": "My engine", "requires_api_key": true}`` -- only the
sensitive-named leaf becomes the sentinel; ordinary siblings stay
plain. A caller that GETs, edits ``description``, and PUTs the result
back therefore submits a container where exactly one leaf is the
sentinel and the rest are ordinary values -- not the "every maskable
leaf is the sentinel" shape round 5's fix required of the WHOLE
container before treating it as anything but a corrupted edit.
Rejecting that outright turns a legitimate edit into an unsatisfiable
400: the client can never construct a request this endpoint will
accept, because it cannot see the real secret to resubmit it and any
masked-leaf resubmission was treated as "embeds the sentinel". This
function resolves it leaf-by-leaf instead of all-or-nothing.
ACCEPTED RISK, DELIBERATE (post-#6201 review, item a): this leaf-by-
leaf merge means a caller who has never seen the real secret can still
edit a NON-secret sibling of it in the SAME write -- e.g. change
``search.engine.web.<engine>.url`` while ``api_key`` stays
``[REDACTED]`` -- and the merge restores the real key under the NEW
url. A round of this feature's own review (round 5) rejected mixed
containers outright specifically to prevent this; this round reverses
that call because the outright rejection made the endpoint
unsatisfiable for the overwhelmingly common case (any GET-then-edit of
a mixed container at all, secret untouched). This is a real,
consciously-accepted trade rather than an oversight: egress/SSRF
validation for registered settings (``security/egress/validators.py``)
keys off FIXED, known setting names, not the contents of arbitrary
user-defined JSON, so this does not by itself hand a caller a new way
to bypass egress policy for a setting the validators inspect. It DOES
mean a masked secret can end up silently repointed at a different
destination than the one it was originally saved under, without the
caller ever needing to know the secret's value. If that trade
ever needs tightening, the narrowing applied to LIST items below (see
the list branch's docstring section) -- requiring every visible field
at a position to match before trusting a positional secret restore --
is the template: the same "verify nothing else changed" check could be
applied to a bare dict's siblings too, at the cost of reintroducing
the unsatisfiable-400 problem this round fixed.
Returns ``(merged_value, rejected)``. ``rejected`` is True when a leaf
cannot be resolved safely:
* the leaf equals the sentinel exactly, but ``stored_value`` is
itself empty (absent, ``""``, ``" "``, ``None``, ``[]`` or ``{}``)
at that path -- there is nothing to "keep", so persisting it would
write the literal placeholder text as the value. This checks only
``stored_value``'s emptiness, the same half of ``redact_value``'s
gate that ``_is_empty_value`` implements -- it does NOT also check
that the leaf's own sub-key is sensitive, so the restore set is a
SUPERSET of the mask set: a stored ``{"port": 19530}`` is never
masked on read (``port`` is not sensitive), but a submitted
``{"port": "[REDACTED]"}`` over it still restores ``19530`` here.
Narrowing ``DEFAULT_SENSITIVE_KEYS`` / ``is_sensitive_setting``
therefore does not narrow what this merge will restore;
* the leaf merely CONTAINS the sentinel as a substring without being
an exact match (e.g. a stale client's ``"[REDACTED],new-value"``)
-- an edit, but a corrupted one that would splice the placeholder
text into the stored value, the same corrupted-edit case the
scalar arm of ``_embeds_redaction_sentinel`` rejects.
A list is walked positionally only when the submitted and stored lists
are the same length; a length change means there is no reliable
correspondence between items, so any sentinel occurring in it can't be
resolved and the whole list is rejected the same way an orphaned leaf
is (matching the "can't confirm, so treat as unresolvable" stance the
other container helpers take). A dict key absent from ``stored_value``
is not itself an error -- it is an ordinary new field unless its own
value happens to be the sentinel, which the orphan case above catches.
Equal length is NOT sufficient on its own to trust a list's positions,
though: a same-length PERMUTATION of a list of dicts is invisible to a
plain ``zip()`` walk. Given stored ``[{url:a,api_key:K1},
{url:b,api_key:K2}]``, a client that swaps the two entries and
resubmits both with their ``api_key`` still masked would otherwise get
K1 silently restored under ``b`` and K2 under ``a`` -- the wrong
secret rebound to the wrong entry, not a rejection (#6201). Before
restoring a sentinel-bearing dict/list item positionally, this walks
it through ``_non_sentinel_fields_match`` first: every field at that
index NOT equal to the sentinel must match the stored item at the same
index, proving nothing but the masked leaf(s) changed there. A
mismatch means the position can't be trusted to identify the same
real-world entry the secret was read from, so that item's sentinel
leaves are treated as unresolvable (rejected) rather than restored
into what may be a different entry. This intentionally narrows the
"edit a sibling next to a restored secret" allowance documented above
to the single-object case -- inside a list it is indistinguishable
from a reorder, so it isn't extended there.
EXCEPTION: a single-element list (``len(value) == 1``) skips this
sibling-match gate entirely. The gate exists solely to rule out a
same-length reorder, and a list of one has no other position for its
one item to have come from or gone to -- there is no reorder for a
sibling edit to be confused with, so the "edit a sibling next to a
restored secret" allowance the single-object dict case gets above
applies here too.
"""
# NOTE (fragility, deliberate): past the cap this does NOT reject on its
# own -- it returns whatever ``_container_embeds_sentinel`` says, and that
# helper's own cap makes it answer True unconditionally past this depth.
# So the clean 400 a too-deep payload gets today is produced by that
# helper's fail-closed default, not by this line. The composition is
# correct (verified at 65/900/3000 levels), but it means a future edit
# that makes ``_container_embeds_sentinel`` return a real answer past the
# cap -- or drops its cap because "the callers already cap" -- would
# silently turn a too-deep payload into an ACCEPTED merge here rather
# than a rejection, with no test naming this line. Anything that touches
# either cap must re-check this pair together; ``return value, True`` is
# the equivalent that does not depend on the other helper, kept as a
# call rather than a literal only so the two stay visibly coupled.
if _depth > _MAX_CONTAINER_DEPTH:
return value, _container_embeds_sentinel(value, redaction_text, _depth)
if isinstance(value, dict):
stored_dict = stored_value if isinstance(stored_value, dict) else {}
merged: dict = {}
rejected = False
for sub_key, sub_val in value.items():
merged_val, sub_rejected = _merge_redacted_container(
sub_val, stored_dict.get(sub_key), redaction_text, _depth + 1
)
merged[sub_key] = merged_val
rejected = rejected or sub_rejected
return merged, rejected
if isinstance(value, list):
if isinstance(stored_value, list) and len(stored_value) == len(value):
merged_list = []
rejected = False
for sub_val, sub_stored in zip(value, stored_value):
# A single-element list has exactly one possible position
# for its one item -- there is no OTHER index a reorder
# could have moved it from or to, so the "position can't
# be trusted" rationale below (which exists to catch a
# same-length reorder) cannot apply. Skip the sibling-
# match gate entirely for len == 1 rather than rejecting
# an ordinary sibling edit next to a masked secret that
# has no reorder to be confused with.
if (
len(value) != 1
and _container_embeds_sentinel(
sub_val, redaction_text, _depth + 1
)
and not _non_sentinel_fields_match(
sub_val, sub_stored, redaction_text, _depth + 1
)
):
# A visible (non-sentinel) field at this index differs
# from the stored item at the same index -- position
# cannot be trusted to identify the same entry the
# secret leaf was read from (e.g. a same-length
# reorder). Reject rather than positionally rebind the
# secret to a possibly different entry (#6201).
merged_list.append(sub_val)
rejected = True
continue
merged_val, sub_rejected = _merge_redacted_container(
sub_val, sub_stored, redaction_text, _depth + 1
)
merged_list.append(merged_val)
rejected = rejected or sub_rejected
return merged_list, rejected
return value, _container_embeds_sentinel(value, redaction_text, _depth)
if isinstance(value, str):
if value == redaction_text:
# Restore from ANY non-empty stored value, not just a string
# (#6201/#6213 item c). ``redact_value`` masks a nested leaf to
# the bare sentinel for any non-empty value whose sub-key is an
# exact ``DEFAULT_SENSITIVE_KEYS`` match -- a list, dict, int or
# bool included -- so requiring ``isinstance(stored_value, str)``
# here made the write-back rule STRICTER than the masking rule:
# for all 18 exact sensitive leaf names, a stored list/dict/int/
# bool leaf was masked on GET and then refused on PUT, an
# unsatisfiable 400 the client could never construct a passing
# request for (it cannot see the value the GET collapsed to one
# string), and on ``save_all_settings`` a rejection rolls back
# the WHOLE batch. Mirroring ``_is_empty_value`` -- the exact
# gate ``redact_value`` masks on -- makes the round-trip a no-op
# again. Every other rejection is unchanged: an empty stored
# value ("", " ", None, [], {}) was never masked, so a sentinel
# over it is still an orphan (below); a missing sub-key arrives
# here as ``None`` from ``stored_dict.get(...)`` and is still
# rejected; and a sentinel EMBEDDED in a longer string is still
# the corrupted-edit case.
if not _is_empty_value(stored_value):
return stored_value, False
return value, True
if redaction_text in value:
return value, True
return value, False
return value, False
def _resolve_container_secret_write(
value: object, stored_value: object, redaction_text: str
) -> Tuple[object, bool, bool]:
"""Decide the outcome of a dict/list write that may carry the
redaction sentinel.
Returns ``(effective_value, is_noop, is_rejected)``:
* No sentinel anywhere in *value* -- pass it through untouched
(``is_noop=False``, ``is_rejected=False``); there is nothing for
this guard to do with an ordinary container write.
* The sentinel is present but there is no ``stored_value`` to
restore a masked leaf from -- rejected, same as before this only
merges against a row that actually exists.
* The sentinel is present and every occurrence resolves against
``stored_value`` (see ``_merge_redacted_container``) -- the merged
container is the value to persist. If it is byte-for-byte
identical to what's already stored, the write is a no-op (covers
both the fully-masked round-trip and a partially-masked one where
nothing actually changed); otherwise it is a genuine edit and the
caller must persist the MERGED value, not the raw submitted
*value*, which still carries the sentinel on its untouched leaves.
* Any leaf cannot be resolved (see ``_merge_redacted_container``) --
rejected.
"""
if not _container_embeds_sentinel(value, redaction_text):
return value, False, False
if stored_value is None:
return value, False, True
merged, rejected = _merge_redacted_container(
value, stored_value, redaction_text
)
if rejected:
return value, False, True
# Type-aware equality (#6201): plain ``==`` would call
# ``{"enabled": 1}`` unchanged from a stored ``{"enabled": True}`` and
# silently discard the type change as a false no-op.
if _values_equal(merged, stored_value):
return merged, True, False
return merged, False, False
def _coerced_for_guard(
key: str, ui_element: str | None, value: object
) -> object:
"""Return *value* as the sentinel guards should see it, coerced to its
stored shape when a JSON-STRING encoding would otherwise hide a masked
container from them.
``PUT /settings/api/<key>`` and both bulk-save routes accept a "json"
ui_element's value either as a native dict/list -- caught by the
container arm of ``_is_secret_empty_noop`` / ``_embeds_redaction_sentinel``
-- or as its JSON-STRING encoding, which ``coerce_setting_for_write`` ->
``get_typed_setting_value`` -> ``_parse_json_value``
(``settings/manager.py``) decodes into the same dict, but only AFTER
every guard call site runs its checks. A masked container submitted in
string form therefore sails past the container arm (which only fires
on an actual ``dict``/``list``) and falls through to the string arm,
which is gated on the OUTER key's sensitivity -- exactly the
"non-sensitive outer key with a sensitive nested leaf" case the
container arm exists to close. Coercing here, before the guards run,
closes that gap the same way the create path's registered-default
branch already does (it coerces before its own guard call).
Only a ``str`` is re-coerced, and the coerced result is used only if
it actually becomes a dict/list: an already-dict/list *value* is
already handled correctly by the container arm as-is, and running it
back through a non-container ``ui_element`` (e.g. "text": ``str(value)``)
would destroy that shape instead of revealing one. This return value
is used ONLY to decide what the guards see and, when a sentinel is
found, to compute the merged replacement value -- callers must keep
persisting their own *value* (or that merge result) unchanged in every
other case, never this function's return value directly, so an
ordinary JSON-string write (no sentinel involved) is unaffected.
A row's ``ui_element`` can itself disagree with its actual stored
shape -- e.g. a ``PUT``-created key with no ``ui_element`` defaults to
"text" (``models/settings.py``) even when a caller stores a dict/list
value under it. For "text"/"textarea"/"password"/"select", the
ui_element-based coercion above NEVER becomes a dict/list (their
target type IS ``str``), so a masked container submitted in
JSON-STRING form under one of THOSE elements would still sail past
the container arm even after the coercion above (#6201). When the
ui_element-based attempt didn't produce a container, this also tries
a plain JSON decode of the same string independent of ``ui_element``
entirely -- the row's ACTUAL stored shape decides whether this is a
container write in disguise, not its declared type. Quiet on failure
(unlike ``settings/manager.py``'s ``_parse_json_value``, which logs a
warning on every non-JSON string): an ordinary "text" setting holding
an ordinary non-JSON string is the overwhelmingly common case here and
must not spam the log.
The BARE sentinel (*value* exactly equal to the redaction text) is
special-cased to skip coercion entirely and pass through unchanged.
``coerce_setting_for_write("multiselect", "[REDACTED]", ...)`` ->
``_parse_multiselect`` (``settings/manager.py``) sees a string starting
with "[" that fails ``json.loads`` (the sentinel isn't valid JSON) and
falls back to its comma-separated split, which -- since there is no
comma -- wraps the whole string into a ONE-ELEMENT LIST,
``["[REDACTED]"]``. That list then looks like a malformed/rejected
container write (a length-mismatch against a stored list of any other
size) instead of the ordinary round-tripped sentinel it actually is,
turning what used to be a 200 no-op into a 400 for a sensitive
``multiselect`` setting (#6201 item 6). The exact-match scalar arm of
``_is_secret_empty_noop`` / ``_embeds_redaction_sentinel`` handles a
bare-string sentinel for a SENSITIVE key under every ui_element (both
scalar arms are ``is_sensitive_setting``-gated -- a bare sentinel
submitted for a NON-sensitive container row still persists verbatim
over the stored container, which those arms do not cover), so there is
nothing this coercion needs to reveal for that case.
A SPLICED sentinel on a ``multiselect`` -- e.g. ``"[REDACTED],new"``
from a stale client that rendered the mask and had a value appended --
must skip the coercion for the same reason, and this one is a
data-loss bug rather than a usability one. ``_parse_multiselect``'s
comma-split fallback fires again (the whole string still isn't valid
JSON) and turns the SPLICED scalar into ``["[REDACTED]", "new"]``,
whose first item is now an EXACT sentinel match. The container arm
then merges it positionally against a stored list of the same length
and persists ``["A", "new"]`` with a 200 -- silently DESTROYING the
stored ``"B"`` -- so the "contains the sentinel but is not equal to it
=> hard 400" rule that ``_merge_redacted_container`` documents (and
that the scalar arm enforces, as the base branch did here) never fires
at all. Splitting a spliced scalar into a list manufactures the exact
match out of a corrupted edit, so malformed JSON carrying the sentinel
is handed to the guards AS A STRING for this ui_element; the scalar arm
of ``_embeds_redaction_sentinel`` then rejects it with the usual 400
(#6201 round 7). Only ``multiselect`` needs this: ``json`` decodes
with ``json.loads`` alone, which never invents list structure out of a
non-JSON string. Valid JSON containers under ``multiselect`` must still
be decoded before the guards run, so nested masks restore the stored
secrets instead of being persisted literally.
"""
if not isinstance(value, str) or not ui_element:
return value
if value == DataSanitizer.REDACTION_TEXT:
return value
# ``multiselect`` is the one ui_element whose coercion SPLITS a string
# on commas, so a spliced sentinel ("[REDACTED],new") comes back as a
# list whose first item is an exact sentinel match -- laundering a
# corrupted edit into a merge that silently drops the stored items the
# client did not resend. Keep it a string so the scalar arm can reject
# it (see the docstring).
if ui_element == "multiselect" and DataSanitizer.REDACTION_TEXT in value:
# Strict JSON reveals real containers without the comma-split
# fallback manufacturing a container from a corrupted scalar.
try:
parsed = json.loads(value)
except (json.JSONDecodeError, ValueError, RecursionError):
return value
return parsed if isinstance(parsed, (dict, list)) else value
# Only "json" and "multiselect" can actually decode a string into a
# dict/list via ``coerce_setting_for_write`` -- every other
# ui_element's converter (``float``, ``bool``, ``str``, ...) can never
# produce one. Calling it for those elements anyway would run
# ``coerce_setting_for_write`` a SECOND time on the exact same
# (key, value, ui_element) once the caller coerces again for the
# actual persisted write below (every string write on an existing
# setting would otherwise pay for this twice): a failing conversion
# (e.g. "abc" on a "number" row) would log its warning twice, and for
# a "number"/"range" row this ran ``float(x)`` on the RAW submission
# BEFORE the sentinel guards below get a chance to run. That used to
# log the raw typed submission at WARNING on conversion failure --
# exactly what the guards below exist to prevent from happening
# unchecked. ``get_typed_setting_value`` no longer logs a setting
# VALUE at all (#6201 round 6), so the disclosure half of this
# rationale is now closed at the converter; the duplicate-work and
# duplicate-warning halves stand on their own.
# Skipping the call here for non-container-capable elements removes
# that channel entirely; those elements still fall through to the
# ui_element-independent JSON-shape check below, which is what
# actually matters for detecting a container submitted under a
# mismatched ui_element (see the docstring).
if ui_element in ("json", "multiselect"):
coerced = coerce_setting_for_write(
key=key, value=value, ui_element=ui_element
)
if isinstance(coerced, (dict, list)):
return coerced
stripped = value.strip()
if stripped and stripped[0] in "{[":
try:
parsed = json.loads(stripped)
except (json.JSONDecodeError, ValueError, RecursionError):
return value
if isinstance(parsed, (dict, list)):
return parsed
return value
def _reconciled_container_value_for_write(
raw_value: object, guard_value: object, stored_value: object
) -> Tuple[object, bool]:
"""Return the value to actually PERSIST for a write that has already
passed both sentinel guards (``_is_secret_empty_noop`` returned False
and ``_embeds_redaction_sentinel`` returned False for *guard_value*).
Returns ``(value_to_persist, is_reconciled_container)``.
For a scalar, or a dict/list that embeds no sentinel at all, this is
``(raw_value, False)`` -- including when *guard_value* differs from
*raw_value* (e.g. *guard_value* is the JSON-string-decoded form
``_coerced_for_guard`` produced purely to run the guards): an ordinary
write, with no security-relevant transformation, must never be altered
by this reconciliation step, or every other special-case handler
downstream (checkbox coercion, the corrupted-value repair block) would
see a different shape than it does today.
Only when *guard_value* is a dict/list that DOES embed the sentinel
does this return ``(effective, True)``, where ``effective`` is the
MERGED container from ``_resolve_container_secret_write`` -- masked
leaves restored to their stored secret, edited leaves as submitted --
instead of *raw_value*, which still carries "[REDACTED]" on every
untouched masked leaf and would otherwise be persisted verbatim.
``is_reconciled_container=True`` is the caller's signal to persist
``effective`` AS-IS, bypassing ``coerce_setting_for_write``. That
coercion exists to turn a submitted SCALAR into the row's declared
Python type (e.g. ``"5" -> 5`` for a number setting); every
ui_element whose declared type is ``str`` -- "text", "textarea",
"password", "select" -- would otherwise run a MERGED CONTAINER
through ``str()``, flattening it to its Python repr and persisting a
real, just-restored secret as a plain, non-redacted string under a
key ``redact_value``/``is_sensitive_setting`` has no reason to treat
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
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
pass a dict/list through unchanged, so skipping the call entirely for
a reconciled container changes nothing for those two ui_elements --
only "text"/"textarea"/"password"/"select" (whose converter is
``str``) and "number"/"checkbox"/"range"/"slider" (whose converter
would silently discard the container's structure) are protected by
this.
"""
if not isinstance(guard_value, (dict, list)):
return raw_value, False
if not _container_embeds_sentinel(
guard_value, DataSanitizer.REDACTION_TEXT
):
return raw_value, False
# NOTE (cross-helper coupling, deliberate but latent -- read before
# editing either side). ``_is_rejected`` is DISCARDED here. When
# ``_resolve_container_secret_write`` rejects -- an orphan sentinel
# (a masked leaf with nothing in the stored row to restore it from), a
# spliced "[REDACTED],x" leaf, a length-changed list, an untrusted
# list position -- ``effective`` is the RAW submission, still carrying
# the literal placeholder text, and this returns it with
# ``is_reconciled_container=True``. Every caller reads that flag as
# "persist as-is, skipping BOTH ``coerce_setting_for_write`` and
# ``validate_setting``", so a rejected write would store "[REDACTED]"
# as the credential with both checks bypassed.
#
# That is unreachable today, and only for one reason: all three call
# sites run ``_embeds_redaction_sentinel`` FIRST, on the SAME
# ``guard_value``, and it 400s on exactly the conditions that set
# ``rejected`` here (it calls ``_resolve_container_secret_write`` with
# the same arguments and returns its ``is_rejected``). By the time
# this function runs, ``rejected`` is therefore always False. This is
# the second undocumented coupling in this file (the first is
# ``_merge_redacted_container``'s depth-cap NOTE) and is recorded
# rather than removed because propagating the rejection would change
# this helper's return arity at three call sites with three different
# error conventions (a 400 JSONResponse, a per-key failed_count skip,
# and a flash+302). If a caller is ever added that does NOT run
# ``_embeds_redaction_sentinel`` on the same guard value first, or if
# that guard's rejection conditions are narrowed, this becomes a live
# fail-open and the rejection MUST be propagated instead.
effective, _is_noop, _is_rejected = _resolve_container_secret_write(
guard_value, stored_value, DataSanitizer.REDACTION_TEXT
)
return effective, True
def _is_secret_empty_noop(
key: str,
ui_element: str | None,
value: object,
stored_value: object = None,
) -> bool:
"""True when a secret write must be ignored: the redaction sentinel
for any sensitive setting, or an empty string for password inputs
(which render blank, so an untouched field must not wipe the secret).
The ``ui_element == "password"`` narrowing matters:
``notifications.service_url`` is a sensitive setting on a ``textarea``
that renders blank once redacted, but its blankness is advertised (the
placeholder names the explicit clear gesture) rather than a stand-in
for an unknown value, so an empty write there is a deliberate "clear
it" gesture and must reach the database (#5960).
A dict/list value goes through the container arm, delegated to
``_resolve_container_secret_write`` / ``_merge_redacted_container``:
``redact_value`` can mask a container's string leaves via
``_force_redact_strings`` or by SUB-KEY rather than replacing the whole
value with the bare sentinel (see its docstring), so the exact-string
check above never sees a container's round-tripped sentinel. Without
this arm, a GET-then-save-untouched container -- e.g. ``{"uri":
"[REDACTED]", "token": "[REDACTED]", "port": 19530}`` -- would sail past
every guard here (all are ``isinstance(value, str)``-gated) and persist
the sentinel over the real credential.
The merge is per-LEAF, not all-or-nothing: every leaf that is exactly
the sentinel is checked against ``stored_value`` at the same path, and
every other leaf (an edited sibling, a non-string port/toggle) is kept
as submitted. The write is a no-op only when that merge comes out
byte-for-byte identical to what's already stored -- i.e. nothing about
the container actually changed. A container that merges to something
DIFFERENT from what's stored is a genuine edit (handled by
``_embeds_redaction_sentinel``'s reject path only if a leaf can't be
resolved; otherwise it is written, see the update-route call sites,
which persist the merged value rather than this function's raw
argument). If the caller has no stored value to compare against
(``stored_value is None``, e.g. no prior row), a sentinel-bearing
container can never be verified as an untouched round-trip and is
therefore never treated as this kind of no-op.
The dict/list arm runs BEFORE the ``is_sensitive_setting`` gate below,
unlike the string arm: ``redact_value`` recurses into a container by
SUB-KEY, so a setting whose OUTER key is not itself sensitive (e.g.
``llm.model_kwargs``) can still have a sensitive-named leaf inside it
(``stop_token``, ``page_token``) masked to the sentinel on the way out.
Gating the container check on the outer key's sensitivity -- as this
function used to -- means that sentinel round-trips straight back into
the leaf on the very next save, since no guard ever looked at it. The
literal string "[REDACTED]" is not a value any real setting leaf would
hold, sensitive or not, so scanning every dict/list write for it
unconditionally closes that gap without needing to re-derive which
nested leaf name is "sensitive" here.
"""
if isinstance(value, (dict, list)):
_effective, is_noop, _is_rejected = _resolve_container_secret_write(
value, stored_value, DataSanitizer.REDACTION_TEXT
)
return is_noop
if not DataSanitizer.is_sensitive_setting(key, ui_element):
return False
if isinstance(value, str):
return value == DataSanitizer.REDACTION_TEXT or (
value == "" and ui_element == "password"
)
return False
def _redaction_sentinel_error(ui_element: str | None) -> str:
"""Explain the 400 raised for a value that embeds the redaction sentinel.
Shared by every write route so the message is identical wherever it
fires, but the "submit an empty value to clear it" hint only holds for
non-password sensitive settings such as the ``notifications.service_url``
textarea. ``_is_secret_empty_noop`` makes an empty write to a
``password`` input a deliberate no-op (those fields render blank, so an
untouched form must not wipe the secret), and
``_embeds_redaction_sentinel`` gates on sensitivity alone, so a
password-backed setting can reach this error through a direct API call
even though the UI cannot produce it. Advertising the empty-value
escape there would tell the caller to do something that provably
cannot work, so the hint is dropped for password inputs.
"""
message = (
"Value contains the redaction placeholder "
f"{DataSanitizer.REDACTION_TEXT!r}. The stored value is hidden, so "
"it cannot be edited in place — retype the whole value"
)
if ui_element == "password":
return (
f"{message}. To clear a password setting, clear the source "
"environment variable or use settings import."
)
return f"{message}, or submit an empty value to clear it."
def _embeds_redaction_sentinel(
key: str,
ui_element: str | None,
value: object,
stored_value: object = None,
) -> bool:
"""True when a submitted sensitive value *embeds* the redaction sentinel.
``_is_secret_empty_noop`` covers the exact sentinel: an untouched field
round-tripped from a settings API read, which is benign and silently
ignored. This covers the *edited* field. Password inputs render blank,
so they cannot produce this, but ``notifications.service_url`` is a
sensitive setting on a ``textarea`` (the first non-password sensitive
setting in the codebase), and editing its comma-separated URL list is
the normal workflow. A stale client that rendered the sentinel yields
values like ``"[REDACTED],discord://webhook/tok"``, which is not an
exact match and would otherwise persist verbatim and silently break
every notification. No legitimate secret contains the sentinel, so this
is a hard 400 rather than a no-op: unlike the exact-match case the user
made an edit, and silently dropping it would look like a successful save.
A dict/list value takes the container arm, delegated to
``_resolve_container_secret_write`` / ``_merge_redacted_container``.
This is a REJECT only, never a silent partial write: a container is
rejected when
1. a leaf equals the sentinel exactly but ``stored_value`` is itself
empty (a newly-introduced key, a structural mismatch, or no
``stored_value`` at all) -- there is nothing to "keep", so
persisting it would write the literal placeholder text. This is
only the emptiness half of the check ``redact_value`` masks on;
the leaf's own sub-key sensitivity is never consulted here, so a
sentinel restores from ANY non-empty stored value at that path,
not only one that was actually masked (a stored ``{"port":
19530}`` is never masked on read, but a submitted ``{"port":
"[REDACTED]"}`` over it still restores ``19530``). Narrowing
``DEFAULT_SENSITIVE_KEYS`` / ``is_sensitive_setting`` therefore
does not narrow what this merge will restore; or
2. a leaf merely CONTAINS the sentinel as a substring without being
an exact match (e.g. a stale client's rendered
"[REDACTED],new-value") -- an edit, but a corrupted one that
would splice the placeholder text into the stored value, same as
the plain string case below.
A container where every sentinel-bearing leaf DOES resolve against
``stored_value`` is NOT rejected here, even when other, non-masked
leaves were edited or a masked leaf's non-string sibling changed:
``redact_value`` masks a container by SUB-KEY, so a MIXED container --
e.g. ``{"api_key": "[REDACTED]", "description": "My engine",
"requires_api_key": true}`` -- has only its sensitive leaf masked, and
an untouched GET-then-PUT round-trip of it, or an edit to
``description``, must not become an unsatisfiable 400 the client can
never construct a passing request for (round 5 required EVERY maskable
leaf be exactly the sentinel, rejecting exactly this shape). Merging
the resolvable case instead of rejecting it is what lets
``_is_secret_empty_noop`` recognize the true no-op and the
update-route call sites persist the resolved edit -- see
``_reconciled_container_value_for_write``.
The dict/list arm runs BEFORE the ``is_sensitive_setting`` gate below,
for the same reason ``_is_secret_empty_noop`` does: ``redact_value``
masks a container by SUB-KEY, so an outer key that is not itself
sensitive (``llm.model_kwargs``) can still carry a masked leaf
(``stop_token``) that this function must catch on write-back. No real
setting leaf ever legitimately holds the literal string
"[REDACTED]", so checking every dict/list write for it, regardless of
the outer key, cannot reject a value nothing would ever submit.
"""
if isinstance(value, (dict, list)):
_effective, _is_noop, is_rejected = _resolve_container_secret_write(
value, stored_value, DataSanitizer.REDACTION_TEXT
)
return is_rejected
if not DataSanitizer.is_sensitive_setting(key, ui_element):
return False
if isinstance(value, str):
return (
DataSanitizer.REDACTION_TEXT in value
and value != DataSanitizer.REDACTION_TEXT
)
return False
def _embeds_sentinel_on_create(
key: str, ui_element: object, value: object
) -> bool:
"""Sentinel check for the CREATE paths.
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 client value that would be
stored verbatim as the credential. A dict/list value gets the same
treatment via ``_container_embeds_sentinel``: there is no "pure
round-trip" exemption here (unlike ``_is_secret_empty_noop`` on the
update path) because creation has no prior stored value for an untouched
field to round-trip from.
The dict/list check runs regardless of the outer key's sensitivity, for
the same reason as the update-path guards: a container's sensitive leaf
can be named differently than its outer key, and no legitimate value
ever contains the literal sentinel string.
"""
if isinstance(value, (dict, list)):
return _container_embeds_sentinel(value, DataSanitizer.REDACTION_TEXT)
if not DataSanitizer.is_sensitive_setting(
key, ui_element if isinstance(ui_element, str) else None
):
return False
if isinstance(value, str):
return DataSanitizer.REDACTION_TEXT in value
return False
def _is_allowed_new_setting_key(key: str) -> bool:
"""Return True if *key* is permitted to be created via the web API."""
# Reject malformed keys (blank, trailing/leading dot, empty ".." segment,
# stray whitespace) before the namespace check — a trailing-dot key such
# as ``local_search_chunk_size.`` otherwise passes the prefix allow-list
# and corrupts prefix lookups (see #4840).
if not is_valid_setting_key(key):
return False
key = key.lower()
for prefix in BLOCKED_SETTING_PREFIXES:
if key.startswith(prefix):
return False
for prefix in ALLOWED_SETTING_PREFIXES:
if key.startswith(prefix):
return True
return False
def _new_key_rejection_reason(key) -> str:
"""Explain why ``_is_allowed_new_setting_key`` rejected *key*.
Distinguishes a malformed key (bad syntax) from an allowed-namespace
violation so an API consumer with, say, a trailing-dot key (#4840) is
pointed at the real problem instead of being told it's a namespace issue.
"""
if not is_valid_setting_key(key):
return f"Setting key is malformed: {key!r}"
return f"Creating settings under this namespace is not allowed: {key}"
@router.get("/")
def settings_page(
request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Main settings dashboard with links to specialized config pages"""
return templates.TemplateResponse(
request=request,
name="settings_dashboard.html",
context={"request": request},
)
def _save_all_settings_sync(form_data: dict, username: str):
"""Synchronous body of save_all_settings.
Separated so the `async def` handler can offload the entire
SQLAlchemy + validation + re-read block to a thread via
asyncio.to_thread, freeing the event loop during a bulk save.
"""
try:
from ...security.data_sanitizer import DataSanitizer
with get_user_db_session(username) as db_session:
settings_manager = get_settings_manager(db_session, username)
if settings_manager.settings_locked:
return JSONResponse(
{
"status": "error",
"message": "Settings are locked and cannot be changed",
},
status_code=403,
)
# Track validation errors
validation_errors = []
settings_by_type: dict[str, Any] = {}
# Track changes for logging
updated_settings = []
created_settings = []
# Store original values for better messaging
original_values = {}
# Fetch all settings and remove non-editable keys
all_db_settings = _filter_editable_settings(form_data, db_session)
# Reject public hostnames being added to the local-hosts allowlist,
# and inherently-public engines being added to the trusted-engines
# list.
_hosts_err = first_egress_validation_error(
form_data, all_db_settings
)
if _hosts_err is not None:
validation_errors.append(_hosts_err)
return JSONResponse(
{
"status": "error",
"message": "Validation errors",
"errors": validation_errors,
},
status_code=400,
)
# Update each setting
for key, value in form_data.items():
# Skip corrupted keys or empty strings as keys
if not key or not isinstance(key, str) or key.strip() == "":
continue
# Get the setting metadata from pre-fetched dict
current_setting = all_db_settings.get(key)
if key == "search.fetch.summary_input_max_length":
try:
value = to_positive_int(value)
except ValueError:
validation_errors.append(
{
"key": key,
"name": "Fetch Summary Input Max Length",
"error": "Value must be a positive integer",
}
)
continue
# The sentinel guards below must see a JSON-STRING-encoded
# container coerced to its real dict/list shape, or a
# masked container submitted in that form (a supported
# input shape for a "json" ui_element) sails past the
# container arm entirely -- see ``_coerced_for_guard``.
_guard_value = (
_coerced_for_guard(
current_setting.key, current_setting.ui_element, value
)
if current_setting
else value
)
# SAFETY NET: the redaction sentinel is never a "clear the
# value" request, and neither is an empty string on a
# password input. Reasons:
# 1. The form templates (Jinja2 + JS-rendered) deliberately
# render password inputs empty so the saved value never
# enters the HTML source. A user who blurs the field
# without typing must not wipe their stored API key.
# 2. /settings/api redacts secret values to the redaction
# sentinel ("[REDACTED]"). A stale browser tab could
# submit it back — that must be idempotent on the DB, or
# the round-trip would persist the literal sentinel over
# the real secret.
# 3. Defense-in-depth against direct cURL or automation
# mistakes that POST an empty/sentinel value.
# The empty-string half is narrowed to password inputs:
# non-password sensitive controls (the
# notifications.service_url textarea) render their real value
# and must stay clearable (#5960). To unset a password
# setting, clear the source env var or use settings import.
if current_setting and _is_secret_empty_noop(
key,
current_setting.ui_element,
_guard_value,
current_setting.value,
):
logger.debug(
f"Skipping empty secret write for {key} (no-op)"
)
continue
# A value that merely *embeds* the sentinel is a corrupted
# edit, not an untouched round-trip: reject it loudly instead
# of persisting a secret with "[REDACTED]" spliced into it
# (#5947).
if current_setting and _embeds_redaction_sentinel(
key,
current_setting.ui_element,
_guard_value,
current_setting.value,
):
logger.warning(
"Rejected redaction-sentinel value for {!r} via "
"save_all_settings (user={!r})",
key,
username,
)
validation_errors.append(
{
"key": key,
"name": current_setting.name,
"error": _container_rejection_error(
current_setting.ui_element, _guard_value
),
}
)
continue
# EARLY VALIDATION: Convert checkbox values BEFORE any other processing
# This prevents incorrect triggering of corrupted value detection
if current_setting and current_setting.ui_element == "checkbox":
if not isinstance(value, bool):
# Never interpolate a settings VALUE into a log
# line -- same rule as ``manager.py``'s converter
# (#6201). A checkbox row can hold an arbitrary
# submitted value here (that is exactly why this
# branch exists), and a stale client or a
# mis-registered ui_element can put a credential or
# a secret-bearing container in it. The key, the
# type name and the length identify the bad
# submission without disclosing it.
logger.debug(
"Converting checkbox {} from {} (len={}) to bool",
key,
type(value).__name__,
len(value)
if isinstance(value, (str, list, dict, tuple))
else "n/a",
)
value = parse_boolean(value)
form_data[key] = (
value # Update the form_data with converted value
)
# Store original value for messaging
if current_setting:
original_values[key] = current_setting.value
# Determine setting type and category
if key.startswith("llm."):
setting_type = SettingType.LLM
category = "llm_general"
if (
"temperature" in key
or "max_tokens" in key
or "batch" in key
or "layers" in key
):
category = "llm_parameters"
elif key.startswith("search."):
setting_type = SettingType.SEARCH
category = "search_general"
if (
"iterations" in key
or "results" in key
or "region" in key
or "questions" in key
or "section" in key
):
category = "search_parameters"
elif key.startswith("report."):
setting_type = SettingType.REPORT
category = "report_parameters"
elif key.startswith("database."):
setting_type = SettingType.DATABASE
category = "database_parameters"
elif key.startswith("app."):
setting_type = SettingType.APP
category = "app_interface"
elif key.startswith("chat."):
setting_type = SettingType.CHAT
category = "chat"
else:
setting_type = None
category = None
# Special handling for corrupted or empty values
if value == "[object Object]" or (
isinstance(value, str)
and value.strip() in ["{}", "[]", "{", "["]
):
if key.startswith("report."):
value = {}
else:
# Use default or null for other types
if key == "llm.model":
# Repair defaults must match main (#3348): an empty
# model lets the provider pick, "ollama" keeps a
# local-only install local instead of silently
# switching it to a cloud provider, and "auto" is
# NOT a registered engine — the factory fails
# closed on it, so a repaired install could no
# longer search at all.
value = ""
elif key == "llm.provider":
value = "ollama"
elif key == "search.tool":
value = DEFAULT_SEARCH_TOOL
elif key in ["app.theme", "app.default_theme"]:
# Hashed (ID "hashed") is the chosen dark default
# while light themes need refinement; repairs use
# that same registered value from app.theme.
value = get_default_theme()
else:
value = None
logger.warning(
"Corrected corrupted value for {}: {}",
_log_value_preview(key),
value,
)
# NOTE: No JSON pre-parsing is done here. After the
# corruption replacement above, values are Python dicts
# (e.g. {}), hardcoded strings, or None — none are JSON
# strings that need parsing. Type conversion below via
# coerce_setting_for_write() handles everything; that
# function delegates to get_typed_setting_value() which
# already parses JSON internally for "json" and
# "multiselect" ui_elements.
if current_setting:
# If the guards above let this through because a masked
# container's sentinel leaves resolved against the
# stored row (see ``_reconciled_container_value_for_write``),
# persist the MERGED value -- secrets restored, edits
# applied -- not the raw submission, which still carries
# "[REDACTED]" on every untouched masked leaf. An
# ordinary write (no sentinel involved) is returned
# unchanged, so this has no effect on it.
value, _is_reconciled_container = (
_reconciled_container_value_for_write(
value, _guard_value, current_setting.value
)
)
# Coerce to correct Python type (e.g. str "5" → int 5
# for number settings, str "true" → bool for checkboxes).
# A reconciled secret-bearing container is persisted
# exactly as merged instead: coercing it through a
# str-typed ui_element ("text"/"textarea"/"select")
# would flatten it to its Python repr, persisting a
# just-restored secret as a plain string (#6201). See
# ``_reconciled_container_value_for_write``'s docstring.
converted_value = (
value
if _is_reconciled_container
else coerce_setting_for_write(
key=current_setting.key,
value=value,
ui_element=current_setting.ui_element,
)
)
# Validate the setting. A reconciled secret-bearing
# container must never reach ``validate_setting``, and
# the load-bearing reason is TYPE REJECTION rather than
# logging: for a "number"/"range" row the value flows
# into ``get_typed_setting_value``'s bare ``float(x)``,
# which fails, so the row is reported "Value must be a
# number" and the merged edit -- with the secret just
# restored into it -- is lost. That same converter also
# used to log the raw value at WARNING; that half is
# closed at the converter as of #6201 round 6 and no
# longer justifies the skip on its own (see
# ``_coerced_for_guard``, whose comment says the same).
# Only a user-constructed row (dict/list value on a
# non-container ui_element) can reach this; skipping
# validation is safe for the secret itself because the
# merge already resolved the container against the
# stored row. ACCEPTED LOSS: it does also skip the
# options-membership / min-max / checkbox-type checks
# for such a row, so e.g. a "select" row already
# holding a container accepts a merged container with
# no options check.
is_valid, error_message = (
(True, None)
if _is_reconciled_container
else validate_setting(current_setting, converted_value)
)
if is_valid:
# Save WITHOUT committing — one final commit runs
# below after the validation pass, so a later
# validation error rolls back every preceding
# write instead of leaving the DB half-saved.
success = set_setting(
key,
converted_value,
commit=False,
db_session=db_session,
)
if success:
updated_settings.append(key)
else:
db_session.rollback()
logger.error("Failed to persist setting {}", key)
return JSONResponse(
{
"status": "error",
"message": "Failed to save setting.",
},
status_code=500,
)
# Track settings by type for exporting
if current_setting.type not in settings_by_type:
settings_by_type[current_setting.type] = []
settings_by_type[current_setting.type].append(
current_setting
)
else:
# Add to validation errors
validation_errors.append(
{
"key": key,
"name": current_setting.name,
"error": error_message,
}
)
else:
# Namespace validation: reject new keys outside allowed
# prefixes (existing keys above bypass — updates only).
if not _is_allowed_new_setting_key(key):
logger.warning(
"Security: Rejected setting outside allowed "
"namespaces: {} (user={!r})",
_log_value_preview(key),
username,
)
validation_errors.append(
{
"key": key,
"name": key,
"error": _new_key_rejection_reason(key),
}
)
continue
# Creation has no prior value, so the sentinel cannot
# mean "keep the stored secret" — every occurrence of it,
# exact match included, would be stored verbatim as the
# credential. ui_element is not yet known here, so
# sensitivity is decided by the key's leaf name (#5947).
if _embeds_sentinel_on_create(key, None, value):
logger.warning(
"Rejected redaction-sentinel value for new key "
"{} via save_all_settings (user={!r})",
_log_value_preview(key),
username,
)
validation_errors.append(
{
"key": key,
"name": key.split(".")[-1]
.replace("_", " ")
.title(),
"error": _container_rejection_error(
None, value
),
}
)
continue
# Create a new setting
new_setting = {
"key": key,
"value": value,
"type": setting_type.value.lower()
if setting_type is not None
else "app",
"name": key.split(".")[-1].replace("_", " ").title(),
"description": f"Setting for {key}",
"category": category,
"ui_element": "text", # Default UI element
}
# Determine better UI element based on value type
if isinstance(value, bool):
new_setting["ui_element"] = "checkbox"
elif isinstance(value, (int, float)) and not isinstance(
value, bool
):
new_setting["ui_element"] = "number"
elif isinstance(value, (dict, list)):
new_setting["ui_element"] = "textarea"
# A JSON body can carry NaN, Infinity or an integer too
# large for a float, which the number type rejects on
# read.
rejection = _strict_read_rejection(
key, value, new_setting["ui_element"]
)
if rejection is not None:
validation_errors.append(
{
"key": key,
"name": new_setting["name"],
"error": rejection,
}
)
continue
# Create the setting without committing yet — see above
db_setting = create_or_update_setting(
new_setting, commit=False, db_session=db_session
)
if db_setting:
created_settings.append(key)
# Track settings by type for exporting
if db_setting.type not in settings_by_type:
settings_by_type[db_setting.type] = []
settings_by_type[db_setting.type].append(db_setting)
else:
validation_errors.append(
{
"key": key,
"name": new_setting["name"],
"error": "Failed to create setting",
}
)
# Report validation errors if any — roll back the whole batch
# so a partial save isn't visible to the next request.
if validation_errors:
db_session.rollback()
return JSONResponse(
{
"status": "error",
"message": "Validation errors",
"errors": validation_errors,
},
status_code=400,
)
# Prepare the effective response before committing. An invalid
# environment override must refuse the batch before any edit or
# post-commit effect becomes visible.
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[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,
}
# Overlay operator-locked (LDR_*) settings onto the echo, the
# way SettingsManager.get_all_settings() already does for
# GET /settings/api. The settings form re-renders from this
# payload, so without the overlay an env-pinned field comes back
# showing the stale DB value and marked editable until a full
# page reload (#5978). Port of main's
# _shape_effective_setting_metadata.
for _echo_key, _echo_meta in all_settings.items():
if is_operator_only_setting(_echo_key):
_echo_meta["editable"] = False
if check_env_setting(_echo_key) is None:
continue
_echo_meta["value"] = get_typed_setting_value(
key=_echo_key,
value=_echo_meta.get("value"),
ui_element=str(_echo_meta.get("ui_element", "text")),
default=_echo_meta.get("value"),
check_env=True,
)
_echo_meta["editable"] = False
# The echo above covers only keys with a saved row. An override on
# a declared (default) key without a row is part of the same
# effective configuration, so it must refuse the batch too rather
# than surface only on the next typed read.
_defaults = settings_manager.default_settings
for _default_key, _default_meta in _defaults.items():
if (
_default_key in all_settings
or check_env_setting(_default_key) is None
):
continue
get_typed_setting_value(
key=_default_key,
value=_default_meta.get("value"),
ui_element=str(_default_meta.get("ui_element", "text")),
default=_default_meta.get("value"),
check_env=True,
)
# Operator-gate the "unprotected" escape hatch out of the
# egress-scope select's options unless explicitly enabled, and
# normalise the displayed value (#5148 / 87537d9ec). Without
# this, a save-and-refresh cycle would re-render the dropdown
# from this echoed payload with the escape hatch back on offer.
if "policy.egress_scope" in all_settings:
all_settings["policy.egress_scope"] = (
_shape_egress_scope_setting(
"policy.egress_scope",
all_settings["policy.egress_scope"],
)
)
# Hide the operator-gated unencrypted "filesystem" PDF-storage
# option from a save-and-refresh echo, same rationale as the
# egress-scope shaping above (#5148 / fb49985aa).
if "research_library.pdf_storage_mode" in all_settings:
all_settings["research_library.pdf_storage_mode"] = (
_shape_pdf_storage_mode_setting(
"research_library.pdf_storage_mode",
all_settings["research_library.pdf_storage_mode"],
)
)
# Customize the success message based on what changed
success_message = ""
if len(updated_settings) == 1:
# For a single update, provide more specific info about what changed
key = updated_settings[0]
# Reuse the already-fetched setting from our pre-fetched dict
updated_setting = all_db_settings.get(key)
name = (
updated_setting.name
if updated_setting
else key.split(".")[-1].replace("_", " ").title()
)
# Format the message
if key in original_values:
# Get original value but comment out if not used
# old_value = original_values[key]
new_value = (
updated_setting.value if updated_setting else None
)
# If it's a boolean, use "enabled/disabled" language
if isinstance(new_value, bool):
state = "enabled" if new_value else "disabled"
success_message = f"{name} {state}"
else:
# For non-boolean values
if isinstance(new_value, (dict, list)):
success_message = f"{name} updated"
else:
success_message = f"{name} updated"
else:
success_message = f"{name} updated"
else:
# Multiple settings or generic message
success_message = f"Settings saved successfully ({len(updated_settings)} updated, {len(created_settings)} created)"
# Check if any warning-affecting settings were changed and include
# warnings. Redact secret values in the echoed settings so a POST
# response never ships plaintext API keys back to the browser —
# matching the redaction the GET /settings/api endpoint applies.
response_data = {
"status": "success",
"message": success_message,
"updated": updated_settings,
"created": created_settings,
"settings": DataSanitizer.redact_settings_snapshot(
all_settings
),
}
# The writes and response both validated: commit atomically.
db_session.commit()
changed_settings = updated_settings + created_settings
# The batch is committed from here on. A settings error raised by
# a post-commit effect must not be reported as a refused save.
try:
if changed_settings:
settings_manager.emit_settings_changed_after_commit(
changed_settings
)
invalidate_settings_caches(username)
reschedule_document_jobs_if_needed(username, changed_settings)
reschedule_zotero_jobs_if_needed(username, changed_settings)
# Check if any warning-affecting settings were changed
if any(
key in WARNING_AFFECTING_KEYS for key in changed_settings
):
warnings = calculate_warnings(username=username)
response_data["warnings"] = warnings
logger.info(
f"Bulk settings update affected warning keys, calculated {len(warnings)} warnings"
)
except SettingsValueError as error:
_log_post_save_settings_error(error)
return response_data
except SettingsValueError as error:
return _settings_value_error_response(
"settings for bulk save", error, bulk_save=True
)
except Exception:
logger.exception("Error saving settings")
return JSONResponse(
{
"status": "error",
"message": "An internal error occurred while saving settings.",
},
status_code=500,
)
@router.post("/save_all_settings")
@settings_limit
async def save_all_settings(
request: Request,
username: Annotated[str, Depends(require_auth)],
):
"""Handle saving all settings at once from the unified settings page.
Thin async wrapper that reads the JSON body, then offloads the
entire sync save to a thread so we don't block the event loop.
"""
form_data, body_error = await read_json_dict(
request, "status", "No settings data provided"
)
if body_error is not None:
return body_error
if not form_data:
return JSONResponse(
{"status": "error", "message": "No settings data provided"},
status_code=400,
)
return await run_db_sync(_save_all_settings_sync, form_data, username)
@router.post("/reset_to_defaults")
@settings_limit
def reset_to_defaults(
request: Request,
username: Annotated[str, Depends(require_auth)],
):
"""Reset all settings to their default values.
Preserves API keys and other password-type settings — overwriting
these with empty defaults from the bundled JSON would silently
erase the user's credentials and force them to re-enter every key.
"""
try:
with get_user_db_session(username) as db_session:
settings_manager = get_settings_manager(db_session, username)
# Settings lock (app.lock_settings) -- ported from main's
# reset_to_defaults (#5659, "enforce the settings lock on delete,
# import and reset"). SettingsManager already refuses when
# locked, so the write cannot happen either way; this repeats
# the check at the route so a locked instance answers 403
# rather than 200 with nothing written, which is what main's
# own comment gives as the reason. Without it the merge that
# brought #5659 in would have silently dropped the fix, since
# it landed in a Flask file this migration deletes.
if settings_manager.settings_locked:
return JSONResponse(
{
"status": "error",
"message": "Settings are locked and cannot be reset",
},
status_code=403,
)
# Snapshot password/api-key settings before reset so we can
# restore them. We use the DB row's ui_element to detect
# password fields rather than a name pattern.
preserved: dict[str, Any] = {}
password_rows = (
db_session.query(Setting)
.filter(Setting.ui_element == "password")
.all()
)
for row in password_rows:
if row.value not in (None, ""):
preserved[row.key] = row.value
# preserve_environment_locked=True is load-bearing and was lost in
# the port: it defaults to False, and import_settings writes rows
# in BULK rather than through the _is_environment_locked-guarded
# setters, so without it a reset overwrites the stored rows of
# settings an operator has locked via LDR_* env vars — and drops
# the policy_audit warning that records the attempt. The damage is
# latent while the env var is set (reads prefer env) and surfaces
# the moment the operator removes it.
settings_manager.load_from_defaults_file(
preserve_environment_locked=True
)
reset_setting_keys = tuple(settings_manager.default_settings)
# Restore preserved values
for key, value in preserved.items():
try:
settings_manager.set_setting(key, value, commit=False)
except Exception:
logger.exception(
f"Could not restore preserved setting {key}"
)
if preserved:
db_session.commit()
logger.info(
"Successfully reset settings to defaults "
f"(preserved {len(preserved)} password-type setting(s))"
)
invalidate_settings_caches(username)
reschedule_document_jobs_if_needed(username, reset_setting_keys)
reschedule_zotero_jobs_if_needed(username, reset_setting_keys)
except Exception:
logger.exception("Error importing default settings")
return JSONResponse(
{
"status": "error",
"message": "Failed to reset settings to defaults",
},
status_code=500,
)
return {
"status": "success",
"message": "All settings have been reset to default values",
}
def _add_form_rejection(
details: list[str], key: str, reason: str | None
) -> None:
"""Collect at most three trusted rejection summaries, totaling <=600 bytes.
Keys come from admitted database rows (or the fixed summary key), never
submitted values. Do not copy option lists, metadata messages or exceptions
into the session. The aggregate failure count also covers omitted details.
"""
if len(details) >= 3:
return
safe_reason = "Invalid value"
if reason in (
"Value must be a positive integer",
"Value must be a number",
"Value must be a boolean",
):
safe_reason = reason
elif isinstance(reason, str):
if reason.startswith("Value must be one of:"):
safe_reason = "Value must be an allowed option"
elif len(reason) <= 80 and re.fullmatch(
r"Value must be at (?:least|most) -?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?",
reason,
):
safe_reason = reason
# Bound each entry while collecting, leaving room for both separators.
# Decode only complete UTF-8 characters; the ellipsis counts in the cap.
key = key[:199]
entry = f"{key}: {safe_reason}"
if len(entry.encode("utf-8")) > 198:
key = key.encode("utf-8")[: 198 - len(safe_reason.encode("utf-8")) - 5]
entry = f"{key.decode('utf-8', errors='ignore')}…: {safe_reason}"
details.append(entry)
def _save_settings_sync(form_data: dict, username: str) -> dict:
"""Sync helper for save_settings — runs the bulk setting writes.
Returns an outcome dict so the caller can flash user-visible feedback
on the no-JS fallback path (``ok``, ``policy_error``, ``failed``,
``rejected``) — Flask's flash()-based feedback was otherwise lost in
the migration, leaving the no-JS form a silent redirect regardless of
success, partial rejection, or failure.
"""
with get_user_db_session(username) as db_session:
settings_manager = get_settings_manager(db_session, username)
# Fetch all settings and remove non-editable keys
all_db_settings = _filter_editable_settings(form_data, db_session)
# Egress-policy validators — the JSON route (save_all_settings) runs
# these; the POST fallback must too, or a JS-disabled client could
# whitelist a public hostname as "local", which the JSON route does
# not permit.
_policy_err = first_egress_validation_error(form_data, all_db_settings)
if _policy_err is not None:
logger.warning(
"Rejected settings POST: {}",
_log_value_preview(
_policy_err.get("error", "Invalid policy setting")
),
)
return {
"ok": False,
"policy_error": _policy_err.get(
"error", "Invalid policy setting"
),
"failed": 0,
"rejected": 0,
}
failed_count = 0
rejection_details: list[str] = []
rejected_count = 0
changed_settings: list[str] = []
sentinel_rejected_ui_elements: list[str | None] = []
# Parallel to sentinel_rejected_ui_elements: whether that specific
# rejection was the depth cap rather than an actual sentinel, so the
# aggregated flash message below doesn't misreport a too-deep
# payload as "contains the redaction placeholder" (see
# ``_container_too_deep_error``).
sentinel_rejected_too_deep: list[bool] = []
for key, value in form_data.items():
try:
db_setting = all_db_settings.get(key)
if key == "search.fetch.summary_input_max_length":
try:
value = to_positive_int(value)
except ValueError:
_add_form_rejection(
rejection_details,
key,
"Value must be a positive integer",
)
failed_count += 1
continue
# Namespace validation: reject new keys outside allowed
# prefixes. Existing keys (updates) bypass this check — it
# only applies to creation of brand-new rows through this
# form-POST route.
if db_setting is None and not _is_allowed_new_setting_key(key):
logger.warning(
"Security: Rejected setting outside allowed "
"namespaces: {} (user={!r})",
_log_value_preview(key),
username,
)
rejected_count += 1
continue
# Creation has no prior value, so the sentinel cannot mean
# "keep the stored secret" — every occurrence is a
# corrupted client value that would be stored verbatim as
# the credential. This is the one write path that never
# had this check wired in (#5947 added it to
# save_all_settings and api_update_setting, but not here);
# ui_element is unknown at creation time, so sensitivity is
# decided by the key's leaf name alone, same as the other
# create paths.
if db_setting is None and _embeds_sentinel_on_create(
key, None, value
):
logger.warning(
"Rejected redaction-sentinel value for new key "
"{} via save_settings (user={!r})",
_log_value_preview(key),
username,
)
sentinel_rejected_ui_elements.append(None)
sentinel_rejected_too_deep.append(
isinstance(value, (dict, list))
and _container_exceeds_max_depth(value)
)
continue
# See ``_coerced_for_guard``: the sentinel guards must see a
# JSON-string-encoded container coerced to its real
# dict/list shape, or a masked container submitted in that
# form sails past the container arm entirely.
_guard_value = (
_coerced_for_guard(
db_setting.key, db_setting.ui_element, value
)
if db_setting
else value
)
# SAFETY NET: the redaction sentinel is a no-op for every
# sensitive setting, and an empty string is a no-op only for
# password inputs — never "clear my key". The no-JS form
# renders password inputs empty (and GET redacts them to the
# sentinel), so a plain form submit must not wipe the stored
# secret. Non-password sensitive controls (the
# notifications.service_url textarea) stay clearable (#5960).
# Matches the guards in save_all_settings +
# api_update_setting.
if db_setting and _is_secret_empty_noop(
key, db_setting.ui_element, _guard_value, db_setting.value
):
logger.debug(
f"Skipping empty secret write for {key} via "
"save_settings (no-op)"
)
continue
# An embedded sentinel is a corrupted edit, not a round-trip.
# This route reports per-setting outcomes by flash message,
# so collect it rather than saving a secret with "[REDACTED]"
# spliced into it (#5947).
if db_setting and _embeds_redaction_sentinel(
key, db_setting.ui_element, _guard_value, db_setting.value
):
logger.warning(
"Rejected redaction-sentinel value for {!r} via "
"save_settings (user={!r})",
key,
username,
)
sentinel_rejected_ui_elements.append(db_setting.ui_element)
sentinel_rejected_too_deep.append(
isinstance(_guard_value, (dict, list))
and _container_exceeds_max_depth(_guard_value)
)
continue
if db_setting:
# An HTML form cannot express None. A <select> whose
# options include a null value (e.g. "All Time" for
# search.engine.web.serper.default_params.time_period)
# posts back "" for that choice, and "" is not in the
# allowed values, so validate_setting below rejects a
# value the user never changed. The JSON route is
# unaffected because it sends a real null.
#
# Only "" is mapped, and only when null is genuinely an
# allowed option — so this cannot turn a typo into a
# silent null on a select that does not permit one.
if (
value == ""
and db_setting.ui_element == "select"
and db_setting.options
and any(
(opt.get("value") if isinstance(opt, dict) else opt)
is None
for opt in list(db_setting.options)
)
):
value = None
# Persist the MERGED value when a masked container's
# sentinel leaves resolved against the stored row
# (see ``_reconciled_container_value_for_write``); an
# ordinary write is returned unchanged.
value, _is_reconciled_container = (
_reconciled_container_value_for_write(
value, _guard_value, db_setting.value
)
)
# A reconciled secret-bearing container is persisted
# exactly as merged: coercing it through a str-typed
# ui_element would flatten it to its Python repr and
# disclose a just-restored secret as a plain string
# (#6201). See _reconciled_container_value_for_write.
if not _is_reconciled_container:
value = coerce_setting_for_write(
key=db_setting.key,
value=value,
ui_element=db_setting.ui_element,
)
# Validate against the setting's constraints (options
# membership, numeric bounds, checkbox type) — the same
# check save_all_settings (~line 655) and
# api_update_setting (~line 3125) run. Main added this
# exact call to the Flask route this function replaces
# (fb49985aa8: "this JS-disabled POST fallback wrote
# values unchecked"); the FastAPI rewrite dropped it.
# Best-effort semantics preserved: an invalid key is
# skipped and counted in failed_count, the rest of the
# batch still validates, saves, and commits.
#
# A reconciled secret-bearing container skips
# ``validate_setting`` the same way it skips coercion
# above. The load-bearing reason is TYPE REJECTION, not
# logging: ``validate_setting`` runs the value through
# ``get_typed_setting_value`` for the row's DECLARED
# ui_element, so a dict/list on a "number"/"range" row
# comes back "Value must be a number" and the merged
# edit -- with the secret just restored into it -- is
# lost. Its other former reason (that same path logged
# the raw, secret-bearing value at WARNING) is closed
# at the converter itself as of #6201 round 6, so it no
# longer justifies anything on its own;
# ``_coerced_for_guard``'s comment already says this.
# ACCEPTED LOSS: skipping validation also skips the
# options-membership / min-max / checkbox-type checks,
# so e.g. a "select" row that already holds a container
# accepts a merged container with no options check.
# Bounded to rows already holding a container under a
# scalar ui_element -- a user-constructed shape -- and
# the merge itself already resolved every leaf against
# the stored row (#6201).
if value is not None and not _is_reconciled_container:
is_valid, error_message = validate_setting(
db_setting, value
)
if not is_valid:
logger.warning(
f"Validation failed for setting {key}: "
f"{error_message}"
)
_add_form_rejection(
rejection_details, db_setting.key, error_message
)
failed_count += 1
continue
if not settings_manager.set_setting(key, value, commit=False):
failed_count += 1
logger.warning(
"Failed to save setting {}", _log_value_preview(key)
)
else:
changed_settings.append(key)
except Exception:
logger.exception(
"Error saving setting {}", _log_value_preview(key)
)
failed_count += 1
if rejected_count:
logger.warning(
f"Rejected {rejected_count} new setting(s) outside "
"allowed namespaces"
)
try:
db_session.commit()
invalidate_settings_caches(username)
reschedule_document_jobs_if_needed(username, changed_settings)
reschedule_zotero_jobs_if_needed(username, changed_settings)
except Exception:
db_session.rollback()
logger.exception("Failed to commit settings")
return {
"ok": False,
"policy_error": None,
"failed": failed_count + 1,
"rejected": rejected_count,
"sentinel_rejected": sentinel_rejected_ui_elements,
"sentinel_rejected_too_deep": sentinel_rejected_too_deep,
}
return {
"ok": failed_count == 0 and not sentinel_rejected_ui_elements,
"policy_error": None,
"failed": failed_count,
"rejection_details": "; ".join(rejection_details),
"rejected": rejected_count,
"sentinel_rejected": sentinel_rejected_ui_elements,
"sentinel_rejected_too_deep": sentinel_rejected_too_deep,
}
@router.post("/save_settings")
@settings_limit
async def save_settings(
request: Request,
username: Annotated[str, Depends(require_auth)],
):
"""Save all settings from the form using POST method — fallback when
JavaScript is disabled. Body work offloaded to threadpool."""
from ..dependencies.flash import flash
outcome = None
try:
form_data = dict(await request.form())
form_data.pop("csrf_token", None)
outcome = await run_db_sync(_save_settings_sync, form_data, username)
except Exception:
logger.exception("Error in save_settings")
# Give the no-JS user visible feedback via a flash message (rendered on
# the /settings/ page) instead of a silent redirect. Flask flashed the
# same success/error; the migration had dropped it.
if outcome is None:
flash(request, "Failed to save settings. Please try again.", "error")
elif outcome.get("policy_error"):
flash(request, outcome["policy_error"], "error")
elif outcome.get("sentinel_rejected"):
# Drop the empty-value hint if any rejected setting is a password
# input, where an empty write is a no-op rather than a clear (see
# ``_redaction_sentinel_error``).
_rejected_uis = outcome["sentinel_rejected"]
_too_deep = outcome.get("sentinel_rejected_too_deep") or []
_hint_ui = (
"password"
if any(ui == "password" for ui in _rejected_uis)
else None
)
# Every rejection in this batch was the depth cap, not an actual
# sentinel -- say so instead of claiming the value "contains the
# redaction placeholder" (see ``_container_too_deep_error``). A
# MIXED batch (some too-deep, some an actual sentinel) states
# both reasons instead of only the sentinel wording, which used
# to silently drop the too-deep explanation for whichever
# settings in the batch were rejected for that reason instead.
if _too_deep and all(_too_deep):
_message = _container_too_deep_error()
elif _too_deep and any(_too_deep):
_message = (
_redaction_sentinel_error(_hint_ui)
+ " (Some of these were instead rejected for nesting too "
"deeply to validate — flatten those before saving.)"
)
else:
_message = _redaction_sentinel_error(_hint_ui)
flash(
request,
f"Rejected {len(_rejected_uis)} settings: " + _message,
"error",
)
elif outcome.get("failed"):
flash(
request,
f"Saved with {outcome['failed']} setting(s) failing. "
"Check the values and try again."
+ (
" " + outcome["rejection_details"]
if outcome.get("rejection_details")
else ""
),
"warning",
)
elif outcome.get("rejected"):
flash(
request,
f"Settings saved; {outcome['rejected']} unrecognized key(s) "
"were ignored.",
"warning",
)
else:
flash(request, "Settings saved.", "success")
return RedirectResponse(url="/settings/", status_code=302)
def _log_post_save_settings_error(error: SettingsValueError) -> None:
"""Log a settings error raised after a bulk save already committed.
``error.diagnostic`` holds only the key, its source and a fixed reason,
never the value.
"""
logger.error(
"Settings saved, but a post-save step could not read settings: {}",
error.diagnostic,
)
def _settings_value_error_response(
resource: str, error: SettingsValueError, *, bulk_save: bool = False
) -> JSONResponse:
"""Return the diagnostic for an invalid configured setting.
The upgrade guide tells operators to locate the setting from this
message, so it replaces the generic error. ``error.diagnostic`` holds
only the key, its source and a fixed reason, never the value.
Bulk saves retain their existing status/message response fields.
"""
logger.error("Could not load {}: {}", resource, error.diagnostic)
body = (
{"status": "error", "message": error.diagnostic}
if bulk_save
else {"error": error.diagnostic}
)
return JSONResponse(body, status_code=500)
# API Routes
@router.get("/api")
def api_get_all_settings(
request: Request,
username: Annotated[str, Depends(require_auth)],
):
"""Get all settings"""
try:
# Get query parameters
category = request.query_params.get("category")
with get_user_db_session(username) as db_session:
settings_manager = get_settings_manager(db_session, username)
# Get settings
settings = settings_manager.get_all_settings()
# Filter by category if requested
if category:
filtered_settings = {}
# Need to get all setting details to check category
db_settings = db_session.query(Setting).all()
category_keys = [
s.key for s in db_settings if s.category == category
]
# Filter settings by keys
filtered_settings = {
key: value
for key, value in settings.items()
if key in category_keys
}
settings = filtered_settings
# Operator-gate the "unprotected" escape hatch out of the
# egress-scope select's options unless explicitly enabled, and
# normalise the displayed value (#5148 / 87537d9ec).
if "policy.egress_scope" in settings:
settings["policy.egress_scope"] = _shape_egress_scope_setting(
"policy.egress_scope", settings["policy.egress_scope"]
)
# Hide the operator-gated unencrypted "filesystem" PDF-storage
# option, same rationale as the egress-scope shaping above
# (#5148 / fb49985aa).
if "research_library.pdf_storage_mode" in settings:
settings["research_library.pdf_storage_mode"] = (
_shape_pdf_storage_mode_setting(
"research_library.pdf_storage_mode",
settings["research_library.pdf_storage_mode"],
)
)
# Redact secret values (API keys, passwords, OAuth tokens) — main
# does this (DataSanitizer.redact_settings_snapshot) as defense in
# depth: this JSON gets cached by clients, logged by proxies, and
# pasted into bug reports. Safe to round-trip: the save path treats
# the '[REDACTED]' sentinel as a no-op (see the write-back guards in
# _save_*_settings_sync), so the dashboard re-saving a redacted dump
# never overwrites stored credentials, and settings.js seeds the
# password baselines from this sentinel (PR #3947).
from ...security.data_sanitizer import DataSanitizer
settings = DataSanitizer.redact_settings_snapshot(settings)
return {"status": "success", "settings": settings}
except SettingsValueError as error:
return _settings_value_error_response("settings", error)
except Exception:
logger.exception("Error getting settings")
return JSONResponse(
{"error": "Failed to retrieve settings"}, status_code=500
)
@router.post("/api/import")
@settings_limit
def api_import_settings(
request: Request,
username: Annotated[str, Depends(require_auth)],
):
"""Import settings from defaults file"""
try:
with get_user_db_session(username) as db_session:
settings_manager = get_settings_manager(db_session, username)
# Settings lock (app.lock_settings) -- ported from main's
# api_import_settings (#5659, "enforce the settings lock on delete,
# import and reset"). SettingsManager already refuses when
# locked, so the write cannot happen either way; this repeats
# the check at the route so a locked instance answers 403
# rather than 200 with nothing written, which is what main's
# own comment gives as the reason. Without it the merge that
# brought #5659 in would have silently dropped the fix, since
# it landed in a Flask file this migration deletes.
if settings_manager.settings_locked:
return JSONResponse(
{"error": "Settings are locked and cannot be imported"},
status_code=403,
)
# See the identical call in reset_to_defaults: this flag is
# required so a bulk import cannot overwrite env-locked settings,
# and it defaults to False.
settings_manager.load_from_defaults_file(
preserve_environment_locked=True
)
imported_setting_keys = tuple(settings_manager.default_settings)
invalidate_settings_caches(username)
reschedule_document_jobs_if_needed(username, imported_setting_keys)
reschedule_zotero_jobs_if_needed(username, imported_setting_keys)
return {"message": "Settings imported successfully"}
except Exception:
logger.exception("Error importing settings")
return JSONResponse(
{"error": "Failed to import settings"}, status_code=500
)
@router.get("/api/categories")
def api_get_categories(
request: Request,
username: Annotated[str, Depends(require_auth)],
):
"""Get all setting categories"""
try:
with get_user_db_session(username) as db_session:
# Get all distinct categories
categories = db_session.query(Setting.category).distinct().all()
category_list = [c[0] for c in categories if c[0] is not None]
return {"categories": category_list}
except Exception:
logger.exception("Error getting categories")
return JSONResponse(
{"error": "Failed to retrieve settings"}, status_code=500
)
@router.get("/api/types")
def api_get_types(
request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Get all setting types"""
try:
# Get all setting types
types = [t.value for t in SettingType]
return {"types": types}
except Exception:
logger.exception("Error getting types")
return JSONResponse(
{"error": "Failed to retrieve settings"}, status_code=500
)
@router.get("/api/ui_elements")
def api_get_ui_elements(
request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Get all UI element types"""
try:
# The types a settings read can convert. A new setting with any
# other ui_element is rejected on write.
ui_elements = list(UI_ELEMENT_TO_SETTING_TYPE)
return {"ui_elements": ui_elements}
except Exception:
logger.exception("Error getting UI elements")
return JSONResponse(
{"error": "Failed to retrieve settings"}, status_code=500
)
@router.get("/api/available-models")
@router.post("/api/available-models")
async def api_get_available_models(
request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Read cached models on GET; discover or refresh only on POST.
``GET`` returns only the policy-filtered model cache: a cold, expired
or filtered cache answers with an empty model list, and a ``GET`` never
performs provider-specific credential lookups, contacts a provider or
writes the cache. It still loads the strict settings snapshot for policy.
Discovery calls providers with the user's stored API keys and rewrites
their cached ``ProviderModel`` rows, so it is a state change accepted
only on the CSRF-protected ``POST``:
* a ``POST`` without a refresh query returns the fresh cached rows and
discovers every provider only on a cache miss;
* ``POST ?force_refresh=true`` bypasses and replaces the whole cache;
* ``POST ?refresh_provider=<p>`` re-discovers that provider (or every
provider, when the cache has no usable rows). A target takes
precedence over ``force_refresh=true``, so a targeted refresh is never
widened into a full one.
A ``GET`` carrying ``refresh_provider`` or ``force_refresh=true``
answers 405 (``Allow: POST``) without touching the cache or any
provider.
Discovery runs on its own executor and does not continue the provider
loop after cancellation.
"""
# Parse as bool — a raw string (non-empty) is always truthy, so the old
# code always took the force-refresh path, deleting every cached model
# on every request.
force_refresh_requested = (
request.query_params.get("force_refresh", "false").lower() == "true"
)
# Refused here, on the event loop, so a 405 never waits for a worker.
if request.method != "POST" and (
force_refresh_requested or request.query_params.get("refresh_provider")
):
raise HTTPException(
status_code=405,
detail="Use POST to refresh models",
headers={"Allow": "POST"},
)
cancelled = threading.Event()
try:
# Cache-only reads must not queue behind slow provider discovery.
if request.method != "POST":
return await run_db_sync(
_get_available_models, request, username, cancelled
)
# Discovery can wait out one provider timeout after another. Keep
# those calls off the workers used by authenticated DB requests.
return await run_model_discovery_sync(
_get_available_models, request, username, cancelled
)
finally:
# Canceling an awaiting task cannot interrupt synchronous SDK I/O.
# The worker must stop after its current provider returns, before
# starting another request or replacing the user's cached models.
cancelled.set()
def _get_available_models(
request: Request, username: str, cancelled: threading.Event
):
"""Run discovery and DB access on the worker that owns their cleanup."""
def check_cancelled():
if cancelled.is_set():
raise asyncio.CancelledError
check_cancelled()
# Only the CSRF-protected POST may discover providers or write the model
# cache. Any other method reads the policy-filtered cache and stops there.
discovery_allowed = request.method == "POST"
endpoint_start = time.perf_counter()
try:
# request comes from FastAPI parameter
from ...database.models.providers import ProviderModel
# Optional targeted refresh: re-discover ONLY this provider and
# merge the result into the cached catalog (used after a provider
# API key is saved — the plain cache read would keep that
# provider's stale/empty list for up to 24h, and a full refresh
# re-probes every provider serially). POST-only: a GET carrying it
# was refused with 405 above.
refresh_provider = (
normalize_provider(
request.query_params.get("refresh_provider", "") or ""
)
if discovery_allowed
else None
)
# The forced (full) refresh: POST ?force_refresh=true without a
# target. A POST without the flag stays cache-first (it discovers
# only on a cache miss), and a target takes precedence over the
# flag, so a targeted POST stays targeted.
force_refresh = (
discovery_allowed
and not refresh_provider
and request.query_params.get("force_refresh", "false").lower()
== "true"
)
# Resolve the egress policy BEFORE the model cache is read or any
# provider is discovered/contacted. Fails closed (PolicyDeniedError).
policy_context, policy_snapshot = _resolve_model_discovery_policy(
username
)
# Get all auto-discovered providers. Every provider is advertised to
# the UI; the egress policy marks blocked ones as disabled (with a
# reason) instead of removing them. Removing them silently made the
# "Model Provider" dropdown look short after configuring a cloud API
# key, leading users to assume the key wasn't picked up — and left
# the front-end code that renders the reason
# (static/js/components/custom_dropdown.js, research.js, settings.js)
# unreachable. The per-provider MODELS list below is still filtered
# so we never actually call a blocked provider (#5922 / #5662).
from ...llm.providers import get_discovered_provider_options
options = list(get_discovered_provider_options())
provider_options = _provider_options_for_snapshot(
options, policy_context, policy_snapshot
)
# Grading uses its own endpoint override. Keep this copied snapshot
# out of research model discovery, credential reads and model caches.
#
# The override is read back from the SAME snapshot the policy context
# was built from, not through a second settings read: the snapshot
# already carries the LDR_* overlay for this key, so the two agree
# (no TOCTOU between classifying the endpoint and reading it), and it
# costs one fewer get_user_db_session per request. The route's own
# deny-before-credential-read ordering is unaffected either way:
# _resolve_model_discovery_policy above has already opened a session
# and read the whole snapshot before anything here runs, and the
# per-provider api_key_setting reads still happen only after the
# denial point.
benchmark_snapshot = dict(policy_snapshot)
benchmark_endpoint = unwrap_setting(
policy_snapshot.get(
"benchmark.evaluation.endpoint_url",
"https://openrouter.ai/api/v1",
)
)
# Match get_llm's explicit endpoint-override normalization.
benchmark_snapshot["llm.openai_endpoint.url"] = (
benchmark_endpoint.strip()
if isinstance(benchmark_endpoint, str)
else benchmark_endpoint
)
benchmark_provider_options = _provider_options_for_snapshot(
options, policy_context, benchmark_snapshot
)
# Add remaining hardcoded providers (complex local providers not yet migrated)
# Available models by provider
providers: dict[str, Any] = {}
# Cached rows of a targeted refresh's provider, set aside when the
# target's cache entries are dropped for re-fetch. Restored to the
# response if the re-fetch fails, so a transient upstream error
# can't blank the provider's catalog.
stale_target_rows: list | None = None
# Whether the cache read produced ANY rows (before the targeted
# refresh pops its provider). Distinct from a post-pop empty
# ``providers`` dict, which just means the cache held only the
# target — not that it is cold.
cache_had_rows = False
# Check database cache first (unless force_refresh is True)
if not force_refresh:
try:
# Define cache expiration (24 hours)
cache_expiry = datetime.now(UTC) - timedelta(hours=24)
# Get cached models from database
with get_user_db_session(username) as db_session:
cached_models = (
db_session.query(ProviderModel)
.filter(ProviderModel.last_updated > cache_expiry)
.all()
)
if cached_models:
logger.info(
f"Found {len(cached_models)} cached models in database"
)
# Group models by provider
for model in cached_models:
if (
policy_context.require_local_llm
and not _model_discovery_provider_allowed(
model.provider, policy_context, policy_snapshot
)
):
continue
provider_key = (
f"{normalize_provider(model.provider)}_models"
)
if provider_key not in providers:
providers[provider_key] = []
providers[provider_key].append(
{
"value": model.model_key,
"label": model.model_label,
"provider": model.provider.upper(),
}
)
# If we have cached data for all providers, return it —
# unless a targeted refresh was requested for a provider
# whose rows are stale or absent (e.g. right after its
# API key was saved): drop just that provider's cached
# entries and fall through to a single-provider fetch.
cache_had_rows = bool(providers)
if providers and refresh_provider:
# nosemgrep: semgrep.rules.sql-string-concatenation, reason: Dictionary key only
stale_key = f"{refresh_provider}_models"
# Drop the target's cached entries (if any) and
# fall through to a single-provider re-fetch. Keep
# them aside for restoration if the re-fetch fails.
stale_target_rows = providers.pop(stale_key, None)
elif providers:
_log_available_models_duration(
endpoint_start, cache_hit=True
)
logger.info("Returning cached models from database")
return {
"provider_options": provider_options,
"benchmark_provider_options": benchmark_provider_options,
"providers": providers,
}
except PolicyDeniedError:
raise
except Exception:
logger.warning("Error reading cached models from database")
if not discovery_allowed:
raise
# A CSRF-protected POST may recover by fetching fresh data.
# Even an ordinary cache miss can populate or replace persisted rows.
# GET must never reach model listing, credential lookup or cache writes.
# Return the same response shape for cold, expired or filtered caches.
if not discovery_allowed:
_log_available_models_duration(endpoint_start, cache_hit=False)
return {
"provider_options": provider_options,
"benchmark_provider_options": benchmark_provider_options,
"providers": providers,
}
if refresh_provider and not cache_had_rows:
# Cold cache (fresh install, or every row older than 24h): a
# targeted refresh would return a one-provider catalog that
# the client would cache as the whole world. Fall back to a
# full discovery — the plain cold-cache path does exactly that.
logger.info(
"Targeted refresh with an empty model cache: "
"falling back to full discovery"
)
refresh_provider = None
# Ollama / OpenAI / Anthropic model listing is handled by the
# auto-discovery loop below (their provider classes' list_models_for_api),
# leaving one provider-class fetch path. Those classes own base-URL
# validation and authentication, and the router does no duplicate network
# work. The removed Ollama probe used safe_get's request-time SSRF checks;
# its problem here was duplicate fetching, not missing validation.
# Fetch models from auto-discovered providers
from ...llm.providers import discover_providers
discovered_providers = discover_providers()
# If the effective egress posture is local-only, the user (or policy)
# has opted into local-only inference, so don't list cloud providers
# (OpenRouter, Google, XAI, IonOS, OpenAI, Anthropic, ...). We still
# list the local providers via their provider classes — which validate
# the URL (SSRF) and support auth headers — by filtering the discovered
# set rather than skipping discovery entirely. The filter classifies
# each provider's configured ENDPOINT (evaluate_llm_endpoint), so a
# nominally-local provider pointed at a public URL is dropped too; a
# static LOCAL_PROVIDERS name check would have kept it.
if policy_context.require_local_llm:
all_discovered_providers = discovered_providers
discovered_providers = {
key: info
for key, info in all_discovered_providers.items()
if _model_discovery_provider_allowed(
key, policy_context, policy_snapshot
)
}
logger.bind(policy_audit=True).info(
"local-only egress posture: limiting discovered model lists "
"to endpoint-approved local providers",
kept=list(discovered_providers.keys()),
skipped=[
key
for key in all_discovered_providers
if key not in discovered_providers
],
)
if refresh_provider and not force_refresh:
# Targeted refresh: only the named provider is re-fetched (and
# only if it survived the policy filter above). Unknown
# provider names degrade to a plain cache read (nothing to
# re-fetch) — the merged `providers` dict below still returns
# the other providers' cached rows.
discovered_providers = {
key: info
for key, info in discovered_providers.items()
if key.lower() == refresh_provider
}
targeted_fetch_failed = False
fetched_provider_settings = {}
for provider_key, provider_info in discovered_providers.items():
check_cancelled()
provider_models = []
try:
logger.info(
f"Fetching models from {provider_info.provider_name}"
)
# Get the provider class
provider_class = provider_info.provider_class
# Get API key if configured
api_key = _get_setting_from_session(
provider_class.api_key_setting, username, ""
)
# Get base URL if provider has configurable URL
provider_base_url: str | None = None
url_setting = getattr(provider_class, "url_setting", None)
if url_setting:
provider_base_url = _get_setting_from_session(
url_setting, username, ""
)
fetched_settings = {}
if provider_class.api_key_setting is not None:
fetched_settings[provider_class.api_key_setting] = api_key
if url_setting:
fetched_settings[url_setting] = provider_base_url
fetched_provider_settings[
f"{normalize_provider(provider_key)}_models"
] = fetched_settings
if policy_context.require_local_llm:
provider_snapshot = dict(policy_snapshot)
if url_setting:
provider_snapshot[url_setting] = provider_base_url
if not _model_discovery_provider_allowed(
provider_key, policy_context, provider_snapshot
):
continue
# Use the provider's list_models_for_api method. This is the
# single remaining cloud fetch path (OpenAI's models.list()
# among them), so it carries PR #3483's provider-fetch timer.
provider_fetch_start = time.perf_counter()
models = provider_class.list_models_for_api(
api_key, provider_base_url
)
provider_fetch_ms = (
time.perf_counter() - provider_fetch_start
) * 1000
if provider_fetch_ms > 1000:
logger.info(
f"{provider_key} list_models_for_api took "
f"{provider_fetch_ms:.0f}ms"
)
else:
logger.debug(
f"{provider_key} list_models_for_api took "
f"{provider_fetch_ms:.0f}ms"
)
# Format models for the API response
for model in models:
provider_models.append(
{
"value": model["value"],
"label": model[
"label"
], # Use provider's label as-is
"provider": provider_key,
}
)
logger.info(
f"Successfully fetched {len(provider_models)} models from {provider_info.provider_name}"
)
except PolicyDeniedError:
raise
except Exception:
logger.exception(
f"Error getting {provider_info.provider_name} models"
)
if (
refresh_provider
and provider_key.lower() == refresh_provider
):
# The targeted provider's re-fetch failed: don't let a
# transient upstream error blank its catalog — the
# cached rows set aside earlier are restored below and
# the DB rows are left untouched.
targeted_fetch_failed = True
# Set models in providers dict using lowercase key
providers[f"{normalize_provider(provider_key)}_models"] = (
provider_models
)
logger.info(
f"Final {provider_key} models count: {len(provider_models)}"
)
# Also check after the final provider, including failed fetches.
check_cancelled()
# Restore the targeted provider's cached rows when its re-fetch
# failed (response keeps the last-known-good catalog).
if targeted_fetch_failed and stale_target_rows is not None:
providers[f"{refresh_provider}_models"] = stale_target_rows
# ``list_models_for_api`` converts every upstream failure into an
# empty list (its catch-all never raises), so the exception path
# above cannot fire for real network errors. Treat "targeted
# refresh produced zero models while non-empty cached rows were
# set aside" as a failed probe too: keep the last-known-good
# catalog and skip the cache write, so a transient outage during
# a key re-save cannot blank the provider's cached models.
if (
refresh_provider
and not force_refresh
and stale_target_rows
and not providers.get(f"{refresh_provider}_models")
):
targeted_fetch_failed = True
providers[f"{refresh_provider}_models"] = stale_target_rows
# Save fetched models to database cache. A targeted refresh only
# persists the refreshed provider's rows — other providers keep
# their cached rows and TTLs untouched. A failed targeted re-fetch
# persists nothing (the cached rows stay valid).
providers_to_save = providers
if refresh_provider and not force_refresh:
# nosemgrep: semgrep.rules.sql-string-concatenation, reason: Dictionary key only
target_key = f"{refresh_provider}_models"
providers_to_save = (
{}
if targeted_fetch_failed
else {
key: models
for key, models in providers.items()
if key == target_key
}
)
if force_refresh or providers_to_save:
# We fetched fresh data, save it to database
with get_user_db_session(username) as db_session:
try:
# Take SQLite's writer lock only AFTER all network calls.
# Checking settings and writing models under the same lock
# prevents a key/URL change (including in another worker)
# from racing between the check and the cache replacement.
db_session.connection().exec_driver_sql("BEGIN IMMEDIATE")
current_providers_to_save = {
key: models
for key, models in providers_to_save.items()
if _model_discovery_settings_unchanged(
db_session, fetched_provider_settings.get(key, {})
)
}
superseded = len(current_providers_to_save) != len(
providers_to_save
)
providers_to_save = current_providers_to_save
# A superseded full refresh must also leave the newer
# provider's rows intact instead of clearing the catalog.
if force_refresh and not superseded:
# When force refresh, clear ALL cached models to remove any stale data
# from old code versions or deleted providers
deleted_count = db_session.query(ProviderModel).delete()
logger.info(
f"Force refresh: cleared all {deleted_count} cached models"
)
else:
# Clear old cache entries only for providers we're updating
for provider_key in providers_to_save:
provider_name = provider_key.replace(
"_models", ""
).upper()
db_session.query(ProviderModel).filter(
ProviderModel.provider == provider_name
).delete()
# Insert new models. A targeted refresh stamps its
# rows with the oldest ``last_updated`` among the other
# providers' fresh cached rows so the whole catalog
# still expires at once: the cache read returns any
# fresh rows as the complete catalog, so rows that
# outlived the others would hide every other
# provider's models until they expired too. Read under
# the writer lock, so a full refresh that committed
# after this request's cache read is taken into
# account.
row_time = datetime.now(UTC)
if refresh_provider and not force_refresh:
other_row_times = [
model.last_updated
for model in db_session.query(ProviderModel)
.filter(
ProviderModel.last_updated
> row_time - timedelta(hours=24)
)
.all()
if normalize_provider(model.provider)
!= refresh_provider
and isinstance(model.last_updated, datetime)
]
if other_row_times:
row_time = min(
row_time,
*(
t if t.tzinfo else t.replace(tzinfo=UTC)
for t in other_row_times
),
)
for provider_key, models in providers_to_save.items():
provider_name = provider_key.replace(
"_models", ""
).upper()
for model in models:
if (
isinstance(model, dict)
and "value" in model
and "label" in model
):
new_model = ProviderModel(
provider=provider_name,
model_key=model["value"],
model_label=model["label"],
last_updated=row_time,
)
db_session.add(new_model)
db_session.commit()
logger.info("Successfully cached models to database")
except Exception:
logger.exception("Error saving models to database cache")
db_session.rollback()
# Return all options
_log_available_models_duration(endpoint_start, cache_hit=False)
return {
"provider_options": provider_options,
"benchmark_provider_options": benchmark_provider_options,
"providers": providers,
}
except PolicyDeniedError as exc:
reason = exc.decision.reason
status_code = 503 if reason == "settings_unavailable" else 400
logger.bind(policy_audit=True).warning(
"available-model discovery denied by egress policy", reason=reason
)
_log_available_models_duration(
endpoint_start, cache_hit=False, error=True
)
return JSONResponse(
{
"status": "error",
"message": f"Egress policy refused this request: {reason}",
},
status_code=status_code,
)
except Exception:
logger.exception("Error getting available models")
_log_available_models_duration(
endpoint_start, cache_hit=False, error=True
)
return JSONResponse(
{
"status": "error",
"message": "Failed to retrieve available models",
},
status_code=500,
)
def _log_available_models_duration(
start: float, cache_hit: bool, error: bool = False
) -> None:
"""Log /api/available-models endpoint duration.
Uses INFO when the endpoint took > 1s (indicating a real provider fetch
latency worth flagging), DEBUG otherwise. This is the likely culprit for
Path C (LLM provider timeout masquerading as backend hang) in the
login-hang investigation (PR #3483 / #5961).
"""
elapsed_ms = (time.perf_counter() - start) * 1000
path = (
"error"
if error
else ("cache hit" if cache_hit else "full provider fetch")
)
if elapsed_ms > 1000:
logger.info(f"/api/available-models ({path}) took {elapsed_ms:.0f}ms")
else:
logger.debug(f"/api/available-models ({path}) took {elapsed_ms:.0f}ms")
def _get_engine_icon_and_category(
engine_data: dict, engine_class=None
) -> tuple:
"""
Get icon emoji and category label for a search engine based on its attributes.
Args:
engine_data: Engine configuration dictionary
engine_class: Optional loaded engine class to check attributes
Returns:
Tuple of (icon, category) strings
"""
# Check attributes from either the class or the engine data
if engine_class:
is_scientific = getattr(engine_class, "is_scientific", False)
is_generic = getattr(engine_class, "is_generic", False)
is_local = getattr(engine_class, "is_local", False)
is_news = getattr(engine_class, "is_news", False)
is_code = getattr(engine_class, "is_code", False)
else:
is_scientific = engine_data.get("is_scientific", False)
is_generic = engine_data.get("is_generic", False)
is_local = engine_data.get("is_local", False)
is_news = engine_data.get("is_news", False)
is_code = engine_data.get("is_code", False)
# Check books attribute
if engine_class:
is_books = getattr(engine_class, "is_books", False)
else:
is_books = engine_data.get("is_books", False)
# Return icon and category based on engine type
# Priority: local > scientific > news > code > books > generic > default
if is_local:
return "📁", "Local RAG"
if is_scientific:
return "🔬", "Scientific"
if is_news:
return "📰", "News"
if is_code:
return "💻", "Code"
if is_books:
return "📚", "Books"
if is_generic:
return "🌐", "Web Search"
return "🔍", "Search"
# Ported verbatim from the Flask ``settings_routes`` (#5221 / issue
# #5204). The body is framework-agnostic — it only consults the egress
# PDP and the logger — so nothing needed adapting; only its caller did.
# This landed on main against a module this branch had already deleted,
# so the merge dropped it while keeping the frontend that depends on it.
def _classify_options_for_egress(
engine_options: list,
*,
egress_scope: str,
primary_engine: str,
settings_snapshot: dict,
username: Optional[str],
search_engines: Optional[dict] = None,
) -> None:
"""Stamp each engine option with an ``egress: {allowed, reason}`` field.
Used by ``api_get_available_search_engines`` when the caller passes
``?egress_scope=…&primary=…``: the frontend needs to know which
options are selectable under the active scope so it can disable
(or hide) the rest in the dropdown. Issue #5204.
The decision is taken through the same PDP the request-boundary
precheck uses (``evaluate_engine``) so the dropdown's disabled set
and the server's 400 denials stay perfectly aligned. Dropdown filtering
strictly reflects PDP allowed decisions; frontend selection reconciliation
handles updating any invalid primary selection when scope changes. The factory PEP
still enforces at instantiation time; this is a UX filter, not a security boundary.
After the PDP pass it applies ``_apply_guarded_url_overlay``, which
can deny an engine the PDP allowed (an unapproved private instance
URL). That overlay is scope-independent and therefore also runs when
the caller did NOT opt into scope filtering — see the route — and on
every degraded early return below (an unimportable policy module, an
unknown ``?egress_scope=``): it needs only the settings snapshot, not
the PDP context, and the runtime blocks the URL regardless, so
skipping it there would make a guard-denied engine read as selectable.
Operates in place; safe to call on a freshly built option list.
Failures are swallowed per option (logged) — a single bad engine
must not blank the whole dropdown.
"""
try:
from ...security.egress.policy import (
context_from_snapshot,
evaluate_engine,
resolve_run_primary_engine,
)
except Exception: # pragma: no cover - defensive
logger.exception(
"egress policy unavailable; emitting unfiltered options"
)
# The URL guard does not ride on the PDP — it only needs the
# snapshot — so it still runs when the PDP is unavailable.
_apply_guarded_url_overlay(engine_options, settings_snapshot)
return
if not isinstance(settings_snapshot, dict):
# Programming error: the route always passes a snapshot. Log it
# loudly so a future caller-side change is debuggable instead of
# silently falling back to the unfiltered list (PR #5221 review).
logger.error(
"_classify_options_for_egress received a non-dict "
"settings_snapshot (type={}); emitting unfiltered options",
type(settings_snapshot).__name__,
)
# Match every other degraded early return: the overlay is a
# no-op here (it guards on isinstance(settings_snapshot, dict)
# itself) since there's no dict to read a URL from, but calling
# it keeps this branch consistent with the docstring above and
# fail-safe if a future caller ever reaches this branch with
# something the overlay CAN read.
_apply_guarded_url_overlay(engine_options, settings_snapshot)
return
# Build an evaluation snapshot that reflects the requested scope and
# primary engine parameter overrides sent by the frontend (issue #5204).
eval_snapshot = dict(settings_snapshot)
if egress_scope:
eval_snapshot["policy.egress_scope"] = egress_scope
if primary_engine:
eval_snapshot["search.tool"] = primary_engine
# The precheck builds an EgressContext via context_from_snapshot; the
# adaptive resolution requires a primary, so fall back to the supplied
# primary and ultimately the saved search.tool.
try:
try:
primary = primary_engine or resolve_run_primary_engine(
eval_snapshot
)
except ValueError:
# ``resolve_run_primary_engine`` raises ValueError when
# ``search.tool`` is missing/blank/non-string and no
# ``default`` is given. That's the only documented failure
# mode — narrow the catch so unrelated bugs (e.g. an
# AttributeError on a future code path) surface instead of
# being silently swallowed (PR #5221 review).
primary = primary_engine or eval_snapshot.get("search.tool", "")
try:
ctx = context_from_snapshot(
eval_snapshot,
primary,
username=username,
)
except Exception:
# ``context_from_snapshot`` raises ``PolicyDeniedError`` for
# an unknown scope (``unknown_egress_scope``) and ``ValueError``
# for a malformed snapshot; either way the precheck would
# 400 the run. Stamp a permissive decision so the frontend
# falls back to the precheck instead of a half-blanked
# dropdown. Use logger.exception (dev-only traceback, no
# exc_info kwarg on logger.warning which would expose a
# full traceback at WARNING level in production — PR #5221
# review).
logger.exception(
"_classify_options_for_egress: context build failed; "
"emitting permissive policy_unavailable decisions"
)
for opt in engine_options:
opt["egress"] = {
"allowed": True,
"reason": "policy_unavailable",
}
# Permissive on SCOPE only. The URL guard is independent of
# the PDP context that just failed to build, and the runtime
# still blocks the URL, so a guard-denied engine must not read
# as selectable on this degraded path either.
_apply_guarded_url_overlay(engine_options, eval_snapshot)
return
except Exception: # pragma: no cover - defensive
logger.exception(
"egress context build failed; emitting unfiltered options"
)
_apply_guarded_url_overlay(engine_options, eval_snapshot)
return
for opt in engine_options:
engine_id = opt.get("value")
try:
metadata = search_engines.get(engine_id) if search_engines else None
decision = evaluate_engine(
engine_id,
ctx,
settings_snapshot=eval_snapshot,
metadata=metadata,
)
opt["egress"] = {
"allowed": bool(decision.allowed),
"reason": decision.reason,
}
except Exception: # pragma: no cover - defensive
logger.exception(f"egress decision failed for engine {engine_id}")
opt["egress"] = {"allowed": True, "reason": "decision_error"}
# Guarded engine-URL overlay: a public engine whose configured private
# URL lacks operator approval self-disables at runtime, so the dropdown
# should gray it out too. Applied here (rather than in the caller) so
# every code path that stamps egress decisions also carries the guard.
# Deliberately scope-INDEPENDENT — see _apply_guarded_url_overlay.
_apply_guarded_url_overlay(engine_options, eval_snapshot)
def _apply_guarded_url_overlay(
engine_options: list, settings_snapshot: dict
) -> None:
"""Gray out engines whose configured instance URL the runtime will refuse.
A PUBLIC-nature engine (SearXNG and friends) pointed at a private /
loopback instance URL without operator approval self-disables at init
and silently contributes zero results to the run. This overlay stamps
``egress={"allowed": False, "reason": "private_url_unapproved"}`` on
those options so the picker grays them out with an explanatory note.
SCOPE-INDEPENDENT BY CONSTRUCTION. The approval resolver this rides on
(``resolve_engine_allow_private_ips``) deliberately ignores
``policy.egress_scope`` — it is a user-editable dropdown, so honouring
it would be a self-service SSRF bypass — which means the runtime blocks
the URL under EVERY scope. The overlay must therefore run under every
scope too, including the shipped ``adaptive`` default and the
``unprotected`` escape hatch, and NOT only when the caller opted into
scope filtering via ``?egress_scope=``. Before PR #5648's follow-up
this lived inside the ``apply_egress_filter`` branch and could only
ever fire under ``public_only`` (under ``private_only`` a public engine
is already denied for scope reasons), i.e. never on a default install.
ADVISORY, NOT AUTHORITATIVE — it is a strict subset of what the runtime
enforces. ``check_private_engine_url_blocked`` is deliberately
DNS-free (it must not turn a settings-page render into a resolver
round-trip, nor let a hostile URL make the render path probe an
internal name), so a private-DNS hostname (``searx.internal`` -> 10.x)
and a short-form literal (``127.1``) are NOT caught here even though
the runtime's ``validate_url`` resolves and blocks them. The overlay
therefore fails OPEN: an engine it leaves selectable may still be
refused at run time. For that residual gap the ONLY backstop is the
runtime's log-panel ERROR — NOT the research form's warning banner,
which ``warning_checks`` emits from this very same DNS-free check and
which therefore stays silent on exactly the URLs the overlay misses
(and is additionally suppressed once the user dismisses it, which the
overlay ignores).
It effectively never fails CLOSED — nothing the runtime would fetch is
grayed out here. The one theoretical exception is a host name ending
in ``.local``, which ``is_private_ip`` classifies by suffix: if a
non-conforming resolver or a ``hosts`` entry maps it to a PUBLIC
address the runtime would allow it while this overlay grays it out.
``.local`` is reserved for mDNS (RFC 6762), so that is a
misconfiguration rather than a supported setup.
Options already carrying a denial (``allowed: False``) are left alone
so a scope denial keeps its more specific reason. Operates in place;
every failure is swallowed per engine so one bad descriptor cannot
blank the dropdown.
"""
if not engine_options or not isinstance(settings_snapshot, dict):
return
try:
from ...security.egress.validators import (
guarded_engine_url_descriptors,
)
from ...security.egress.warnings import (
check_private_engine_url_blocked,
)
from ...utilities.type_utils import unwrap_setting
guarded_urls = {
d.engine_name: d
for d in guarded_engine_url_descriptors()
if d.is_public
}
except Exception: # pragma: no cover - defensive
logger.exception("guarded engine-URL overlay unavailable")
return
for opt in engine_options:
# Everything that touches the option — including the id lookup and
# the existing-decision read — runs inside the try, so a malformed
# entry is swallowed per engine as the docstring promises rather
# than aborting the overlay for the rest of the list.
desc = None
try:
desc = guarded_urls.get(opt.get("value"))
if desc is None:
continue
existing = opt.get("egress")
if isinstance(existing, dict) and not existing.get("allowed", True):
continue
url_value = unwrap_setting(
settings_snapshot.get(desc.url_setting, "")
)
if check_private_engine_url_blocked(
desc.engine_name,
desc.engine_name,
desc.url_setting,
url_value,
True,
False,
):
opt["egress"] = {
"allowed": False,
"reason": "private_url_unapproved",
}
except Exception:
engine_name = desc.engine_name if desc is not None else "unknown"
logger.exception(
f"guarded-URL overlay failed for engine {engine_name}"
)
@router.get("/api/available-search-engines")
def api_get_available_search_engines(
request: Request,
username: Annotated[str, Depends(require_auth)],
):
"""Get available search engines.
Optional query params (issue #5204):
``egress_scope`` — when set, each option gets an
``egress: {allowed, reason}`` field matching the same PDP the
request-boundary precheck uses. The frontend uses this to disable
(or hide) options that would be refused under the active scope.
``primary`` — the user's saved primary search tool, used by the
PDP for strict / adaptive scope resolution.
When ``egress_scope`` is absent the SCOPE filtering is skipped, but
the guarded engine-URL overlay still runs: it stamps
``egress: {allowed: false, reason: "private_url_unapproved"}`` on any
public engine whose configured instance URL the runtime will refuse
for lack of operator approval. That guard ignores
``policy.egress_scope`` by design, so gating the overlay on the
opt-in would have hidden it on every default (``adaptive``) install.
Options that are not guard-blocked keep the historical shape (no
``egress`` key), so existing callers — the settings page, the news
form — are unaffected except for the engines they could not have
used anyway.
"""
try:
# Issue #5204: optional egress-scope filter. The scope/primary
# query params opt INTO a per-option egress decision; without
# them the response is the historical, unfiltered list.
# Flask read these from request.args; the FastAPI equivalent is
# request.query_params.
requested_scope = (
(request.query_params.get("egress_scope") or "").strip().lower()
)
requested_primary = (request.query_params.get("primary") or "").strip()
apply_egress_filter = requested_scope in (
"private_only",
"public_only",
)
with get_user_db_session(username) as db_session:
settings_manager = get_settings_manager(db_session, username)
# Get search engines using the same approach as search_engines_config.py
from ...web_search_engines.search_engines_config import (
_resolve_api_key,
search_config,
)
from ...web_search_engines.engine_groups import (
classify_engine_group,
effective_group,
group_label,
group_order,
)
search_engines = search_config(
username=username, db_session=db_session
)
# Get user's favorites using SettingsManager
favorites = settings_manager.get_setting("search.favorites", [])
if not isinstance(favorites, list):
favorites = []
# Use the same effective settings for credentials and policy. Only
# key presence is returned; credential values stay on the server.
policy_snapshot = settings_manager.get_settings_snapshot() or {}
# Extract search engines from config
engines_dict = {}
engine_options = []
if search_engines:
# Format engines for API response with metadata
from ...security.module_whitelist import (
get_safe_module_class,
SecurityError,
)
for engine_id, engine_data in search_engines.items():
if not engine_data.get("supports_query_search", True):
continue
# Try to load the engine class to get metadata
engine_class = None
try:
module_path = engine_data.get("module_path")
class_name = engine_data.get("class_name")
if module_path and class_name:
# Use secure whitelist-validated import
engine_class = get_safe_module_class(
module_path, class_name
)
except SecurityError:
logger.warning(
f"Security: Blocked unsafe module for {engine_id}"
)
except Exception as e:
logger.debug(
f"Could not load engine class for {engine_id}: {e}"
)
# Get icon and category from engine attributes
icon, category = _get_engine_icon_and_category(
engine_data, engine_class
)
# Check if engine requires an API key
requires_api_key = engine_data.get(
"requires_api_key", False
)
has_api_key = bool(
_resolve_api_key(
engine_id, engine_data, policy_snapshot
)
)
# Build display name with icon, category, and API key status
base_name = engine_data.get("display_name", engine_id)
if requires_api_key:
label = f"{icon} {base_name} ({category}, API key)"
else:
label = f"{icon} {base_name} ({category}, Free)"
# Check if engine is a favorite
is_favorite = engine_id in favorites
# Classify the engine into a selector band. base_group
# ignores favorite status (used by the frontend to move an
# engine back to its category when un-starred); the
# effective band is the Favorites overlay when starred.
# See engine_groups.py.
base_group = classify_engine_group(
engine_id, category, requires_api_key
)
shown_group = effective_group(base_group, is_favorite)
engines_dict[engine_id] = {
"display_name": base_name,
"description": engine_data.get("description", ""),
"strengths": engine_data.get("strengths", []),
"icon": icon,
"category": category,
"requires_api_key": requires_api_key,
"has_api_key": has_api_key,
"is_favorite": is_favorite,
}
engine_options.append(
{
"value": engine_id,
"label": label,
"icon": icon,
"category": category,
"requires_api_key": requires_api_key,
"has_api_key": has_api_key,
"is_favorite": is_favorite,
"group": shown_group,
"group_label": group_label(shown_group),
"group_order": group_order(shown_group),
"base_group": base_group,
"base_group_label": group_label(base_group),
"base_group_order": group_order(base_group),
# Describes automatic tool discovery only; an
# explicit primary selection remains independent.
"agent_enabled": engine_data.get(
"agent_enabled", True
),
}
)
# Sort engine_options by band order (favorites band first), then
# alphabetically by label within each band.
engine_options.sort(
key=lambda x: (
x.get("group_order", 999),
x.get("label", "").lower(),
)
)
# If no engines found, log the issue but return empty list
if not engine_options:
logger.warning("No search engines found in configuration")
# Issue #5204: when the caller opts in via ?egress_scope=&primary=,
# stamp each option with the PDP's per-engine decision so the
# frontend can disable/hide the ones that would be refused at
# submit time. UNPROTECTED and missing-scope callers skip the
# SCOPE filtering (the historical shape) but still get the
# guarded engine-URL overlay: that guard is scope-independent by
# design (see ``_apply_guarded_url_overlay``), so an engine the
# runtime will refuse must read as disabled under the shipped
# ``adaptive`` default too, not only under ``public_only``.
# A snapshot failure must not be replaced with an empty policy:
# the filter and the overlay would then deny nothing, so the
# list would be served unfiltered. Let it reach the handlers
# below, which return an error instead of a list.
if apply_egress_filter:
# Runs the guarded-URL overlay itself, after the PDP pass.
_classify_options_for_egress(
engine_options,
egress_scope=requested_scope,
primary_engine=requested_primary,
settings_snapshot=policy_snapshot,
username=username,
search_engines=search_engines,
)
else:
_apply_guarded_url_overlay(engine_options, policy_snapshot)
return {
"engines": engines_dict,
"engine_options": engine_options,
"favorites": favorites,
}
except SettingsValueError as error:
return _settings_value_error_response("available search engines", error)
except Exception:
logger.exception("Error getting available search engines")
return JSONResponse(
{"error": "Failed to retrieve search engines"}, status_code=500
)
@router.get("/api/search-favorites")
def api_get_search_favorites(
request: Request,
username: Annotated[str, Depends(require_auth)],
):
"""Get the list of favorite search engines for the current user"""
try:
with get_user_db_session(username) as db_session:
settings_manager = get_settings_manager(db_session, username)
favorites = settings_manager.get_setting("search.favorites", [])
if not isinstance(favorites, list):
favorites = []
return {"favorites": favorites}
except Exception:
logger.exception("Error getting search favorites")
return JSONResponse(
{"error": "Failed to retrieve favorites"}, status_code=500
)
@router.put("/api/search-favorites")
@settings_limit
async def api_update_search_favorites(
request: Request,
username: Annotated[str, Depends(require_auth)],
):
"""Update the list of favorite search engines for the current user"""
data, body_error = await read_json_dict(
request, "simple", "No data provided"
)
if body_error is not None:
return body_error
def _impl():
try:
favorites = data.get("favorites")
if favorites is None:
return JSONResponse(
{"error": "No favorites provided"}, status_code=400
)
if not isinstance(favorites, list):
return JSONResponse(
{"error": "Favorites must be a list"}, status_code=400
)
with get_user_db_session(username) as db_session:
settings_manager = get_settings_manager(db_session, username)
if settings_manager.settings_locked:
return JSONResponse(
{"error": "Settings are locked"}, status_code=403
)
if settings_manager.set_setting("search.favorites", favorites):
invalidate_settings_caches(username)
return {
"message": "Favorites updated successfully",
"favorites": favorites,
}
return JSONResponse(
{"error": "Failed to update favorites"}, status_code=500
)
except Exception:
logger.exception("Error updating search favorites")
return JSONResponse(
{"error": "Failed to update favorites"}, status_code=500
)
# SQLCipher PBKDF2 key derivation in get_user_db_session blocks the
# event loop for hundreds of ms on first call after login. Offload
# the entire DB-touching body so concurrent requests don't serialise.
return await run_db_sync(_impl)
@router.post("/api/search-favorites/toggle")
@settings_limit
async def api_toggle_search_favorite(
request: Request,
username: Annotated[str, Depends(require_auth)],
):
"""Toggle a search engine as favorite"""
data, body_error = await read_json_dict(
request, "simple", "No data provided"
)
if body_error is not None:
return body_error
def _impl():
try:
engine_id = data.get("engine_id")
if not engine_id:
return JSONResponse(
{"error": "No engine_id provided"}, status_code=400
)
with get_user_db_session(username) as db_session:
settings_manager = get_settings_manager(db_session, username)
if settings_manager.settings_locked:
return JSONResponse(
{"error": "Settings are locked"}, status_code=403
)
# Get current favorites
favorites = settings_manager.get_setting("search.favorites", [])
if not isinstance(favorites, list):
favorites = []
else:
# Make a copy to avoid modifying the original
favorites = list(favorites)
# Toggle the engine
is_favorite = engine_id in favorites
if is_favorite:
favorites.remove(engine_id)
is_favorite = False
else:
favorites.append(engine_id)
is_favorite = True
# Update the setting
if settings_manager.set_setting("search.favorites", favorites):
invalidate_settings_caches(username)
return {
"message": "Favorite toggled successfully",
"engine_id": engine_id,
"is_favorite": is_favorite,
"favorites": favorites,
}
return JSONResponse(
{"error": "Failed to toggle favorite"}, status_code=500
)
except Exception:
logger.exception("Error toggling search favorite")
return JSONResponse(
{"error": "Failed to toggle favorite"}, status_code=500
)
return await run_db_sync(_impl)
# Legacy routes for backward compatibility - these will redirect to the new routes
@router.get("/main")
def main_config_page(
request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Redirect to app settings page"""
return RedirectResponse(url="/settings/", status_code=302)
@router.get("/collections")
def collections_config_page(
request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Redirect to app settings page"""
return RedirectResponse(url="/settings/", status_code=302)
@router.get("/api_keys")
def api_keys_config_page(
request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Redirect to LLM settings page"""
return RedirectResponse(url="/settings/", status_code=302)
@router.get("/search_engines")
def search_engines_config_page(
request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Redirect to search settings page"""
return RedirectResponse(url="/settings/", status_code=302)
@router.get("/llm")
def llm_config_page(
request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Redirect to LLM settings page"""
return RedirectResponse(url="/settings/", status_code=302)
@router.post("/open_file_location")
def open_file_location(
request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Open the location of a configuration file.
Security: This endpoint is disabled for server deployments.
It only makes sense for desktop usage where the server and client are on the same machine.
"""
return JSONResponse(
{
"status": "error",
"message": "This feature is disabled. It is only available in desktop mode.",
},
status_code=403,
)
# CSRF token is injected globally via fastapi_app template globals
@router.get("/api/warnings")
def api_get_warnings(
request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Get current warnings based on settings"""
try:
warnings = calculate_warnings(username=username)
return {"warnings": warnings}
except Exception:
logger.exception("Error getting warnings")
return JSONResponse(
{"error": "Failed to retrieve warnings"}, status_code=500
)
@router.get("/api/backup-status")
def api_get_backup_status(
request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Get backup status for the current user.
Always answers 200 to an authenticated caller. ``enabled`` is ``None``
when reading the setting raises, for example because the user's database
cannot be opened; a read error inside the settings table falls back to
the default, as elsewhere. ``listing_available`` is ``False`` when the
backup directory cannot be listed. Neither failure looks like "disabled"
or "no backups yet".
"""
if not username:
return JSONResponse({"error": "Not authenticated"}, status_code=401)
from ...database.backup.backup_status import get_backup_status
try:
attempt_status = get_backup_status(username)
except Exception:
# get_backup_status already degrades on storage errors; this keeps
# the documented always-200 contract for anything unforeseen.
logger.exception("Error reading backup attempt status")
attempt_status = {"status_available": False, "last_attempt": None}
# Read the setting on its own: a settings failure must not be reported as
# an unreadable backup directory. None means unknown, not disabled.
backup_enabled = None
try:
backup_enabled = bool(
_get_setting_from_session("backup.enabled", username, True)
)
except Exception:
logger.exception("Error reading backup.enabled")
try:
from ...config.paths import get_user_backup_directory
from ...utilities.formatting import human_size
backup_dir = get_user_backup_directory(username)
# Sort by modification time (not filename) for robustness
backup_list = []
total_size = 0
from ...database.backup.backup_service import (
is_safe_glob_result,
list_backup_files,
)
# Not Path.glob: it swallows the error for an unreadable directory
# and would report it as "no backups yet".
for b in list_backup_files(backup_dir):
# Symlink/traversal guard (main #4663): skip a planted symlink whose
# target escapes the per-user backup dir, so its external file's
# name/size/mtime can't be exfiltrated through this endpoint.
if not is_safe_glob_result(b, backup_dir):
continue
try:
stat = b.stat()
total_size += stat.st_size
backup_list.append(
{
"filename": b.name,
"size_bytes": stat.st_size,
"size_human": human_size(stat.st_size),
"created_at": datetime.fromtimestamp(
stat.st_mtime, tz=timezone.utc
).isoformat(),
"_mtime": stat.st_mtime,
}
)
except FileNotFoundError:
continue
# Sort newest first by mtime, then remove internal field
backup_list.sort(key=lambda x: x["_mtime"], reverse=True)
for entry in backup_list:
del entry["_mtime"]
return {
"enabled": backup_enabled,
"listing_available": True,
"count": len(backup_list),
"backups": backup_list,
"total_size_bytes": total_size,
"total_size_human": human_size(total_size),
**attempt_status,
}
except Exception:
logger.exception("Error getting backup status")
# A storage/permission failure must not hide the very backup error
# this status screen is meant to explain. Unknown is not an empty
# directory; retain the attempt report and mark the listing unavailable.
return {
"enabled": backup_enabled,
"listing_available": False,
"count": None,
"backups": [],
"total_size_bytes": None,
"total_size_human": None,
**attempt_status,
}
@router.get("/api/ollama-status")
def check_ollama_status(
request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Check if Ollama is running and available"""
try:
# Get Ollama URL from settings
raw_base_url = _get_setting_from_session(
"llm.ollama.url", username, DEFAULT_OLLAMA_URL
)
base_url = (
normalize_url(raw_base_url) if raw_base_url else DEFAULT_OLLAMA_URL
)
response = safe_get(
f"{base_url}/api/version",
timeout=2,
allow_localhost=True,
allow_private_ips=True,
)
if response.status_code == 200:
return {
"running": True,
"version": response.json().get("version", "unknown"),
}
return {
"running": False,
"error": f"Ollama returned status code {response.status_code}",
}
except requests.exceptions.RequestException:
logger.exception("Ollama check failed")
return {
"running": False,
"error": "Failed to check search engine status",
}
@router.get("/api/rate-limiting/status")
def api_get_rate_limiting_status(
request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Get current rate limiting status and statistics"""
try:
# exploration_rate / learning_rate are the *configured* settings, not
# the effective operating values: AdaptiveRateLimitTracker._apply_profile
# scales them by the active profile (conservative ~0.5x/0.7x, aggressive
# ~1.5x/1.3x, each capped). The profile is reported alongside so a
# consumer can tell which transform the running tracker applies; we
# deliberately don't duplicate that scaling math here.
status = {
# Default True to match the schema default (default_settings.json)
# and the tracker's web-mode default; the prior endpoint reported
# the tracker's effective enabled state, which was on by default.
"enabled": _get_setting_from_session(
"rate_limiting.enabled", username, True
),
"profile": _get_setting_from_session(
"rate_limiting.profile", username, "balanced"
),
"exploration_rate": _get_setting_from_session(
"rate_limiting.exploration_rate", username, 0.1
),
"learning_rate": _get_setting_from_session(
"rate_limiting.learning_rate", username, 0.45
),
"memory_window": _get_setting_from_session(
"rate_limiting.memory_window", username, 100
),
}
with get_user_db_session(username) as db_session:
estimates = (
db_session.query(RateLimitEstimate)
.order_by(RateLimitEstimate.engine_type)
.all()
)
engines = []
for est in estimates:
engines.append(
{
"engine_type": est.engine_type,
"base_wait_seconds": round(est.base_wait_seconds, 2),
"min_wait_seconds": round(est.min_wait_seconds, 2),
"max_wait_seconds": round(est.max_wait_seconds, 2),
"last_updated": est.last_updated,
"total_attempts": est.total_attempts,
"success_rate": round(est.success_rate * 100, 1),
}
)
return {"status": status, "engines": engines}
except Exception:
logger.exception("Error getting rate limiting status")
return JSONResponse(
{"error": "An internal error occurred"}, status_code=500
)
@router.post("/api/rate-limiting/engines/{engine_type}/reset")
def api_reset_engine_rate_limiting(
request: Request,
engine_type,
username: Annotated[str, Depends(require_auth)],
):
"""Reset (forget) the learned rate-limit estimate for a specific engine.
Deletes the engine's persisted ``RateLimitEstimate`` row from the user's
database so the adaptive tracker re-learns it from scratch. The previous
implementation called the per-request ``get_tracker()``, whose mutation
path is gated on a research-session context that is absent in an analytics
HTTP request — so it was a silent no-op that never cleared the persisted
estimate the ``/status`` and ``/current`` endpoints display (#4721).
"""
try:
# (#6945) Same retry wrap the tracker's reset_engine got: a
# transient SQLite writer-lock blip must not fail the request
# on the first "database is locked". The closure opens a fresh
# ``get_user_db_session`` per attempt so the writer lock is
# released between tries; after retry exhaustion the existing
# error handling below still applies.
def _reset_db():
with get_user_db_session(username) as db_session:
db_session.query(RateLimitEstimate).filter_by(
engine_type=engine_type
).delete(synchronize_session=False)
db_session.commit()
retry_on_db_lock(_reset_db)
return {"message": f"Rate limiting data reset for {engine_type}"}
except Exception:
logger.exception(
"Error resetting rate limiting for {}",
_log_value_preview(engine_type),
)
return JSONResponse(
{"error": "An internal error occurred"}, status_code=500
)
def _cleanup_rate_limit_estimates_sync(username: str, cutoff: float) -> None:
"""Delete persisted rate-limit estimates last updated before *cutoff*."""
# (#6945) Same retry wrap the tracker's cleanup_old_data got — see
# api_reset_engine_rate_limiting above for the rationale. Fresh
# session per attempt; lock exhaustion propagates to the route's
# existing error handling.
def _cleanup_db():
with get_user_db_session(username) as db_session:
db_session.query(RateLimitEstimate).filter(
RateLimitEstimate.last_updated < cutoff
).delete(synchronize_session=False)
db_session.commit()
retry_on_db_lock(_cleanup_db)
@router.post("/api/rate-limiting/cleanup")
async def api_cleanup_rate_limiting(
request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Clean up old rate limiting data.
Note: not using @require_json_body because the JSON body is optional
here — the endpoint works with or without a payload (defaults to 30 days).
Parse errors use the same response as a non-object body. The body is
optional, so ``read_json_dict`` would reject valid ``null`` and cannot
be used here. The isinstance check below has the same reasoning as
``@require_json_body``:
a *valid but truthy non-dict* JSON body (e.g. ``[]`` or a bare number)
would otherwise reach ``data.get(...)`` and raise ``AttributeError``.
The parse catches exactly what ``read_json_dict`` does: ``ValueError``
(bad syntax, undecodable bytes, an oversized integer literal) and
``RecursionError`` (nesting too deep to parse). Anything else, such as
the request-size limit's exception, must propagate to its own handler.
"""
content_type = request.headers.get("content-type", "")
is_json = "application/json" in content_type
try:
data = await request.json() if is_json else None
except (ValueError, RecursionError):
return json_body_error("simple", "Request body must be a JSON object")
if data is not None and not isinstance(data, dict):
return json_body_error("simple", "Request body must be a JSON object")
days = data.get("days", 30) if data is not None else 30
try:
days = int(days)
except (TypeError, ValueError):
return JSONResponse(
{"error": "'days' must be an integer"}, status_code=400
)
if days < 1 or days > 365:
return JSONResponse(
{"error": "'days' must be between 1 and 365"}, status_code=400
)
try:
# Delete persisted estimates not updated within the window. Mirrors the
# read endpoints (#4721): operate on RateLimitEstimate rather than the
# per-request get_tracker(), whose cleanup path is a no-op outside a
# research-session context. last_updated is a unix timestamp (Float).
cutoff = time.time() - days * 86400
await run_db_sync(_cleanup_rate_limit_estimates_sync, username, cutoff)
return {
"message": f"Cleaned up rate limiting data older than {days} days"
}
except Exception:
logger.exception("Error cleaning up rate limiting data")
return JSONResponse(
{"error": "An internal error occurred"}, status_code=500
)
@router.get("/api/bulk")
def get_bulk_settings(
request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Get multiple settings at once for performance."""
try:
# Get requested settings from query parameters
requested = request.query_params.getlist("keys[]")
if not requested:
# Default to common settings if none specified
requested = [
"llm.provider",
"llm.model",
"search.tool",
"search.iterations",
"search.questions_per_iteration",
"search.search_strategy",
"benchmark.evaluation.provider",
"benchmark.evaluation.model",
"benchmark.evaluation.temperature",
"benchmark.evaluation.endpoint_url",
]
# Fetch all settings at once
from ...security.data_sanitizer import DataSanitizer
result = {}
for key in requested:
try:
value = _get_setting_from_session(key, username)
# Redact secret values (main does this — this endpoint is an
# exfiltration channel for plaintext API keys/tokens via
# ?keys[]=...). 'exists' reflects the RAW value, not the sentinel.
result[key] = {
"value": DataSanitizer.redact_value(key, None, value),
"exists": value is not None,
}
except Exception:
logger.warning(
"Error getting setting {}", _log_value_preview(key)
)
result[key] = {
"value": None,
"exists": False,
"error": "Failed to retrieve setting",
}
return {"success": True, "settings": result}
except Exception:
logger.exception("Error getting bulk settings")
return JSONResponse(
{"success": False, "error": "An internal error occurred"},
status_code=500,
)
@router.get("/api/data-location")
def api_get_data_location(
request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Get information about data storage location and security"""
try:
# Get the data directory path
data_dir = get_data_directory()
# Get the encrypted databases path
encrypted_db_path = get_encrypted_database_path()
# 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 info
platform_info = {
"Windows": "C:\\Users\\Username\\AppData\\Local\\local-deep-research",
"macOS": "~/Library/Application Support/local-deep-research",
"Linux": "~/.local/share/local-deep-research",
}
# Current platform
current_platform = platform.system()
if current_platform == "Darwin":
current_platform = "macOS"
# Get SQLCipher settings from environment
from ...database.sqlcipher_utils import get_sqlcipher_settings
# Debug logging
logger.info(f"db_manager type: {type(db_manager)}")
logger.info(
f"db_manager.has_encryption: {getattr(db_manager, 'has_encryption', 'ATTRIBUTE NOT FOUND')}"
)
cipher_settings = (
get_sqlcipher_settings() if db_manager.has_encryption else {}
)
return {
"data_directory": str(data_dir),
"database_path": str(encrypted_db_path),
"encrypted_database_path": str(encrypted_db_path),
"is_custom": custom_data_dir is not None,
"custom_env_var": "LDR_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)
),
"platform_info": platform_info,
"security_notice": {
"encrypted": db_manager.has_encryption,
"warning": "All data including API keys stored in the database are securely encrypted."
if db_manager.has_encryption
else "All data including API keys stored in the database are currently unencrypted. Please ensure appropriate file system permissions are set.",
"recommendation": "Your data is protected with database encryption."
if db_manager.has_encryption
else "Consider using environment variables for sensitive API keys instead of storing them in the database.",
},
"encryption_settings": cipher_settings,
}
except Exception:
logger.exception("Error getting data location information")
return JSONResponse(
{"error": "Failed to retrieve data location"}, status_code=500
)
def _is_blank_service_url(value) -> bool:
"""True when a notification URL counts as unset.
``DataSanitizer._is_empty_value`` and ``NotificationManager`` both treat
a whitespace-only ``notifications.service_url`` as unconfigured, so the
test endpoint has to agree -- a stored ``" "`` is truthy, and without
this it would be handed to Apprise verbatim.
"""
if isinstance(value, str):
return not value.strip()
return not value
async def _notification_test_body(request: Request) -> dict:
"""Parse the test-url body and stash it for the rate-limit predicate.
Runs as a route dependency, i.e. *before* slowapi's decorator wrapper,
which is the only way ``_caller_supplied_notification_url`` (a
synchronous callback) can see the request body at all.
``await request.json()`` is deliberately called here rather than inside
the handler's broad ``except Exception`` so a malformed body reaches the
app's registered ``json.JSONDecodeError`` -> 400 handler instead of
being swallowed and reported as a 500 (see
``web/dependencies/json_body.py``). A valid but non-dict body (e.g. a
bare number) is normalised to ``{}`` rather than raising, matching
main's ``request.get_json(silent=True)`` shape.
"""
data = await request.json()
if not isinstance(data, dict):
data = {}
request.state.notification_test_payload = data
return data
def _caller_supplied_notification_url(request: Request) -> bool:
"""True when the test-url request names its own destination.
Rate-limit exemption predicate. Testing a URL the caller just typed is
the case the endpoint exists to serve and stays unlimited. Falling back
to the caller's STORED URL does not: that path is a zero-argument send
trigger, so it is the one that gets a bucket.
"""
payload = getattr(request.state, "notification_test_payload", None)
if not isinstance(payload, dict):
return False
submitted = payload.get("service_url")
if _is_blank_service_url(submitted):
return False
return submitted != DataSanitizer.REDACTION_TEXT
# Error strings ``NotificationService.test_service`` can return that name
# no destination: operator instructions and shape refusals whose text is
# fixed, or parameterised only with counts. Kept as prefixes because two of
# them continue with a count or a second sentence.
_HOST_FREE_NOTIFICATION_TEST_ERRORS = (
# The outbound master switch is off; only an operator can change it.
"Outbound notifications are disabled.",
# The input does not partition into unambiguous entries.
"Notification service URL could not be parsed unambiguously",
# More entries than MAX_NOTIFICATION_TARGETS -- a count, not a host.
"Too many notification targets",
# Apprise declined to register the parsed entries.
"Failed to add service URL",
# The validator rejected the URL without a reason of its own.
"Invalid notification service URL.",
# Validation passed; delivery did not.
"Failed to send test notification",
)
def _is_host_free_notification_error(error_text: object) -> bool:
"""True when a ``test_service`` error is safe to echo for a URL the
caller never named.
The stored-URL fallback tests a destination the caller does not have to
name and, once the setting is redacted, cannot read back. An error that
names it -- the validator's ``Blocked private/internal IP address:
<host>`` and ``Blocked cloud-metadata / link-local IP address: <host>``
-- would disclose the stored hostname/IP through the very endpoint that
exists to keep the URL hidden.
Matching an ALLOWLIST rather than denylisting those two prefixes keeps
the failure closed: an error string added to ``test_service`` later is
suppressed (the user loses detail, the log keeps it) instead of leaking
by default. Static operator instructions carry no host and must still
reach the UI -- "set LDR_NOTIFICATIONS_ALLOW_OUTBOUND=true" is useless
in a log the user cannot read, and ``docs/NOTIFICATIONS.md`` promises
it inline.
"""
return isinstance(error_text, str) and error_text.startswith(
_HOST_FREE_NOTIFICATION_TEST_ERRORS
)
# Own bucket, not the shared "settings" one: this caps the stored-URL
# fallback without spending the quota a user needs for saving settings.
# Keyed per authenticated user (the branch convention for settings routes)
# rather than main's per-IP default -- the destination being spammed is the
# caller's own configured webhook.
notification_test_limit = limiter.shared_limit(
SETTINGS_RATE_LIMIT,
scope="notification_test",
key_func=_user_key,
exempt_when=_caller_supplied_notification_url,
)
@router.post("/api/notifications/test-url")
@notification_test_limit
async def api_test_notification_url(
request: Request,
data: Annotated[dict, Depends(_notification_test_body)],
username: Annotated[str, Depends(require_auth)],
):
"""
Test a submitted notification URL or the calling user's stored URL.
When ``service_url`` is missing, blank, or the redaction sentinel, the
authenticated user's stored ``notifications.service_url`` is used
instead. Blank includes whitespace-only, matching
``DataSanitizer._is_empty_value`` and the notification manager, which
both treat ``" "`` as unconfigured -- otherwise Apprise is handed
literal whitespace. An unconfigured stored URL returns 400. Test
notifications still use a temporary Apprise instance.
Security note: this endpoint was deliberately unlimited, on the grounds
that users need to test URLs while configuring notifications. That
reasoning covers a caller who submits a URL, and that path is still
exempt. It does not cover the stored-URL fallback: with no body, this
becomes a zero-argument trigger that sends to a destination the caller
never has to name, so an authenticated caller could loop on an empty
body to spam their configured service. That path consumes a dedicated
rate-limit bucket. ``require_auth`` still bounds the blast radius to the
caller's own notification services.
A wrong-typed or hostile ``service_url`` *value* flows unchanged into
``NotificationService.test_service`` / ``NotificationURLValidator``,
which already reject it cleanly (non-string, unparsable, or
private/loopback targets all return ``{"success": False, "error": ...}``
rather than raising).
"""
service_url = data.get("service_url")
# Captured before the stored-URL fallback replaces ``service_url``:
# the response shaping below branches on who chose the destination.
caller_supplied = _caller_supplied_notification_url(request)
if _is_blank_service_url(service_url) or (
service_url == DataSanitizer.REDACTION_TEXT
):
# Off-loop: ``_get_setting_from_session`` opens a SQLCipher session
# (PBKDF2 key derivation + disk I/O) and constructs a
# SettingsManager, both synchronous. Called inline from this
# ``async def`` it stalls the event loop, and the server runs
# single-worker, so every other in-flight request stalls with it.
service_url = await run_db_sync(
_get_setting_from_session,
"notifications.service_url",
username,
default="",
)
if _is_blank_service_url(service_url):
return JSONResponse(
{"success": False, "error": "No notification URL configured"},
status_code=400,
)
try:
from ...notifications.service import NotificationService
# Create notification service instance and test the URL.
# No password/session needed - URL provided directly, no DB access.
# test_service performs a synchronous Apprise network send (can
# block for the full connect/read timeout against a slow or
# unreachable endpoint) — run it off the event loop.
import asyncio
from ...settings.env_registry import get_env_setting
# Honour the operator's env gating (main does this) — otherwise the
# service defaults to outbound_allowed=False and the URL test can never
# succeed even when the operator set LDR_NOTIFICATIONS_ALLOW_OUTBOUND.
notification_service = NotificationService(
allow_private_ips=bool(
get_env_setting("notifications.allow_private_ips", False)
),
outbound_allowed=bool(
get_env_setting("notifications.allow_outbound", False)
),
)
result = await asyncio.to_thread(
notification_service.test_service, service_url
)
# Only return expected fields to prevent information leakage. On
# the caller-supplied path the validator detail is safe to echo —
# the caller just typed that URL. The stored-URL fallback is
# different: an error that names the destination would reveal the
# stored hostname/IP, content the redacted API otherwise never
# returns. Those go to the server log and come back generic; the
# host-free operator instructions still come back inline, since
# they say what the user has to do next.
if caller_supplied:
return {
"success": result.get("success", False),
"message": result.get("message", ""),
"error": result.get("error", ""),
}
if result.get("success"):
return {
"success": result.get("success", False),
"message": result.get("message", ""),
"error": "",
}
error_text = result.get("error", "") or ""
logger.warning(
"Stored-URL notification test failed for user={!r}: {}",
username,
error_text or result.get("message", ""),
)
return {
"success": False,
"message": "",
"error": (
error_text
if _is_host_free_notification_error(error_text)
else (
"Failed to test notification service. Check server "
"logs for details."
)
),
}
except Exception:
logger.exception("Error testing notification URL")
return JSONResponse(
{
"success": False,
"error": "Failed to test notification service. Check logs for details.",
},
status_code=500,
)
# =============================================================================
# Catch-all {key} routes — MUST be last so they don't shadow specific routes
# =============================================================================
@router.get("/api/{key}")
def api_get_db_setting(
request: Request,
key,
username: Annotated[str, Depends(require_auth)],
):
"""Get a specific setting by key from DB, falling back to defaults.
Secret values (API keys, passwords, OAuth tokens) are redacted with the
'[REDACTED]' sentinel — main does this (DataSanitizer.redact_value) so a
single authenticated GET can't exfiltrate a plaintext credential. Safe to
round-trip: the save path treats the sentinel as a no-op, so re-saving a
redacted value never overwrites the stored credential.
"""
try:
with get_user_db_session(username) as db_session:
settings_manager = get_settings_manager(db_session, username)
db_setting = (
db_session.query(Setting).filter(Setting.key == key).first()
)
if db_setting:
from ...security.data_sanitizer import DataSanitizer
# Overlay any LDR_* env-var override BEFORE redaction, so a
# redacted secret still reflects the effective (env) value
# rather than the stale DB row — same order main used
# (_shape_single_effective_metadata, then redact once).
effective_value, effective_editable = _apply_env_override(
settings_manager,
key,
db_setting.value,
db_setting.editable,
)
value = DataSanitizer.redact_value(
db_setting.key, db_setting.ui_element, effective_value
)
setting_data = {
"key": db_setting.key,
"value": value,
"type": db_setting.type
if isinstance(db_setting.type, str)
else db_setting.type.value,
"name": db_setting.name,
"description": db_setting.description,
"category": db_setting.category,
"ui_element": db_setting.ui_element,
"options": db_setting.options,
"min_value": db_setting.min_value,
"max_value": db_setting.max_value,
"step": db_setting.step,
"visible": db_setting.visible,
"editable": effective_editable,
}
# Operator-gate the "unprotected" egress escape hatch and
# the "filesystem" PDF-storage option out of their
# respective options lists unless explicitly enabled, and
# normalise egress-scope's displayed value (#5148 /
# 87537d9ec / fb49985aa).
return _shape_pdf_storage_mode_setting(
key, _shape_egress_scope_setting(key, setting_data)
)
default_meta = settings_manager.default_settings.get(key)
if default_meta:
from ...security.data_sanitizer import DataSanitizer
# Same env-var overlay as the DB branch above — a default-
# only key (no DB row yet) can still be pinned via LDR_*.
effective_value, effective_editable = _apply_env_override(
settings_manager,
key,
default_meta.get("value"),
default_meta.get("editable", True),
)
default_value = DataSanitizer.redact_value(
key,
default_meta.get("ui_element", "text"),
effective_value,
)
setting_data = {
"key": key,
"value": default_value,
"type": default_meta.get("type", "APP"),
"name": default_meta.get("name", key),
"description": default_meta.get("description"),
"category": default_meta.get("category"),
"ui_element": default_meta.get("ui_element", "text"),
"options": default_meta.get("options"),
"min_value": default_meta.get("min_value"),
"max_value": default_meta.get("max_value"),
"step": default_meta.get("step"),
"visible": default_meta.get("visible", True),
"editable": effective_editable,
}
return _shape_pdf_storage_mode_setting(
key, _shape_egress_scope_setting(key, setting_data)
)
return JSONResponse(
{"error": f"Setting not found: {key}"}, status_code=404
)
except SettingsValueError as error:
return _settings_value_error_response("setting", error)
except Exception:
logger.exception("Error getting setting {}", _log_value_preview(key))
return JSONResponse(
{"error": "Failed to retrieve settings"}, status_code=500
)
@router.put("/api/{key}")
@settings_limit
async def api_update_setting(
request: Request,
key,
username: Annotated[str, Depends(require_auth)],
):
"""Update a setting"""
data, body_error = await read_json_dict(
request, "simple", "No data provided"
)
if body_error is not None:
return body_error
return await run_db_sync(_api_update_setting_sync, data, key, username)
def _api_update_setting_sync(data, key, username):
try:
# Key PRESENCE, not truthiness. An *absent* "value" is still a 400,
# but an explicit JSON null must stay distinguishable from it:
# embeddings.openai.chunk_size is the one registered setting whose
# default IS null ("use the provider default"), and the read side
# already supports it (#5963).
if "value" not in data:
return JSONResponse({"error": "No value provided"}, status_code=400)
value = data["value"]
is_openai_chunk_size = key == "embeddings.openai.chunk_size"
with get_user_db_session(username) as db_session:
# Environment-locked settings (LDR_* env var override) are
# rejected up front, before any DB lookup. Ported from Flask's
# api_update_setting early guard (web/routes/settings_routes.py).
# Without this, the write is still correctly blocked further
# down by set_setting()/create_or_update_setting()'s own
# _is_environment_locked() check — but that failure was
# indistinguishable from any other and fell through to a
# generic 500 "Failed to update setting {key}" instead of the
# 403 naming the lock. Lost diagnostic + wrong status code, not
# a data-exposure bug (main's contract restored here).
settings_manager = get_settings_manager(db_session, username)
if is_operator_only_setting(key):
return JSONResponse(
{"error": f"Setting {key} is operator-only"},
status_code=403,
)
if settings_manager.settings_locked:
return JSONResponse(
{"error": "Settings are locked"}, status_code=403
)
if settings_manager._is_environment_locked(
key, "api_update_setting"
):
return JSONResponse(
{"error": f"Setting {key} is environment-locked"},
status_code=403,
)
# embeddings.openai.chunk_size is a whole-number batch size. The
# generic numeric validation below only checks type + min/max, so
# a boolean (coerced to 1/0) or a non-integer float (5.7) would
# silently persist and then fail inside the embedding provider at
# request time. Validate ONCE, up front, against the REGISTERED
# metadata — before the db_setting lookup, so the create path
# (row missing after a DELETE) is guarded too, and so a drifted
# row ui_element cannot change how the value is coerced (#5979).
# A null is allowed through unvalidated: it is this setting's
# registered default (#5963).
if is_openai_chunk_size:
registered_metadata = settings_manager.default_settings[key]
if value is not None:
raw_value = value
value = coerce_setting_for_write(
key=key,
value=value,
ui_element=str(registered_metadata["ui_element"]),
)
if (
isinstance(raw_value, bool)
or not isinstance(value, (int, float))
or (isinstance(value, float) and not value.is_integer())
or value < registered_metadata["min_value"]
):
logger.warning(
f"Validation failed for setting {key}: "
"value must be a whole number at or above "
f"{registered_metadata['min_value']}"
)
return JSONResponse(
{"error": f"Invalid value for setting {key}"},
status_code=400,
)
value = int(value)
elif value is None:
# Every other key keeps the pre-#5174 contract: an explicit
# null is rejected exactly like an absent one.
return JSONResponse(
{"error": "No value provided"}, status_code=400
)
db_setting = (
db_session.query(Setting).filter(Setting.key == key).first()
)
if db_setting:
if not db_setting.editable:
return JSONResponse(
{"error": f"Setting {key} is not editable"},
status_code=403,
)
# See ``_coerced_for_guard``: the sentinel guards must see a
# JSON-string-encoded container coerced to its real
# dict/list shape, or a masked container submitted in that
# form (a supported shape for PUT .../<key> with
# ``{"value": "<json string>"}``) sails past the container
# arm entirely.
_guard_value = _coerced_for_guard(
db_setting.key, db_setting.ui_element, value
)
# The redaction sentinel is a no-op for any sensitive
# setting, and an empty string is a no-op only for password
# inputs (which render blank, so an untouched field must not
# wipe the secret). Companion to the same guard in
# save_all_settings/save_settings. The idempotent 200 keeps
# client-side save indicators from erroring (#5960).
if _is_secret_empty_noop(
key, db_setting.ui_element, _guard_value, db_setting.value
):
logger.debug(
f"Skipping sensitive value write for {key} via "
"api_update_setting (no-op)"
)
return {
"message": (
f"Setting {key} unchanged "
"(sensitive value not overwritten)"
)
}
# An embedded sentinel is a corrupted edit rather than an
# untouched round-trip, so it is a hard error here (400)
# while the exact-match case above stays an idempotent 200
# no-op (#5947).
if _embeds_redaction_sentinel(
key, db_setting.ui_element, _guard_value, db_setting.value
):
logger.warning(
"Rejected redaction-sentinel value for {!r} via "
"api_update_setting (user={!r})",
key,
username,
)
return JSONResponse(
{
"error": _container_rejection_error(
db_setting.ui_element, _guard_value
)
},
status_code=400,
)
if value is not None and not is_openai_chunk_size:
# Persist the MERGED value when a masked container's
# sentinel leaves resolved against the stored row (see
# ``_reconciled_container_value_for_write``); an
# ordinary write is returned unchanged.
value, _is_reconciled_container = (
_reconciled_container_value_for_write(
value, _guard_value, db_setting.value
)
)
# Coerce to the correct Python type before saving (e.g.
# string "5" -> int 5 for a number setting). chunk_size
# was already coerced and bounds-checked above against
# the registry, which is authoritative for a setting's
# type; the row is only data. A reconciled secret-
# bearing container is persisted exactly as merged
# instead -- coercing it through a str-typed ui_element
# 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=effective_ui_element,
)
# A reconciled secret-bearing container skips
# ``validate_setting`` the same way it skips coercion
# above. The load-bearing reason is TYPE REJECTION, not
# logging: ``validate_setting`` runs the value through
# ``get_typed_setting_value`` for the row's DECLARED
# ui_element, so a dict/list on a "number"/"range" row
# comes back "Value must be a number" and the merged
# edit -- with the secret just restored into it -- is
# lost. Its other former reason (that same path logged
# the raw, secret-bearing value at WARNING) is closed
# at the converter itself as of #6201 round 6, so it no
# longer justifies anything on its own;
# ``_coerced_for_guard``'s comment already says this.
# ACCEPTED LOSS: skipping validation also skips the
# options-membership / min-max / checkbox-type checks,
# so e.g. a "select" row that already holds a container
# accepts a merged container with no options check.
# Bounded to rows already holding a container under a
# scalar ui_element -- a user-constructed shape -- and
# the merge itself already resolved every leaf against
# the stored row (#6201).
is_valid, error_message = (
(True, None)
if _is_reconciled_container
else validate_setting(db_setting, value)
)
if not is_valid:
logger.warning(
f"Validation failed for setting {key}: "
f"{error_message}"
)
return JSONResponse(
{"error": f"Invalid value for setting {key}"},
status_code=400,
)
# set_setting() re-infers the type of a text row from
# the value, so a non-finite JSON number would be
# stored as an invalid number row. Check the row it
# will store.
rejection = (
None
if _is_reconciled_container
else _strict_read_rejection(
key,
value,
_infer_ui_element(value, db_setting.ui_element),
)
)
if rejection is not None:
logger.warning(
"Validation failed for setting {}: {}",
_log_value_preview(key),
rejection,
)
return JSONResponse(
{
"error": (
f"Invalid value for setting {key}: "
f"{rejection}"
)
},
status_code=400,
)
# Cross-field egress-policy validation. The full-form saves run
# these guards unconditionally for every key; this single-key
# PUT previously restricted the call to a 4-key allowlist
# (policy.egress_scope / search.tool /
# llm.allowed_local_hostnames / policy.trusted_search_engines),
# which let an SSRF-shaped value through on any key the
# allowlist omitted — notably
# search.engine.web.searxng.default_params.instance_url. Run
# it for every key, matching main
# (web/routes/settings_routes.py, 87537d9ec).
_all_db_settings = {
s.key: s for s in db_session.query(Setting).all()
}
_err = first_egress_validation_error(
{key: value}, _all_db_settings
)
if _err is not None:
logger.bind(policy_audit=True).warning(
"egress-policy setting rejected at api_update_setting",
key=key,
reason=_err.get("error"),
)
return JSONResponse(
{"error": _err["error"]}, status_code=400
)
success = set_setting(key, value, db_session=db_session)
if success:
invalidate_settings_caches(username)
# A document_scheduler.* toggle (e.g.
# sweep_library_collections or generate_rag) must take
# effect without a re-login.
reschedule_document_jobs_if_needed(username, [key])
reschedule_zotero_jobs_if_needed(username, [key])
response_data: dict[str, Any] = {
"message": f"Setting {key} updated successfully"
}
if key in WARNING_AFFECTING_KEYS:
warnings = calculate_warnings(username=username)
response_data["warnings"] = warnings
# Never the value: it may carry a secret (see #6201).
logger.debug(
f"Setting {key} changed, calculated {len(warnings)} warnings"
)
return response_data
return JSONResponse(
{"error": f"Failed to update setting {key}"},
status_code=500,
)
# Registered settings may be absent after DELETE. Recreate them
# from trusted default metadata (type/options/min_value/
# max_value/step/ui_element/editable) instead of the
# caller-supplied request body, so callers cannot replace those
# by racing a delete+recreate. Building setting_dict from
# data[...] alone (the prior behaviour here) let a DELETE+PUT
# round trip silently drop min/max bounds and degrade a
# "number" setting to "text", after which even the
# properly-validating bulk path accepted out-of-range values.
# Genuinely custom keys (no registered default) keep the
# namespace-prefix contract below. Ported from main
# (web/routes/settings_routes.py, 87537d9ec).
default_meta = settings_manager.default_settings.get(key)
if default_meta is not None:
if not default_meta.get("editable", True):
return JSONResponse(
{"error": f"Setting {key} is not editable"},
status_code=403,
)
default_ui = str(default_meta.get("ui_element", "text"))
if value is not None:
value = coerce_setting_for_write(
key=key, value=value, ui_element=default_ui
)
_validation_setting = SimpleNamespace(
key=key,
ui_element=default_ui,
options=default_meta.get("options"),
min_value=default_meta.get("min_value"),
max_value=default_meta.get("max_value"),
)
is_valid, error_message = validate_setting(
_validation_setting, value
)
if not is_valid:
logger.warning(
"Validation failed for recreated setting {}: {}",
key,
error_message,
)
return JSONResponse(
{"error": f"Invalid value for setting {key}"},
status_code=400,
)
setting_dict = dict(default_meta)
setting_dict.update({"key": key, "value": value})
default_type = setting_dict.get("type")
if (
isinstance(default_type, str)
and default_type in SettingType.__members__
):
setting_dict["type"] = SettingType[default_type]
else:
# Namespace validation: reject new keys outside allowed
# prefixes.
if not _is_allowed_new_setting_key(key):
logger.warning(
"Security: Rejected setting outside allowed "
"namespaces: {} (user={!r})",
_log_value_preview(key),
username,
)
return JSONResponse(
{"error": _new_key_rejection_reason(key)},
status_code=400,
)
setting_dict = {
"key": key,
"value": value,
"name": key.split(".")[-1].replace("_", " ").title(),
"description": f"Setting for {key}",
}
# Add additional metadata if provided.
# 'visible' and 'editable' are system-controlled — not
# accepted from callers.
for field in [
"type",
"name",
"description",
"category",
"ui_element",
"options",
"min_value",
"max_value",
"step",
]:
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)
# The caller may choose the type. An unsupported type, or a
# value that type cannot convert, would make every
# effective settings read of this account fail, and only a
# DELETE could undo it.
rejection = _strict_read_rejection(
key, value, setting_dict["ui_element"]
)
if rejection is not None:
logger.warning(
"Rejected new setting {}: {}",
_log_value_preview(key),
rejection,
)
return JSONResponse(
{
"error": (
f"Invalid value for setting {key}: {rejection}"
)
},
status_code=400,
)
# 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
# client value that would be stored verbatim as the credential
# (#5947).
_create_ui = setting_dict.get("ui_element")
# This is the one create branch that never coerces before its
# guard: the REGISTERED-default branch above already coerces
# `value` in place before reaching here, but a genuinely new
# (unregistered) key has no coercion step of its own. Without
# this, a masked container submitted as its JSON-string
# encoding -- caught for a registered key -- would sail past
# the container arm here the same way it did on the update
# paths (see ``_coerced_for_guard``). Only takes effect when
# the caller explicitly provided ``ui_element`` in the request
# body (custom keys have none registered to infer it from).
_create_guard_value = _coerced_for_guard(
key,
_create_ui if isinstance(_create_ui, str) else None,
value,
)
if _embeds_sentinel_on_create(key, _create_ui, _create_guard_value):
logger.warning(
"Rejected redaction-sentinel value for {} via "
"api_update_setting create (user={!r})",
_log_value_preview(key),
username,
)
return JSONResponse(
{
"error": _container_rejection_error(
_create_ui if isinstance(_create_ui, str) else None,
_create_guard_value,
)
},
status_code=400,
)
# Apply egress validation to creation as well as updates.
# Otherwise DELETE followed by PUT recreates a governed key with
# no guards: `llm.allowed_local_hostnames` is `editable`, so the
# delete endpoint accepts it, and `llm.` is an allowed prefix, so
# re-creation passes the namespace check. A public host smuggled
# into that key is then read into EgressContext.local_hostnames
# and classified LOCAL, laundering it past private_only and
# require_local_llm.
#
# Ported from main (web/routes/settings_routes.py), which runs
# this at FOUR sites; this port had three. The update branch ~40
# lines above already carries the guard and its comment claims
# the hole is closed — it was closed for update only.
_all_db_settings = {
s.key: s for s in db_session.query(Setting).all()
}
_err = first_egress_validation_error({key: value}, _all_db_settings)
if _err is not None:
logger.bind(policy_audit=True).warning(
"egress-policy setting rejected at api_update_setting create",
key=key,
reason=_err.get("error"),
)
return JSONResponse({"error": _err["error"]}, status_code=400)
db_setting = create_or_update_setting(
setting_dict, db_session=db_session
)
if db_setting:
invalidate_settings_caches(username)
reschedule_document_jobs_if_needed(username, [key])
reschedule_zotero_jobs_if_needed(username, [key])
from ...security.data_sanitizer import DataSanitizer
return JSONResponse(
{
"message": f"Setting {key} created successfully",
"setting": {
"key": db_setting.key,
# Don't echo a freshly-created password back in
# plaintext — redact like every other settings
# response that ships to the browser.
#
# Route this through ``redact_value`` rather
# than ``is_sensitive_setting`` (#6201, R4).
# ``is_sensitive_setting`` is a NAME predicate
# with no type guard; ``redact_value`` adds the
# guard every read path already applies, so a
# checkbox/number row whose name merely matches
# the broadened snake_case arm (e.g.
# ``llm.x_supports_api_key``) keeps its typed
# value instead of echoing the string
# "[REDACTED]" that no GET of the same row
# would ever return. It also masks nested
# string leaves inside a created container,
# which the bare sentinel substitution could
# not express at all.
"value": DataSanitizer.redact_value(
key, db_setting.ui_element, db_setting.value
),
"type": db_setting.type.value,
"name": db_setting.name,
},
},
status_code=201,
)
return JSONResponse(
{"error": f"Failed to create setting {key}"},
status_code=500,
)
except Exception:
logger.exception("Error updating setting {}", _log_value_preview(key))
return JSONResponse(
{"error": "Failed to update setting"}, status_code=500
)
@router.delete("/api/{key}")
@settings_limit
def api_delete_setting(
request: Request,
key,
username: Annotated[str, Depends(require_auth)],
):
"""Delete a setting"""
try:
with get_user_db_session(username) as db_session:
settings_manager = get_settings_manager(db_session, username)
if is_operator_only_setting(key):
return JSONResponse(
{"error": f"Setting {key} is operator-only"},
status_code=403,
)
# Settings lock (app.lock_settings) -- ported from main's
# api_delete_setting (#5659, "enforce the settings lock on delete,
# import and reset"). SettingsManager already refuses when
# locked, so the write cannot happen either way; this repeats
# the check at the route so a locked instance answers 403
# rather than 200 with nothing written, which is what main's
# own comment gives as the reason. Without it the merge that
# brought #5659 in would have silently dropped the fix, since
# it landed in a Flask file this migration deletes.
if settings_manager.settings_locked:
return JSONResponse(
{"error": "Settings are locked"},
status_code=403,
)
# Environment-locked settings (LDR_* env var override) are
# rejected up front — see the matching guard in
# _api_update_setting_sync above for the full rationale. Checked
# before the existence lookup so an env-locked key still reports
# 403 (not 404) even if a client races a delete against a key
# that hasn't been materialized into a DB row yet, matching
# main's contract (web/routes/settings_routes.py).
if settings_manager._is_environment_locked(
key, "api_delete_setting"
):
return JSONResponse(
{"error": f"Setting {key} is environment-locked"},
status_code=403,
)
db_setting = (
db_session.query(Setting).filter(Setting.key == key).first()
)
if not db_setting:
return JSONResponse(
{"error": f"Setting not found: {key}"}, status_code=404
)
if not db_setting.editable:
return JSONResponse(
{"error": f"Setting {key} is not editable"},
status_code=403,
)
success = settings_manager.delete_setting(key)
if success:
invalidate_settings_caches(username)
reschedule_document_jobs_if_needed(username, [key])
reschedule_zotero_jobs_if_needed(username, [key])
return {"message": f"Setting {key} deleted successfully"}
return JSONResponse(
{"error": f"Failed to delete setting {key}"}, status_code=500
)
except Exception:
logger.exception("Error deleting setting {}", _log_value_preview(key))
return JSONResponse(
{"error": "Failed to delete setting"}, status_code=500
)