Skip to content

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

fix(security): bind the benchmark grader's endpoint key to its origin (#7782)

LearningCircuitc1e570b8dc7c
diff --git a/changelog.d/7782.bugfix.md b/changelog.d/7782.bugfix.md
new file mode 100644
index 0000000000..e89a628410
--- /dev/null
+++ b/changelog.d/7782.bugfix.md
@@ -0,0 +1 @@
+Benchmark evaluation supports a separate endpoint API key and reports configuration errors before research starts. The Benchmark page saves and clears that key in order while preserving newer edits. Python API endpoint overrides use the key supplied with the call, with consistent provider and settings resolution.
diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md
index 143f470b3e..62d0893b8d 100644
--- a/docs/CONFIGURATION.md
+++ b/docs/CONFIGURATION.md
@@ -89,6 +89,7 @@ They are not available in the Web UI because they are needed to start the applic
| `backup.enabled` | `LDR_BACKUP_ENABLED` | `true` | Automatically backup database after successful login. Each backup uses disk space proportional to your database size. Disable this if disk space is limited. | APP |
| `backup.max_age_days` | `LDR_BACKUP_MAX_AGE_DAYS` | `7` | Delete backups older than this many days | APP |
| `backup.max_count` | `LDR_BACKUP_MAX_COUNT` | `1` | Maximum number of backup files to keep per user | APP |
+| `benchmark.evaluation.api_key` | `LDR_BENCHMARK_EVALUATION_API_KEY` | `` | API key for the OpenAI-compatible evaluation endpoint. Leave blank to reuse the research endpoint key when its endpoint settings permit it. Local and private evaluation endpoints can run without a key; use a placeholder for other keyless endpoints. | APP |
| `benchmark.evaluation.endpoint_url` | `LDR_BENCHMARK_EVALUATION_ENDPOINT_URL` | `https://openrouter.ai/api/v1` | Endpoint URL for evaluation model (when using OpenAI-compatible APIs) | APP |
| `benchmark.evaluation.model` | `LDR_BENCHMARK_EVALUATION_MODEL` | `anthropic/claude-3.7-sonnet` | LLM model used as a judge to score benchmark answers against reference answers (e.g., 'anthropic/claude-3.7-sonnet' for OpenRouter, 'gpt-4o' for OpenAI). Must be compatible with the selected evaluation provider. | APP |
| `benchmark.evaluation.provider` | `LDR_BENCHMARK_EVALUATION_PROVIDER` | `openai_endpoint` | LLM provider used to grade benchmark answers by comparing research outputs against reference answers. This is separate from the research LLM being tested. Options: openai_endpoint (recommended, supports OpenRouter), openai, anthropic, ollama. | APP |
diff --git a/src/local_deep_research/api/research_functions.py b/src/local_deep_research/api/research_functions.py
index c17ec6465a..12a176fd36 100644
--- a/src/local_deep_research/api/research_functions.py
+++ b/src/local_deep_research/api/research_functions.py
@@ -10,6 +10,7 @@ from loguru import logger
from local_deep_research.settings.logger import log_settings
from ..config.llm_config import get_llm
+from ..config.openai_endpoint_binding import bind_openai_endpoint_override
from ..config.search_config import get_search
from ..config.thread_settings import get_setting_from_snapshot
from ..report_generator import IntegratedReportGenerator
@@ -17,6 +18,7 @@ from ..search_system import AdvancedSearchSystem
from ..utilities.db_utils import no_db_settings
from ..utilities.thread_context import clear_search_context, set_search_context
from ..utilities.type_utils import overlay_runtime_settings
+from ..llm.providers.base import normalize_provider
from .settings_utils import create_settings_snapshot
from ..utilities.llm_utils import invoke_llm_sync
from ..security.log_sanitizer import redact_and_bound_for_log
@@ -51,6 +53,7 @@ def _init_search_system(
programmatic_mode: bool = True,
search_original_query: bool = True,
settings_snapshot: dict[str, Any] | None = None,
+ api_key: str | None = None,
**kwargs: Any,
) -> AdvancedSearchSystem:
"""
@@ -74,6 +77,12 @@ def _init_search_system(
llms: Optional dictionary of {name: llm} pairs to use as language models
programmatic_mode: If True, disables database operations and metrics tracking
search_original_query: Whether to include the original query in the first iteration of search
+ api_key: API key supplied in the same call. With the
+ ``openai_endpoint`` provider and ``openai_endpoint_url`` it is the
+ key for that URL and wins over any key in ``settings_snapshot``.
+ A key that only comes from ``settings_snapshot`` or stored
+ settings is not sent to an ``openai_endpoint_url`` on a
+ different origin (scheme, host, port).
Returns:
AdvancedSearchSystem: An instance of the configured AdvancedSearchSystem.
@@ -100,6 +109,30 @@ def _init_search_system(
if settings_snapshot is None:
settings_snapshot = kwargs.get("settings_snapshot")
+ # A key passed in the same call as openai_endpoint_url belongs to that
+ # URL; bind it explicitly instead of letting the overlay withhold it as
+ # if it were the stored key of another endpoint. A provider no argument,
+ # snapshot entry or thread context names yet is left unresolved here on
+ # purpose: this is a defensive arm. get_llm resolves the provider from
+ # the same snapshot/thread-context lookup consulted here; its only
+ # divergent default is ``ollama`` (config/llm_config.py), which drops
+ # the key, so in the fully-unresolved shape neither key nor URL is
+ # used. The divergence this arm guards against is limited to the
+ # settings_snapshot=None + thread-context shape.
+ endpoint_key = None
+ if (
+ openai_endpoint_url is not None
+ and isinstance(api_key, str)
+ and api_key.strip()
+ ):
+ effective_provider = provider
+ if effective_provider is None:
+ effective_provider = get_setting_from_snapshot(
+ "llm.provider", None, settings_snapshot=settings_snapshot
+ )
+ if normalize_provider(effective_provider) in (None, "openai_endpoint"):
+ endpoint_key = api_key.strip()
+
if settings_snapshot is not None:
settings_snapshot = dict(settings_snapshot)
overlay_runtime_settings(
@@ -107,11 +140,20 @@ def _init_search_system(
search_tool=search_tool,
model_provider=provider,
model=model_name,
- custom_endpoint=openai_endpoint_url,
+ custom_endpoint=(
+ openai_endpoint_url if endpoint_key is None else None
+ ),
iterations=iterations,
questions_per_iteration=questions_per_iteration,
search_strategy=search_strategy,
)
+ if endpoint_key is not None:
+ bind_openai_endpoint_override(
+ settings_snapshot,
+ openai_endpoint_url,
+ explicit_key=endpoint_key,
+ keep_envelope=False,
+ )
if search_strategy is None and settings_snapshot:
search_strategy = get_setting_from_snapshot(
@@ -124,6 +166,7 @@ def _init_search_system(
llm = get_llm(
temperature=temperature,
openai_endpoint_url=openai_endpoint_url,
+ openai_endpoint_api_key=endpoint_key,
model_name=model_name,
provider=provider,
research_id=research_id,
@@ -340,6 +383,7 @@ def quick_summary(
init_kwargs["research_id"] = research_id
init_kwargs["research_context"] = search_context
init_kwargs["search_original_query"] = search_original_query
+ init_kwargs["api_key"] = api_key
system = _init_search_system(llms=llms, **init_kwargs)
# Perform the search and analysis
@@ -504,7 +548,11 @@ def generate_report(
system = None
try:
system = _init_search_system(
- retrievers=retrievers, llms=llms, username=username, **kwargs
+ retrievers=retrievers,
+ llms=llms,
+ username=username,
+ api_key=api_key,
+ **kwargs,
)
# Set progress callback if provided
if progress_callback:
diff --git a/src/local_deep_research/api/settings_utils.py b/src/local_deep_research/api/settings_utils.py
index d13120633d..cfbc07add8 100644
--- a/src/local_deep_research/api/settings_utils.py
+++ b/src/local_deep_research/api/settings_utils.py
@@ -10,6 +10,7 @@ import copy
from typing import Any
from loguru import logger
+from ..llm.providers.base import normalize_provider
from ..settings import SettingsManager
from ..settings.base import ISettingsManager
from ..settings.env_registry import registry as env_registry
@@ -415,6 +416,18 @@ def create_settings_snapshot(
Args:
overrides: Dict of setting overrides (e.g., {"llm.provider": "openai"})
This is the most common use case - pass a dict of settings to override.
+ Internal snapshot keys (names starting with ``_``, such
+ as the ``openai_endpoint`` key-owner marker) cannot be
+ set here and raise ``ValueError``: they are run metadata
+ written by the code that owns them (the marker only ever
+ comes from the endpoint-key binder).
+ A ``llm.openai_endpoint.url`` override keeps the stored
+ ``llm.openai_endpoint.api_key`` only on the same origin,
+ or on the origin of a set ``LDR_LLM_OPENAI_ENDPOINT_URL``;
+ a key from ``LDR_LLM_OPENAI_ENDPOINT_API_KEY`` is kept
+ only on the env URL's origin, or with no env URL the
+ saved URL's (see config/openai_endpoint_binding.py). A
+ key in the same dict is the key for that URL.
base_settings: Base settings dict (defaults to get_default_settings_snapshot())
Rarely needed - only for advanced use cases.
**kwargs: Common setting shortcuts:
@@ -449,9 +462,36 @@ def create_settings_snapshot(
else:
settings = copy.deepcopy(base_settings)
- # Apply overrides if provided
+ # Apply overrides if provided.
+ #
+ # ``llm.openai_endpoint.url`` is not written verbatim: the stored
+ # ``llm.openai_endpoint.api_key`` belongs to the URL it was configured
+ # for, so the override goes through the endpoint-key binder instead
+ # (below), which records the key's owner and withholds the key when the
+ # override is on another origin (see
+ # config/openai_endpoint_binding.py). A verbatim write left the stored
+ # key paired with whatever URL the override named.
+ url_override_pending = False
+ endpoint_url_override = None
if overrides:
for key, value in overrides.items():
+ if isinstance(key, str) and key.startswith("_"):
+ # Internal snapshot keys are run metadata written by the
+ # code that owns them — never caller-settable through this
+ # channel. In particular the openai_endpoint key-owner
+ # marker (config/openai_endpoint_binding.py) records which
+ # origin the stored API key belongs to; letting an override
+ # write it would let a caller steer the stored key to a URL
+ # of their choosing.
+ raise ValueError(
+ f"{key!r} is an internal snapshot key and cannot be set "
+ "through overrides; names starting with '_' are written "
+ "by the code that owns them only."
+ )
+ if key == "llm.openai_endpoint.url":
+ url_override_pending = True
+ endpoint_url_override = value
+ continue
if key in settings:
if isinstance(settings[key], dict) and "value" in settings[key]:
settings[key]["value"] = value
@@ -505,6 +545,53 @@ def create_settings_snapshot(
# Add any other common shortcuts here...
+ if url_override_pending:
+ from ..config.openai_endpoint_binding import (
+ bind_openai_endpoint_override,
+ effective_openai_endpoint_url,
+ )
+
+ # A key named in the same call belongs to that call's URL — the
+ # same rule as the ``openai_endpoint_url=`` + ``api_key=`` pair in
+ # ``_init_search_system``, which decides this through
+ # ``normalize_provider`` (case/whitespace-insensitive). It replaces
+ # the stored key, so nothing stored travels to the overridden URL.
+ explicit_key = ""
+ if overrides:
+ candidate = overrides.get("llm.openai_endpoint.api_key")
+ if isinstance(candidate, str) and candidate.strip():
+ explicit_key = candidate.strip()
+ call_provider = kwargs.get("provider")
+ if (
+ not explicit_key
+ and isinstance(call_provider, str)
+ and normalize_provider(call_provider) == "openai_endpoint"
+ and isinstance(kwargs.get("api_key"), str)
+ and kwargs["api_key"].strip()
+ ):
+ explicit_key = kwargs["api_key"].strip()
+
+ if "llm.openai_endpoint.url" not in settings:
+ # Match the entry shape the generic override path leaves
+ # behind (an envelope), so an operator ``LDR_*`` override of
+ # this key keeps winning on reads: environment values are
+ # operator policy (see ``effective_openai_endpoint_url``).
+ settings["llm.openai_endpoint.url"] = {
+ "value": effective_openai_endpoint_url(settings),
+ "ui_element": "text",
+ }
+ # A ``None`` override in the generic path keeps the entry and stores
+ # a ``None`` value (reads then fall back to the provider default),
+ # while the binder reads ``None`` as "keep the current URL"; write
+ # ``""`` instead, which reads as "unset" the same way and cannot be
+ # misread as "no change".
+ bind_openai_endpoint_override(
+ settings,
+ "" if endpoint_url_override is None else endpoint_url_override,
+ explicit_key=explicit_key,
+ keep_envelope=True,
+ )
+
return settings
diff --git a/src/local_deep_research/benchmarks/benchmark_functions.py b/src/local_deep_research/benchmarks/benchmark_functions.py
index b2a48f895c..95f5834449 100644
--- a/src/local_deep_research/benchmarks/benchmark_functions.py
+++ b/src/local_deep_research/benchmarks/benchmark_functions.py
@@ -10,7 +10,7 @@ from typing import Any, Dict, List, Optional
from loguru import logger
from ..config.thread_settings import get_setting_from_snapshot
-from ..llm.providers.base import normalize_provider
+from .graders import normalize_grader_provider
from ..benchmarks import (
calculate_metrics,
@@ -36,6 +36,7 @@ def evaluate_simpleqa(
search_provider: Optional[str] = None,
endpoint_url: Optional[str] = None,
search_strategy: str = "source_based",
+ evaluation_api_key: Optional[str] = None,
) -> Dict[str, Any]:
"""
Run SimpleQA benchmark evaluation.
@@ -53,6 +54,10 @@ def evaluate_simpleqa(
search_provider: Optional provider to use for the search system
endpoint_url: Optional endpoint URL for OpenRouter or other API services
search_strategy: Search strategy to use (default: 'source_based')
+ evaluation_api_key: Optional API key for the grader's endpoint. It is
+ only used for grading, with the grader endpoint of this run,
+ and only when the evaluation provider is ``openai_endpoint``;
+ other providers ignore it.
Returns:
Dictionary with benchmark results
@@ -92,13 +97,16 @@ def evaluate_simpleqa(
if evaluation_model:
evaluation_config["model_name"] = evaluation_model
if evaluation_provider:
- evaluation_provider = normalize_provider(evaluation_provider)
+ evaluation_provider = normalize_grader_provider(evaluation_provider)
evaluation_config["provider"] = evaluation_provider
# Add endpoint URL if using openai_endpoint
if evaluation_provider == "openai_endpoint" and endpoint_url:
evaluation_config["openai_endpoint_url"] = endpoint_url
elif evaluation_provider == "openai_endpoint" and env_url:
evaluation_config["openai_endpoint_url"] = env_url
+ if evaluation_api_key:
+ evaluation_config = dict(evaluation_config or {"temperature": 0})
+ evaluation_config["api_key"] = evaluation_api_key
# Run the benchmark
return run_simpleqa_benchmark(
@@ -123,6 +131,7 @@ def evaluate_browsecomp(
search_provider: Optional[str] = None,
endpoint_url: Optional[str] = None,
search_strategy: str = "source_based",
+ evaluation_api_key: Optional[str] = None,
) -> Dict[str, Any]:
"""
Run BrowseComp benchmark evaluation.
@@ -140,6 +149,10 @@ def evaluate_browsecomp(
search_provider: Optional provider to use for the search system
endpoint_url: Optional endpoint URL for OpenRouter or other API services
search_strategy: Search strategy to use (default: 'source_based')
+ evaluation_api_key: Optional API key for the grader's endpoint. It is
+ only used for grading, with the grader endpoint of this run,
+ and only when the evaluation provider is ``openai_endpoint``;
+ other providers ignore it.
Returns:
Dictionary with benchmark results
@@ -179,13 +192,16 @@ def evaluate_browsecomp(
if evaluation_model:
evaluation_config["model_name"] = evaluation_model
if evaluation_provider:
- evaluation_provider = normalize_provider(evaluation_provider)
+ evaluation_provider = normalize_grader_provider(evaluation_provider)
evaluation_config["provider"] = evaluation_provider
# Add endpoint URL if using openai_endpoint
if evaluation_provider == "openai_endpoint" and endpoint_url:
evaluation_config["openai_endpoint_url"] = endpoint_url
elif evaluation_provider == "openai_endpoint" and env_url:
evaluation_config["openai_endpoint_url"] = env_url
+ if evaluation_api_key:
+ evaluation_config = dict(evaluation_config or {"temperature": 0})
+ evaluation_config["api_key"] = evaluation_api_key
# Run the benchmark
return run_browsecomp_benchmark(
@@ -210,6 +226,7 @@ def evaluate_xbench_deepsearch(
search_provider: Optional[str] = None,
endpoint_url: Optional[str] = None,
search_strategy: str = "source_based",
+ evaluation_api_key: Optional[str] = None,
) -> Dict[str, Any]:
"""
Run xbench-DeepSearch benchmark evaluation.
@@ -227,6 +244,10 @@ def evaluate_xbench_deepsearch(
search_provider: Optional provider to use for the search system
endpoint_url: Optional endpoint URL for API services
search_strategy: Search strategy to use
+ evaluation_api_key: Optional API key for the grader's endpoint. It is
+ only used for grading, with the grader endpoint of this run,
+ and only when the evaluation provider is ``openai_endpoint``;
+ other providers ignore it.
Returns:
Dictionary with benchmark results
@@ -268,13 +289,16 @@ def evaluate_xbench_deepsearch(
if evaluation_model:
evaluation_config["model_name"] = evaluation_model
if evaluation_provider:
- evaluation_provider = normalize_provider(evaluation_provider)
+ evaluation_provider = normalize_grader_provider(evaluation_provider)
evaluation_config["provider"] = evaluation_provider
# Add endpoint URL if using openai_endpoint
if evaluation_provider == "openai_endpoint" and endpoint_url:
evaluation_config["openai_endpoint_url"] = endpoint_url
elif evaluation_provider == "openai_endpoint" and env_url:
evaluation_config["openai_endpoint_url"] = env_url
+ if evaluation_api_key:
+ evaluation_config = dict(evaluation_config or {"temperature": 0})
+ evaluation_config["api_key"] = evaluation_api_key
# Run the benchmark
return run_xbench_deepsearch_benchmark(
diff --git a/src/local_deep_research/benchmarks/evaluators/simpleqa.py b/src/local_deep_research/benchmarks/evaluators/simpleqa.py
index ccfecdde66..dbec5314db 100644
--- a/src/local_deep_research/benchmarks/evaluators/simpleqa.py
+++ b/src/local_deep_research/benchmarks/evaluators/simpleqa.py
@@ -120,6 +120,12 @@ class SimpleQAEvaluator(BaseBenchmarkEvaluator):
Returns:
Dictionary with benchmark results
"""
+ # Refuse before any research when the grader would have no API key
+ # for its endpoint (grading runs only after every example).
+ from ..graders import check_grader_endpoint_key
+
+ check_grader_endpoint_key()
+
# Create a dataset instance using the registry
try:
dataset_instance = DatasetRegistry.create_dataset(
diff --git a/src/local_deep_research/benchmarks/graders.py b/src/local_deep_research/benchmarks/graders.py
index 57ddba29bd..5309ba4835 100644
--- a/src/local_deep_research/benchmarks/graders.py
+++ b/src/local_deep_research/benchmarks/graders.py
@@ -13,9 +13,15 @@ from typing import Any, Callable, Dict, List, Optional
from langchain_core.messages.human import HumanMessage
-from ..config.llm_config import get_llm
+from ..config.llm_config import LLMNotConfiguredError, get_llm
+from ..config.openai_endpoint_binding import (
+ resolve_openai_endpoint_override_key,
+)
+from ..config.thread_settings import get_setting_from_snapshot
from ..llm.providers.base import normalize_provider
from ..utilities.json_utils import get_llm_response_text
+from ..security.network_utils import is_private_ip
+from ..utilities.url_utils import endpoint_origin, same_endpoint_origin
from .templates import BROWSECOMP_GRADER_TEMPLATE, SIMPLEQA_GRADER_TEMPLATE
@@ -29,20 +35,129 @@ DEFAULT_EVALUATION_CONFIG = {
}
-def get_evaluation_llm(
- custom_config: Optional[Dict[str, Any]] = None,
- settings_snapshot: Optional[Dict[str, Any]] = None,
-):
+def normalize_grader_provider(provider):
+ """The grader provider ``provider`` names, normalised as ``get_llm`` does.
+
+ A provider that normalises to nothing (``None``, ``""``, whitespace,
+ ``'""'``) returns the grader default, ``openai_endpoint``. The start
+ routes and the grader treat it as an unset
+ ``benchmark.evaluation.provider``. The ``benchmark_functions`` runners
+ call this only for a truthy provider: there a quotes-only or whitespace
+ provider selects ``openai_endpoint`` with the research endpoint URL
+ (the ``endpoint_url`` argument or ``llm.openai_endpoint.url``) when one
+ is set, and only ``None`` or ``""`` leaves the grader on
+ ``benchmark.evaluation.endpoint_url``.
"""
- Get an LLM for evaluation purposes using Claude 3.7 Sonnet via OpenRouter
- by default, which can be overridden with custom settings.
+ return normalize_provider(provider) or DEFAULT_EVALUATION_CONFIG["provider"]
+
+
+GRADER_KEY_ERROR_MESSAGE = (
+ "The benchmark grader endpoint is on a different origin (scheme, host "
+ "or port) than the endpoint its API key was configured for, so no key "
+ "is sent to it. Set benchmark.evaluation.api_key for the endpoint in "
+ "benchmark.evaluation.endpoint_url, or point the grader at the "
+ "research endpoint (llm.openai_endpoint.url). A grader on a local or "
+ "private address (for example http://localhost:11434/v1) runs without "
+ "a key; for another keyless endpoint, set benchmark.evaluation.api_key "
+ "to any placeholder value."
+)
+
+
+def grader_endpoint_url(settings_snapshot: Optional[Dict[str, Any]] = None):
+ """The configured grader endpoint (``benchmark.evaluation.endpoint_url``)."""
+ url = get_setting_from_snapshot(
+ "benchmark.evaluation.endpoint_url",
+ None,
+ settings_snapshot=settings_snapshot,
+ )
+ if isinstance(url, str) and url.strip():
+ return url.strip()
+ return DEFAULT_EVALUATION_CONFIG["openai_endpoint_url"]
- Args:
- custom_config: Optional custom configuration that overrides defaults
- settings_snapshot: Optional settings snapshot for thread-safe access
+
+def resolve_grader_endpoint_api_key(
+ endpoint_url: str,
+ explicit_key: Optional[str] = None,
+ settings_snapshot: Optional[Dict[str, Any]] = None,
+) -> str:
+ """Resolve the API key for an ``openai_endpoint`` grader at ``endpoint_url``.
+
+ Each key is only sent to the endpoint it was configured for:
+
+ 1. ``explicit_key`` (an ``api_key`` in a custom evaluation config): the
+ caller's key for this run's grader, returned as is and bound to the
+ grader's resolved endpoint — ``benchmark.evaluation.endpoint_url``
+ unless the evaluation config names its own ``openai_endpoint_url``
+ (call-supplied or derived from ``llm.openai_endpoint.url``).
+ 2. ``benchmark.evaluation.api_key``, when ``endpoint_url`` has the same
+ origin (scheme, host, port) as ``benchmark.evaluation.endpoint_url``.
+ 3. ``llm.openai_endpoint.api_key``, when ``endpoint_url`` has the same
+ origin as ``llm.openai_endpoint.url`` (or as a set
+ ``LDR_LLM_OPENAI_ENDPOINT_URL``). A key from
+ ``LDR_LLM_OPENAI_ENDPOINT_API_KEY`` follows only the env URL's
+ origin, or with none set the saved URL's — see
+ ``resolve_openai_endpoint_override_key``.
+ 4. Otherwise no key. If a configured key was withheld and the grader
+ endpoint is not on a local/private address, raise instead.
Returns:
- An LLM instance for evaluation
+ The key to bind to ``endpoint_url``, or ``""`` when none applies.
+
+ Raises:
+ LLMNotConfiguredError: a configured key exists but none belongs to
+ ``endpoint_url``; message ``GRADER_KEY_ERROR_MESSAGE``.
+ """
+ if isinstance(explicit_key, str) and explicit_key.strip():
+ return explicit_key.strip()
+
+ grader_key = get_setting_from_snapshot(
+ "benchmark.evaluation.api_key",
+ "",
+ settings_snapshot=settings_snapshot,
+ )
+ grader_key = grader_key.strip() if isinstance(grader_key, str) else ""
+ grader_key_withheld = False
+ if grader_key:
+ if same_endpoint_origin(
+ endpoint_url, grader_endpoint_url(settings_snapshot)
+ ):
+ return grader_key
+ grader_key_withheld = True
+
+ key, research_key_withheld = resolve_openai_endpoint_override_key(
+ endpoint_url, settings_snapshot=settings_snapshot
+ )
+ if key:
+ return key
+ if (grader_key_withheld or research_key_withheld) and not (
+ _is_local_endpoint(endpoint_url)
+ ):
+ raise LLMNotConfiguredError(GRADER_KEY_ERROR_MESSAGE)
+ # Keyless: nothing configured, or a local/private grader (Ollama, vLLM
+ # on the LAN) that typically needs no key. No configured key is sent.
+ return ""
+
+
+def _is_local_endpoint(endpoint_url) -> bool:
+ """True for a grader endpoint on a loopback or private address.
+
+ Decided from the URL text only (no DNS lookup): ``localhost``, private,
+ loopback and link-local IP literals, and ``.local`` names.
+ """
+ origin = endpoint_origin(endpoint_url)
+ if origin is None:
+ return False
+ return is_private_ip(origin[1])
+
+
+def _evaluation_llm_kwargs(
+ custom_config: Optional[Dict[str, Any]] = None,
+ settings_snapshot: Optional[Dict[str, Any]] = None,
+) -> Dict[str, Any]:
+ """Build the ``get_llm`` keyword arguments for the grader.
+
+ Raises:
+ LLMNotConfiguredError: see :func:`resolve_grader_endpoint_api_key`.
"""
# Start with default config (Claude 3.7 Sonnet via OpenRouter)
config = DEFAULT_EVALUATION_CONFIG.copy()
@@ -69,37 +184,77 @@ def get_evaluation_llm(
k: v for k, v in config.items() if k in ldr_supported_params
}
- # Check if we're using openai_endpoint but don't have an API key configured
- if normalize_provider(filtered_config.get("provider")) == "openai_endpoint":
- # Try to get API key from settings snapshot or environment
- api_key = None
-
- if settings_snapshot:
- # Get from settings snapshot for thread safety
- api_key_setting = settings_snapshot.get(
- "llm.openai_endpoint.api_key"
+ # ``api_key`` is accepted in a custom config as the grader's own key;
+ # get_llm takes it as ``openai_endpoint_api_key``.
+ explicit_key = filtered_config.pop("api_key", None)
+
+ # Normalise as get_llm does and hand get_llm that value, so a quoted
+ # '"openai_endpoint"' takes the grader-endpoint path below instead of
+ # reaching get_llm with the hard-coded default URL. A provider that
+ # normalises to nothing is the grader default, as if it were unset.
+ provider = normalize_grader_provider(filtered_config.get("provider"))
+ filtered_config["provider"] = provider
+
+ if provider == "openai_endpoint":
+ # A config without its own URL (e.g. a request-supplied
+ # {"provider": "openai_endpoint"}) grades against the configured
+ # grader endpoint, not the hard-coded default.
+ if not (custom_config or {}).get("openai_endpoint_url"):
+ filtered_config["openai_endpoint_url"] = grader_endpoint_url(
+ settings_snapshot
)
- if api_key_setting:
- api_key = (
- api_key_setting.get("value")
- if isinstance(api_key_setting, dict)
- else api_key_setting
- )
- else:
- # No settings snapshot available
+ if settings_snapshot is None:
logger.warning(
"No settings snapshot provided for benchmark grader. "
"API key must be provided via settings_snapshot for thread safety."
)
-
- if not api_key:
+ grader_key = resolve_grader_endpoint_api_key(
+ filtered_config["openai_endpoint_url"],
+ explicit_key=explicit_key,
+ settings_snapshot=settings_snapshot,
+ )
+ if not grader_key:
logger.warning(
- "Using openai_endpoint provider but no API key found. "
- "Set the llm.openai_endpoint.api_key setting in the database or "
- "LDR_LLM_OPENAI_ENDPOINT_API_KEY environment variable."
+ "Using openai_endpoint provider for the benchmark grader but "
+ "no API key found. Set the benchmark.evaluation.api_key "
+ "setting if the grader endpoint requires one."
)
- # Try to fall back to LDR's config if API key not explicitly provided
- # The get_llm function will handle this case
+ filtered_config["openai_endpoint_api_key"] = grader_key
+
+ return filtered_config
+
+
+def check_grader_endpoint_key(
+ custom_config: Optional[Dict[str, Any]] = None,
+ settings_snapshot: Optional[Dict[str, Any]] = None,
+) -> None:
+ """Fail fast if the grader would have no key for its endpoint.
+
+ Runs the same resolution as :func:`get_evaluation_llm` without building
+ a client, so a benchmark can be refused before any research runs.
+
+ Raises:
+ LLMNotConfiguredError: with ``GRADER_KEY_ERROR_MESSAGE``.
+ """
+ _evaluation_llm_kwargs(custom_config, settings_snapshot)
+
+
+def get_evaluation_llm(
+ custom_config: Optional[Dict[str, Any]] = None,
+ settings_snapshot: Optional[Dict[str, Any]] = None,
+):
+ """
+ Get an LLM for evaluation purposes using Claude 3.7 Sonnet via OpenRouter
+ by default, which can be overridden with custom settings.
+
+ Args:
+ custom_config: Optional custom configuration that overrides defaults
+ settings_snapshot: Optional settings snapshot for thread-safe access
+
+ Returns:
+ An LLM instance for evaluation
+ """
+ filtered_config = _evaluation_llm_kwargs(custom_config, settings_snapshot)
# Get the LLM using LDR's existing function. Thread settings_snapshot
# through — without it, get_llm's snapshot-less PEP only permits local
diff --git a/src/local_deep_research/benchmarks/runners.py b/src/local_deep_research/benchmarks/runners.py
index 73185151e6..f2e25d0a98 100644
--- a/src/local_deep_research/benchmarks/runners.py
+++ b/src/local_deep_research/benchmarks/runners.py
@@ -14,7 +14,11 @@ from typing import Any, Callable, Dict, Optional
from ..api import quick_summary
from .datasets import DEFAULT_DATASET_URLS, load_dataset
from .datasets.base import DatasetRegistry
-from .graders import extract_answer_from_response, grade_results
+from .graders import (
+ check_grader_endpoint_key,
+ extract_answer_from_response,
+ grade_results,
+)
from .metrics import calculate_metrics, generate_report
from .templates import BROWSECOMP_QUERY_TEMPLATE
@@ -149,6 +153,12 @@ def run_benchmark(
Dictionary with benchmark results and metrics. The returned file
paths are inside the resolved output directory.
"""
+ # Refuse up front when the grader would have no API key for its
+ # endpoint, before any research budget is spent. Raises
+ # LLMNotConfiguredError naming benchmark.evaluation.api_key.
+ if run_evaluation and not human_evaluation:
+ check_grader_endpoint_key(evaluation_config, settings_snapshot)
+
output_dir = str(
resolve_output_dir(output_dir, fallback="benchmark_results")
)
diff --git a/src/local_deep_research/config/llm_config.py b/src/local_deep_research/config/llm_config.py
index 0252870922..c886185489 100644
--- a/src/local_deep_research/config/llm_config.py
+++ b/src/local_deep_research/config/llm_config.py
@@ -20,6 +20,10 @@ from ..utilities.search_utilities import remove_think_tags
from ..llm.providers import discover_providers # noqa: F401
from ..llm.providers.auto_discovery import is_builtin_provider_factory
from ..llm.providers.base import normalize_provider
+from .openai_endpoint_binding import (
+ OPENAI_ENDPOINT_KEY_OWNER_MARKER,
+ bind_openai_endpoint_override,
+)
from .thread_settings import get_setting_from_snapshot
@@ -93,6 +97,7 @@ def get_llm(
research_context=None,
settings_snapshot=None,
username=None,
+ openai_endpoint_api_key=None,
):
"""
Get LLM instance based on model name and provider.
@@ -103,12 +108,24 @@ def get_llm(
provider: Provider to use (if None, uses database setting)
openai_endpoint_url: Per-call URL override for the
``openai_endpoint`` provider. When omitted, the provider uses
- the ``llm.openai_endpoint.url`` setting.
+ the ``llm.openai_endpoint.url`` setting. The stored
+ ``llm.openai_endpoint.api_key`` is sent to the override only
+ when both URLs share an origin (scheme, host, port), or when the
+ override is on the origin of a set
+ ``LDR_LLM_OPENAI_ENDPOINT_URL``. A key from
+ ``LDR_LLM_OPENAI_ENDPOINT_API_KEY`` is sent only to the env
+ URL's origin, or with no env URL to the saved URL's. Otherwise
+ the call carries no stored key unless
+ ``openai_endpoint_api_key`` supplies one (see
+ config/openai_endpoint_binding.py).
research_id: Optional research ID for token tracking
research_context: Optional research context for enhanced token tracking
username: Requesting user, used to resolve per-user registered LLMs.
When omitted, falls back to the ``_username`` in the settings
snapshot; ``None`` resolves shared/built-in providers only.
+ openai_endpoint_api_key: Per-call API key for the
+ ``openai_endpoint`` provider, bound to this call's endpoint.
+ Takes precedence over the stored key.
Returns:
A LangChain LLM instance with automatic think-tag removal
@@ -147,18 +164,45 @@ def get_llm(
had_settings_snapshot = settings_snapshot is not None
+ if openai_endpoint_api_key is not None and not isinstance(
+ openai_endpoint_api_key, str
+ ):
+ raise ValueError("openai_endpoint_api_key must be a string")
+ explicit_endpoint_key = (openai_endpoint_api_key or "").strip()
+
# The endpoint override must reach both the egress-policy gate and the
# provider factory. Overlay it onto a per-call copy so those paths share
# one effective value without mutating the caller's settings snapshot.
- if provider == "openai_endpoint" and openai_endpoint_url is not None:
- if (
- not isinstance(openai_endpoint_url, str)
- or not openai_endpoint_url.strip()
- ):
- raise ValueError("openai_endpoint_url must be a non-empty string")
+ #
+ # The API key is bound in the same copy. The provider reads its key
+ # from ``llm.openai_endpoint.api_key``, which belongs to the configured
+ # ``llm.openai_endpoint.url``; an override pointing at another origin
+ # must not inherit it (see config/openai_endpoint_binding.py). A
+ # snapshot whose URL was overridden earlier (runtime overlay) carries an
+ # owner marker and is re-checked here, so a key restored by a later
+ # environment-override pass cannot follow the overridden URL.
+ if provider == "openai_endpoint" and (
+ openai_endpoint_url is not None
+ or explicit_endpoint_key
+ or (
+ isinstance(settings_snapshot, dict)
+ and OPENAI_ENDPOINT_KEY_OWNER_MARKER in settings_snapshot
+ )
+ ):
+ override_url = None
+ if openai_endpoint_url is not None:
+ if (
+ not isinstance(openai_endpoint_url, str)
+ or not openai_endpoint_url.strip()
+ ):
+ raise ValueError(
+ "openai_endpoint_url must be a non-empty string"
+ )
+ override_url = openai_endpoint_url.strip()
+
settings_snapshot = dict(settings_snapshot or {})
- settings_snapshot["llm.openai_endpoint.url"] = (
- openai_endpoint_url.strip()
+ bind_openai_endpoint_override(
+ settings_snapshot, override_url, explicit_endpoint_key
)
# Egress policy PEP for LLM endpoints. Fires here (before the registered-
@@ -186,7 +230,10 @@ def get_llm(
)
if not had_settings_snapshot:
- if provider == "openai_endpoint" and settings_snapshot is not None:
+ if (
+ provider == "openai_endpoint"
+ and openai_endpoint_url is not None
+ ):
# A per-call endpoint is enough to classify this otherwise
# snapshot-less provider. Preserve the fail-closed contract:
# only a local endpoint may proceed without a policy snapshot.
diff --git a/src/local_deep_research/config/openai_endpoint_binding.py b/src/local_deep_research/config/openai_endpoint_binding.py
new file mode 100644
index 0000000000..23c7d88857
--- /dev/null
+++ b/src/local_deep_research/config/openai_endpoint_binding.py
@@ -0,0 +1,508 @@
+"""Bind the ``openai_endpoint`` API key to the endpoint it was configured for.
+
+``llm.openai_endpoint.api_key`` belongs to ``llm.openai_endpoint.url``. Any
+code that points the provider at another URL for one call or one run (the
+``custom_endpoint`` research overlay, ``get_llm(openai_endpoint_url=...)``,
+and the ``create_settings_snapshot`` overrides that the Python API's
+``settings_override=`` builds its snapshot from) goes through
+:func:`bind_openai_endpoint_override`, which carries the stored key over
+only when the new URL has the same origin (scheme, host, port).
+
+The binding is idempotent: the first override records, under
+``OPENAI_ENDPOINT_KEY_OWNER_MARKER``, the origin the key belongs to, and
+every later binding compares against that record. Which origin is recorded
+depends on the snapshot the first binding sees:
+
+* no marker yet, no explicit key: the snapshot's own
+ ``llm.openai_endpoint.url`` entry as stored in it — the envelope's
+ ``"value"`` or the raw string — read before the override is written and
+ without applying ``LDR_*`` environment overrides (a value an earlier
+ environment pass wrote into the snapshot is read as is for the
+ decision); with no entry of its own — including on the documented
+ ``settings_snapshot=None`` Python-API path — the same thread-settings-
+ context fallback the ``llm.openai_endpoint.api_key`` read uses, so the
+ key is always owned by the endpoint it was configured for rather than
+ by the provider default; a missing or empty entry records the provider
+ default. A value equal to a live ``LDR_LLM_OPENAI_ENDPOINT_URL`` is
+ never recorded, whichever source it came from — entry or fallback —
+ and the record then fails closed to "no owner" (see
+ :func:`_configured_openai_endpoint_url`);
+* an explicit key (one named with the URL in the same call): the URL it
+ was named for; when that URL has no origin (``None``, ``""``,
+ whitespace), the URL the provider actually contacts after the write —
+ the current URL when none was named, the provider default for an
+ emptied URL, the env URL while ``LDR_LLM_OPENAI_ENDPOINT_URL`` pins an
+ envelope entry, and no owner (the key is withheld) for a whitespace-only
+ raw URL, which the provider cannot reach either;
+* a marker already present: the marker, kept as is.
+
+The marker is written by this module only. ``create_settings_snapshot``
+refuses caller overrides of internal (``_``-prefixed) snapshot keys, and
+:func:`_key_owner_url` trusts a marker only in the exact form
+:func:`_owner_origin_url` records it in. A snapshot passed in another way
+(``create_settings_snapshot(base_settings=...)``, ``settings_snapshot=``)
+is trusted like any other snapshot: a canonical marker it carries is
+honoured as the owner record.
+
+The same first binding also records, under
+``OPENAI_ENDPOINT_SAVED_URL_MARKER``, the origin of the snapshot's URL
+entry as it stood before any override (the saved URL).
+
+The recorded owner speaks for a key that came from the snapshot only. An
+operator ``LDR_LLM_OPENAI_ENDPOINT_API_KEY`` is never authorised by it: an
+env-supplied key follows exactly one origin, the one a plain ``get_llm()``
+without overrides would send it to — that of
+``LDR_LLM_OPENAI_ENDPOINT_URL`` when it is set, otherwise that of the saved
+URL (see :func:`_key_may_follow`). No default URL is allowed in its own
+right; a default is reached only when it is the saved URL. A key from the
+snapshot additionally may go to the env URL's origin while that variable is
+set (operator policy). These rules are evaluated at decision time and the
+env origin is never recorded as a stored key's owner — not through
+``LDR_LLM_OPENAI_ENDPOINT_URL`` directly and not through a value an
+earlier environment pass wrote into the snapshot or the
+thread-settings-context fallback surfaced, which the binder's recording
+path drops from the record whichever source it came from — so the env
+rules expire with the variables.
+
+Kept free of provider and langchain imports so the settings overlay helpers
+in ``utilities.type_utils`` can use it.
+"""
+
+from loguru import logger
+
+from ..settings.manager import check_env_setting
+from ..utilities.url_utils import endpoint_origin, same_endpoint_origin
+from .thread_settings import get_setting_from_snapshot
+
+OPENAI_ENDPOINT_URL_SETTING = "llm.openai_endpoint.url"
+OPENAI_ENDPOINT_API_KEY_SETTING = "llm.openai_endpoint.api_key"
+# The URL the provider uses when ``llm.openai_endpoint.url`` is unset/empty.
+OPENAI_ENDPOINT_DEFAULT_BASE_URL = "https://api.openai.com/v1"
+# Snapshot entry recording which origin ``llm.openai_endpoint.api_key`` belongs
+# to once the URL has been overridden. Leading underscore like ``_username``:
+# run metadata, not a user setting.
+OPENAI_ENDPOINT_KEY_OWNER_MARKER = "_openai_endpoint_key_owner_url"
+# Snapshot entry recording the origin of the snapshot's own
+# ``llm.openai_endpoint.url`` entry as it was before the first override (the
+# saved URL). An env-supplied key with no env URL follows this origin only.
+OPENAI_ENDPOINT_SAVED_URL_MARKER = "_openai_endpoint_saved_url_origin"
+
+
+def effective_openai_endpoint_url(settings_snapshot=None):
+ """The URL the ``openai_endpoint`` provider would contact for this snapshot.
+
+ Mirrors ``CustomOpenAIEndpointProvider.create_llm``: a missing or empty
+ value falls back to the provider default; any other value (including a
+ whitespace-only one) is used as is and normalised later. An operator-set
+ ``LDR_LLM_OPENAI_ENDPOINT_URL`` environment override becomes the
+ effective value here (environment values are operator policy), so the
+ stored key is kept for the env URL while it is set — see
+ :func:`_key_may_follow`.
+ """
+ url = get_setting_from_snapshot(
+ "llm.openai_endpoint.url", None, settings_snapshot=settings_snapshot
+ )
+ if not url:
+ return OPENAI_ENDPOINT_DEFAULT_BASE_URL
+ return url
+
+
+def _configured_openai_endpoint_url(settings_snapshot, *, for_record=False):
+ """The configured ``llm.openai_endpoint.url``: where the stored key belongs.
+
+ Resolved from the same sources, in the same order, as the API-key read
+ (:func:`get_setting_from_snapshot`): the snapshot's own
+ ``llm.openai_endpoint.url`` entry first, then the thread-settings-
+ context fallback of that lookup — which is where a snapshot-less
+ caller's (``settings_snapshot=None``, or a snapshot without its own
+ entry) configured URL lives. Key and owner must come from the same
+ source: a key read through the fallback whose owner resolved from the
+ snapshot dict alone would be withheld from its own endpoint and
+ authorised for the provider default instead.
+
+ Two deliberate differences from a plain ``get_setting_from_snapshot``
+ read of that key:
+
+ * The entry is read exactly as it sits in ``settings_snapshot`` at
+ call time: the ``"value"`` of an envelope, or the raw string. That
+ is the stored, configured URL for a snapshot built from the settings
+ database (``get_all_settings(include_environment_overrides=False)``),
+ and the already-overridden URL for a snapshot an earlier write
+ changed — which is why the binder records the owner before it
+ writes. A transient ``LDR_LLM_OPENAI_ENDPOINT_URL`` is never
+ consulted for it: an environment value is policy only while it is
+ set and must never permanently re-own the key. The environment is
+ NOT stripped from the entry itself: a snapshot built with
+ ``include_environment_overrides=True`` or passed through
+ ``apply_environment_overrides_to_snapshot`` already carries the env
+ URL as its value, and that is what this returns — for a decision.
+ For a record (``for_record=True``) such a value is dropped like the
+ fallback's (below), whichever source it came from.
+ * A missing or empty entry falls back to the provider default (the URL
+ the provider contacts unconfigured). A default is reached only here
+ — when it *is* the URL the provider contacts — never in its own
+ right.
+
+ The thread-settings-context fallback may surface the live
+ ``LDR_LLM_OPENAI_ENDPOINT_URL`` (a context built on the settings
+ managers applies ``LDR_*`` overrides on read), and an earlier
+ environment pass may have written that value into the entry itself.
+ Either is fine for a live decision — :func:`_key_may_follow`'s env
+ rule grants exactly its origin while the variable is set and nothing
+ after — but never for a record, which would outlive the variable: the
+ binder's recording path (``for_record=True``) drops a value equal to
+ the live ``LDR_LLM_OPENAI_ENDPOINT_URL``, whichever source it came
+ from, and gets ``""`` ("no owner", failing closed) for it; the
+ provider default must not stand in either, or the default origin
+ would be granted in its own right. The drop is keyed on a LIVE
+ (non-empty) env URL: an empty configured value is not the env value
+ and records the provider default below. A value that merely shares
+ the env URL's origin is not the env value and is recorded as is (it
+ is the stored value a context reports).
+ """
+ raw = None
+ if (
+ isinstance(settings_snapshot, dict)
+ and OPENAI_ENDPOINT_URL_SETTING in settings_snapshot
+ ):
+ raw = settings_snapshot[OPENAI_ENDPOINT_URL_SETTING]
+ if isinstance(raw, dict) and "value" in raw:
+ raw = raw["value"]
+ else:
+ # No entry of its own: the same fallback the key read uses —
+ # ``get_setting_from_snapshot``'s thread-settings-context lookup.
+ raw = get_setting_from_snapshot(
+ OPENAI_ENDPOINT_URL_SETTING,
+ None,
+ settings_snapshot=settings_snapshot,
+ )
+ if not isinstance(raw, str):
+ raw = None
+ if for_record:
+ # A record outlives ``LDR_LLM_OPENAI_ENDPOINT_URL``: a value equal
+ # to the live env URL is transient policy, never stored
+ # configuration, so the recording path drops it whichever source
+ # it came from — the thread-settings-context fallback surfacing
+ # it, or an earlier environment pass writing it into the entry —
+ # and fails closed to "no owner" (see the docstring). The test is
+ # against a LIVE (non-empty) env URL only: ``check_env_setting``
+ # reports unset and empty alike, so without it an empty configured
+ # URL would be dropped whenever no env URL is set — and a missing
+ # or empty value records the provider default below.
+ env_url = _env_openai_endpoint_url()
+ if env_url and raw == env_url:
+ return ""
+ if not raw:
+ return OPENAI_ENDPOINT_DEFAULT_BASE_URL
+ return raw
+
+
+def _env_openai_endpoint_key():
+ """The operator's ``LDR_LLM_OPENAI_ENDPOINT_API_KEY`` while it is set."""
+ return (check_env_setting(OPENAI_ENDPOINT_API_KEY_SETTING) or "").strip()
+
+
+def _key_is_env_supplied(settings_snapshot):
+ """Whether the key a read of ``settings_snapshot`` yields is the env key.
+
+ With ``LDR_LLM_OPENAI_ENDPOINT_API_KEY`` set, an envelope read applies
+ it, a missing entry resolves outside the snapshot, and
+ ``apply_environment_overrides_to_snapshot`` writes it into raw entries.
+ Only a raw entry holding some other value (an explicit key the binder
+ wrote, or the cleared ``""``) is not the env key. Fails toward "env"
+ on anything else.
+ """
+ env_key = _env_openai_endpoint_key()
+ if not env_key:
+ return False
+ if (
+ not isinstance(settings_snapshot, dict)
+ or OPENAI_ENDPOINT_API_KEY_SETTING not in settings_snapshot
+ ):
+ return True
+ entry = settings_snapshot[OPENAI_ENDPOINT_API_KEY_SETTING]
+ if isinstance(entry, dict):
+ return True
+ return str(entry or "").strip() == env_key
+
+
+def _saved_openai_endpoint_url(settings_snapshot, *, for_record=False):
+ """The snapshot's saved ``llm.openai_endpoint.url``, before any override.
+
+ The binder records it under ``OPENAI_ENDPOINT_SAVED_URL_MARKER`` the
+ first time it rewrites the snapshot, from the URL entry as it stood
+ then (:func:`_configured_openai_endpoint_url`: the settings-database
+ or default value for a snapshot built from the settings, the same
+ thread-settings-context fallback the key read uses when there is no
+ snapshot entry — or no snapshot at all —, the provider default for a
+ missing or empty entry). A recorded value is trusted only in the
+ canonical form :func:`_owner_origin_url` writes. Before any binding
+ the URL entry has not been overridden and is read directly. A
+ snapshot that carries a key-owner marker but no saved-URL record
+ fails closed to "no saved URL": the entry may already hold an
+ override, and the owner marker may name a call's URL.
+
+ ``for_record=True`` is the binder's recording path: the recorded saved
+ URL must outlive ``LDR_LLM_OPENAI_ENDPOINT_URL`` without ever steering
+ an env-supplied key to the env URL's former origin, so a value equal
+ to the live env URL is not recorded, whichever source it came from
+ (:func:`_configured_openai_endpoint_url`). Such a record is ``""``,
+ which means no known saved URL and withholds an env-supplied key (fail
+ closed) — unlike an empty ``llm.openai_endpoint.url`` entry, which
+ resolves to the provider default.
+ """
+ if isinstance(settings_snapshot, dict):
+ if OPENAI_ENDPOINT_SAVED_URL_MARKER in settings_snapshot:
+ saved = settings_snapshot.get(OPENAI_ENDPOINT_SAVED_URL_MARKER)
+ if not isinstance(saved, str):
+ return ""
+ return saved if saved == _owner_origin_url(saved) else ""
+ if OPENAI_ENDPOINT_KEY_OWNER_MARKER in settings_snapshot:
+ return ""
+ return _configured_openai_endpoint_url(
+ settings_snapshot, for_record=for_record
+ )
+
+
+def _env_openai_endpoint_url():
+ """The operator's ``LDR_LLM_OPENAI_ENDPOINT_URL`` while it is set.
+
+ Read live at decision time through ``check_env_setting`` (an empty
+ variable counts as unset) and never recorded anywhere: the policy
+ lasts only as long as the variable.
+ """
+ return check_env_setting(OPENAI_ENDPOINT_URL_SETTING) or ""
+
+
+def _key_owner_url(settings_snapshot, *, for_record=False):
+ """The URL a snapshot-supplied ``llm.openai_endpoint.api_key`` belongs to.
+
+ A marker present in the snapshot is trusted when, and only when, it is
+ in the canonical ``scheme://host:port`` form :func:`_owner_origin_url`
+ writes — whichever way the snapshot arrived (binder-written in this
+ process, or carried in a ``base_settings=`` / ``settings_snapshot=``
+ the caller passed). Any other value fails closed to "no owner". With
+ no marker the owner is the configured URL
+ (:func:`_configured_openai_endpoint_url`): the snapshot's entry as
+ stored in it, else the same thread-settings-context fallback the key
+ read uses — so on the ``settings_snapshot=None`` Python-API path the
+ key is owned by the endpoint it was configured for, not by the
+ provider default. The binder never consults ``LDR_LLM_OPENAI_ENDPOINT_URL``
+ directly; a value equal to a live one is used for decisions but never
+ recorded, whichever source it came from (``for_record=True``, see
+ :func:`_configured_openai_endpoint_url`).
+
+ This owner never authorises an env-supplied key; see
+ :func:`_key_may_follow`.
+ """
+ if (
+ isinstance(settings_snapshot, dict)
+ and OPENAI_ENDPOINT_KEY_OWNER_MARKER in settings_snapshot
+ ):
+ owner = settings_snapshot.get(OPENAI_ENDPOINT_KEY_OWNER_MARKER)
+ if not isinstance(owner, str):
+ return ""
+ return owner if owner == _owner_origin_url(owner) else ""
+ return _configured_openai_endpoint_url(
+ settings_snapshot, for_record=for_record
+ )
+
+
+def _owner_origin_url(url):
+ """Record the comparison origin without retaining other URL components."""
+ origin = endpoint_origin(url)
+ if origin is None:
+ return ""
+ scheme, host, port = origin
+ if ":" in host:
+ host = f"[{host}]"
+ return f"{scheme}://{host}:{port}"
+
+
+def _key_may_follow(target_url, owner, settings_snapshot):
+ """Whether the key ``settings_snapshot`` yields may be sent to ``target_url``.
+
+ An env-supplied key (``LDR_LLM_OPENAI_ENDPOINT_API_KEY``, see
+ :func:`_key_is_env_supplied`) follows exactly one origin, the one a
+ plain ``get_llm()`` on the snapshot would send it to: that of
+ ``LDR_LLM_OPENAI_ENDPOINT_URL`` when it is set, otherwise that of the
+ saved ``llm.openai_endpoint.url`` (:func:`_saved_openai_endpoint_url`
+ — an empty ``llm.openai_endpoint.url`` entry is the provider default
+ there; a dropped saved record means no known saved URL and the key is
+ withheld). ``owner`` — which may name a call's URL — does not speak
+ for it, and no default URL is allowed in its own right.
+
+ Any other key may go to ``target_url`` when it shares ``owner``'s
+ origin (scheme, host, port), or when ``target_url`` is on the origin
+ of a currently-set ``LDR_LLM_OPENAI_ENDPOINT_URL``: environment values
+ are operator policy while they are set.
+
+ Both rules are evaluated here, live, and are never recorded as
+ ownership — once a variable is gone its rule no longer applies.
+ """
+ env_url = _env_openai_endpoint_url()
+ if _key_is_env_supplied(settings_snapshot):
+ return same_endpoint_origin(
+ target_url, env_url or _saved_openai_endpoint_url(settings_snapshot)
+ )
+ if same_endpoint_origin(target_url, owner):
+ return True
+ return bool(env_url) and same_endpoint_origin(target_url, env_url)
+
+
+def resolve_openai_endpoint_override_key(endpoint_url, settings_snapshot=None):
+ """Decide whether the stored ``openai_endpoint`` key may go to ``endpoint_url``.
+
+ Returns:
+ ``(key, withheld)``: ``key`` is the key the snapshot yields
+ (stored, or the operator's env key) when ``endpoint_url`` is an
+ origin that key may follow (see :func:`_key_may_follow`: an env
+ key follows the env URL, or with none the saved URL; a
+ stored key follows its owner's origin or a currently-set env
+ URL's), otherwise ``""``.
+ ``withheld`` is True when a stored key exists but the key is not
+ sent.
+ """
+ stored_key = get_setting_from_snapshot(
+ "llm.openai_endpoint.api_key", "", settings_snapshot=settings_snapshot
+ )
+ stored_key = str(stored_key or "").strip()
+ if _key_may_follow(
+ endpoint_url, _key_owner_url(settings_snapshot), settings_snapshot
+ ):
+ return stored_key, False
+ return "", bool(stored_key)
+
+
+def bind_openai_endpoint_override(
+ snapshot, endpoint_url=None, explicit_key=None, *, keep_envelope=False
+):
+ """Point ``snapshot`` at ``endpoint_url`` and keep the API key bound, in place.
+
+ Args:
+ snapshot: The settings snapshot dict to modify.
+ endpoint_url: The new ``llm.openai_endpoint.url``, or ``None`` to
+ keep the current URL and only re-check an earlier binding.
+ explicit_key: A key that belongs to the (new) URL; bound as is.
+ keep_envelope: Write the URL into an existing ``{"value": ...}``
+ envelope (as the runtime-settings overlay does) instead of
+ replacing the entry with the raw string.
+
+ The first binding records, under ``OPENAI_ENDPOINT_KEY_OWNER_MARKER``,
+ the origin the key belongs to (the module docstring lists which origin
+ each snapshot shape records): without an explicit key, the snapshot's
+ URL entry as stored in it — or the thread-settings-context fallback
+ the key read uses when there is no entry — read before the override is
+ written and without the environment applied (a value equal to a live
+ ``LDR_LLM_OPENAI_ENDPOINT_URL`` is dropped from the record rather than
+ written down, whichever source it came from); with one, the URL it
+ was named for, or the URL the provider contacts after the write when
+ that URL has no origin.
+ It also records the saved URL's origin under
+ ``OPENAI_ENDPOINT_SAVED_URL_MARKER``. Later bindings, including the
+ re-check ``get_llm`` runs on every ``openai_endpoint`` call,
+ compare against that origin rather than the snapshot's current one.
+ That makes binding idempotent, and it stops a key that
+ ``apply_environment_overrides_to_snapshot`` writes back from following
+ the overridden URL. An env-supplied key is checked against the env
+ URL (or, with none set, the recorded saved URL) and never against the
+ recorded owner; a stored key is additionally kept for a currently-set
+ ``LDR_LLM_OPENAI_ENDPOINT_URL`` (operator policy). The env origin is
+ never recorded as a stored key's owner. See :func:`_key_may_follow`.
+
+ Clearing is final for that snapshot: the key is not kept anywhere, so
+ binding back to the owner's origin later does not bring it back (fail
+ closed). A run that needs it again starts from a fresh snapshot.
+
+ The cleared key is written as a raw ``""``, never into an envelope:
+ envelope reads apply ``LDR_*`` environment overrides, which would bring
+ the stored key back. An explicit key is written raw too, and
+ ``apply_environment_overrides_to_snapshot`` leaves a raw key under an
+ owner marker in place, so the env key is not swapped in under a
+ record that names another origin. That includes a cleared ``""``: a
+ slot the binder emptied stays empty for that snapshot even when an
+ ``LDR_LLM_OPENAI_ENDPOINT_API_KEY`` is set later.
+
+ Returns:
+ True when a stored key was withheld because the origins differ.
+ """
+ explicit_key = explicit_key.strip() if isinstance(explicit_key, str) else ""
+ # Decision-time and recorded values are distinguished on purpose (see
+ # ``_configured_openai_endpoint_url``): ``owner`` speaks for this
+ # call's keep/clear check below, while ``recorded_owner`` and
+ # ``saved_url`` are written into marker records that outlive a
+ # transient ``LDR_LLM_OPENAI_ENDPOINT_URL`` an earlier environment
+ # pass or the thread-settings-context fallback may surface. A record
+ # naming that value would re-own the key to the env origin after the
+ # variable is gone, so the recording path drops it, whichever source
+ # it came from (failing closed to "no owner"). Nothing is lost at
+ # decision time by that: any authority the transient value carries is
+ # re-granted live by ``_key_may_follow``'s env rule for exactly as
+ # long as the variable is set.
+ owner = _key_owner_url(snapshot)
+ recorded_owner = _key_owner_url(snapshot, for_record=True)
+ # Read before the write, like ``owner``: the saved URL is the entry as
+ # it stood before this (or any earlier) override.
+ saved_url = _owner_origin_url(
+ _saved_openai_endpoint_url(snapshot, for_record=True)
+ )
+
+ if endpoint_url is not None:
+ if keep_envelope:
+ from ..utilities.type_utils import overlay_snapshot_value
+
+ overlay_snapshot_value(
+ snapshot, OPENAI_ENDPOINT_URL_SETTING, endpoint_url
+ )
+ else:
+ snapshot[OPENAI_ENDPOINT_URL_SETTING] = endpoint_url
+
+ # The provider's actual destination after the write (an env override on
+ # an envelope entry can pin it).
+ new_url = effective_openai_endpoint_url(snapshot)
+
+ if explicit_key:
+ snapshot[OPENAI_ENDPOINT_API_KEY_SETTING] = explicit_key
+ # The call's key belongs to the URL it was named for. When that URL
+ # has no origin — none named, or an emptied/blank one — it belongs
+ # to where the provider actually goes after the write: the current
+ # URL when none was named, the provider default for an emptied URL,
+ # the env URL when an ``LDR_LLM_OPENAI_ENDPOINT_URL`` pins an
+ # envelope entry, and no owner for a whitespace-only raw URL.
+ key_owner = (
+ endpoint_url
+ if endpoint_origin(endpoint_url) is not None
+ else new_url
+ )
+ snapshot[OPENAI_ENDPOINT_KEY_OWNER_MARKER] = _owner_origin_url(
+ key_owner
+ )
+ snapshot[OPENAI_ENDPOINT_SAVED_URL_MARKER] = saved_url
+ return False
+
+ if (
+ endpoint_url is None
+ and OPENAI_ENDPOINT_KEY_OWNER_MARKER not in snapshot
+ ):
+ # Nothing was overridden; the stored key belongs to the stored URL.
+ return False
+
+ snapshot[OPENAI_ENDPOINT_KEY_OWNER_MARKER] = _owner_origin_url(
+ recorded_owner
+ )
+ snapshot[OPENAI_ENDPOINT_SAVED_URL_MARKER] = saved_url
+ if _key_may_follow(new_url, owner, snapshot):
+ return False
+
+ stored_key = get_setting_from_snapshot(
+ "llm.openai_endpoint.api_key", "", settings_snapshot=snapshot
+ )
+ snapshot[OPENAI_ENDPOINT_API_KEY_SETTING] = ""
+ if str(stored_key or "").strip():
+ logger.warning(
+ "The configured llm.openai_endpoint.api_key is not sent to an "
+ "endpoint override on a different origin (scheme, host or "
+ "port); the call proceeds without it."
+ )
+ return True
+ return False
diff --git a/src/local_deep_research/defaults/default_settings.json b/src/local_deep_research/defaults/default_settings.json
index 813df710bf..f7e2252ad9 100644
--- a/src/local_deep_research/defaults/default_settings.json
+++ b/src/local_deep_research/defaults/default_settings.json
@@ -4666,6 +4666,20 @@
"value": "https://openrouter.ai/api/v1",
"visible": true
},
+ "benchmark.evaluation.api_key": {
+ "category": "benchmark",
+ "description": "API key for the OpenAI-compatible evaluation endpoint. Leave blank to reuse the research endpoint key when its endpoint settings permit it. Local and private evaluation endpoints can run without a key; use a placeholder for other keyless endpoints.",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Evaluation Endpoint API Key",
+ "options": null,
+ "step": null,
+ "type": "APP",
+ "ui_element": "password",
+ "value": "",
+ "visible": true
+ },
"benchmark.evaluation.temperature": {
"category": "benchmark",
"description": "Sampling temperature for the benchmark judge model (0.0-1.0). Use 0 for deterministic, reproducible grading results. Higher values introduce randomness in evaluation scores.",
diff --git a/src/local_deep_research/settings/manager.py b/src/local_deep_research/settings/manager.py
index ce94017cb4..19cf7eecb9 100644
--- a/src/local_deep_research/settings/manager.py
+++ b/src/local_deep_research/settings/manager.py
@@ -715,6 +715,18 @@ def apply_environment_overrides_to_snapshot(
# injected at dispatch, not only overrides for keys already serialized.
default_metadata = SettingsManager().default_settings
candidate_keys = set(snapshot) | set(default_metadata)
+ # Function-local import: the binding module imports this one.
+ from ..config.openai_endpoint_binding import (
+ OPENAI_ENDPOINT_API_KEY_SETTING,
+ OPENAI_ENDPOINT_KEY_OWNER_MARKER,
+ )
+
+ if OPENAI_ENDPOINT_KEY_OWNER_MARKER in snapshot:
+ # Preserve the value associated with the recorded owner. Envelope
+ # reads already apply the current environment key at dispatch; it
+ # must not replace the configured value retained in the envelope.
+ # Raw entries are explicit or cleared values and stay unchanged.
+ candidate_keys.discard(OPENAI_ENDPOINT_API_KEY_SETTING)
for key in candidate_keys:
if check_env_setting(str(key)) is None:
continue
@@ -1459,6 +1471,8 @@ class SettingsManager(ISettingsManager):
)
for key, metadata in selected_settings:
+ if key.startswith("_"):
+ continue # internal snapshot keys are run metadata, never rows
# Handle type field - it might be a string or an enum
setting_type = metadata["type"]
if hasattr(setting_type, "name"):
diff --git a/src/local_deep_research/utilities/type_utils.py b/src/local_deep_research/utilities/type_utils.py
index 017fefd9c4..58084d9601 100644
--- a/src/local_deep_research/utilities/type_utils.py
+++ b/src/local_deep_research/utilities/type_utils.py
@@ -214,6 +214,14 @@ def overlay_runtime_settings(
``None`` values are skipped so callers can pass through unspecified
fields without clobbering snapshot defaults.
+ ``custom_endpoint`` (``llm.openai_endpoint.url``) is written through
+ :func:`config.openai_endpoint_binding.bind_openai_endpoint_override`, so
+ ``llm.openai_endpoint.api_key`` is cleared when the new URL is on a
+ different origin from the stored one and not on the origin of a set
+ ``LDR_LLM_OPENAI_ENDPOINT_URL``. A key from
+ ``LDR_LLM_OPENAI_ENDPOINT_API_KEY`` is kept only on the env URL's
+ origin, or with no env URL the saved URL's.
+
STRICT-scope security note: under ``policy.egress_scope == strict``
the factory PEP only admits the saved primary engine
(``search.tool``), so overwriting ``search.tool`` with the requested
@@ -239,6 +247,19 @@ def overlay_runtime_settings(
and arg in ("search_engine", "search_tool")
):
continue
+ if key == "llm.openai_endpoint.url":
+ # The endpoint URL and its API key travel together: the
+ # stored key only follows the new URL on the same origin.
+ # Function-local import: config.thread_settings imports
+ # this module.
+ from ..config.openai_endpoint_binding import (
+ bind_openai_endpoint_override,
+ )
+
+ bind_openai_endpoint_override(
+ snapshot, runtime[arg], keep_envelope=True
+ )
+ continue
overlay_snapshot_value(snapshot, key, runtime[arg])
return snapshot
diff --git a/src/local_deep_research/utilities/url_utils.py b/src/local_deep_research/utilities/url_utils.py
index f299e0658f..10aa5fabe4 100644
--- a/src/local_deep_research/utilities/url_utils.py
+++ b/src/local_deep_research/utilities/url_utils.py
@@ -20,6 +20,8 @@ from ..security.network_utils import is_private_ip
# Re-export for backwards compatibility
__all__ = [
"normalize_url",
+ "endpoint_origin",
+ "same_endpoint_origin",
"is_private_ip",
"canonical_url_key",
"content_web_cache_key",
@@ -104,6 +106,38 @@ def normalize_url(raw_url: str) -> str:
return f"{scheme}://{raw_url}"
+def endpoint_origin(raw_url) -> tuple[str, str, int] | None:
+ """Return the ``(scheme, host, port)`` an LLM client built from ``raw_url`` contacts.
+
+ The URL is first passed through :func:`normalize_url`, exactly as the
+ OpenAI-compatible endpoint provider does before building its client,
+ so the origin describes the real destination rather than the text the
+ user typed. Scheme and host are lowercased, a trailing dot on the host
+ is dropped, a missing port takes the scheme default (80/443), and path,
+ query, fragment and userinfo are ignored.
+
+ Returns ``None`` for anything that is not a cleanly parseable http(s)
+ URL with a host, so callers comparing origins fail closed.
+ """
+ if not isinstance(raw_url, str) or not raw_url.strip():
+ return None
+ try:
+ normalized = normalize_url(raw_url)
+ except ValueError:
+ return None
+ # Function-local import: the egress validators import this package's
+ # settings helpers at module load.
+ from ..security.egress.validators import _engine_url_origin
+
+ return _engine_url_origin(normalized)
+
+
+def same_endpoint_origin(url_a, url_b) -> bool:
+ """True only when both URLs parse and resolve to the same origin."""
+ origin_a = endpoint_origin(url_a)
+ return origin_a is not None and origin_a == endpoint_origin(url_b)
+
+
# Internal library-document routes emitted as citation URLs by the RAG
# search engines (see ``LibraryRAGSearchEngine._get_document_url``). These
# are the only scheme-less URLs whose shape ``canonical_url_key`` knows
diff --git a/src/local_deep_research/web/routers/benchmark.py b/src/local_deep_research/web/routers/benchmark.py
index 5e1f1b850d..db98820789 100644
--- a/src/local_deep_research/web/routers/benchmark.py
+++ b/src/local_deep_research/web/routers/benchmark.py
@@ -10,9 +10,11 @@ from ..template_config import templates
import time
from loguru import logger
+from sqlalchemy.exc import SQLAlchemyError
from ...database.session_context import get_user_db_session
from ...llm.providers.base import normalize_provider
+from ...benchmarks.graders import normalize_grader_provider
from local_deep_research.settings import SettingsManager
@@ -100,6 +102,42 @@ router = APIRouter(prefix="/benchmark", tags=["benchmark"])
# fast if the dependency is ever removed.
+def _grader_key_error(evaluation_config, settings_manager):
+ """Refuse a benchmark whose grader would have no key for its endpoint.
+
+ Grading failures are recorded per example, so without this check every
+ example would run its research and then fail to grade. Returns a 400
+ response, or ``None`` when the grader can be built.
+ """
+ from ...benchmarks.graders import (
+ GRADER_KEY_ERROR_MESSAGE,
+ check_grader_endpoint_key,
+ )
+ from ...config.llm_config import LLMNotConfiguredError
+
+ try:
+ snapshot = settings_manager.get_all_settings()
+ except (SQLAlchemyError, LookupError, ValueError):
+ # Same best-effort contract as BenchmarkService.start_benchmark:
+ # an unreadable snapshot is handled (and logged) by the run itself.
+ logger.exception("Grader key pre-check skipped")
+ return None
+ if not isinstance(snapshot, dict):
+ return None
+ try:
+ check_grader_endpoint_key(evaluation_config or None, snapshot)
+ except LLMNotConfiguredError:
+ return JSONResponse(
+ {"success": False, "error": GRADER_KEY_ERROR_MESSAGE},
+ status_code=400,
+ )
+ except Exception:
+ # Anything else is the grader's own failure to report at grading
+ # time, as before this pre-check existed.
+ logger.exception("Grader key pre-check skipped")
+ return None
+
+
def _validate_datasets_config(datasets_config):
"""Return ``(total_examples, error)`` for a benchmark dataset mapping.
@@ -148,6 +186,16 @@ def index(request: Request, username: Annotated[str, Depends(require_auth)]):
"evaluation_temperature": settings_manager.get_setting(
"benchmark.evaluation.temperature", 0
),
+ # Whether a grader key is saved; the key itself never reaches
+ # the page.
+ "evaluation_api_key_saved": bool(
+ str(
+ settings_manager.get_setting(
+ "benchmark.evaluation.api_key", ""
+ )
+ or ""
+ ).strip()
+ ),
}
return templates.TemplateResponse(
@@ -261,9 +309,6 @@ def _start_benchmark_sync(data, username, session_id):
search_config["openai_endpoint_url"] = (
settings_manager.get_setting("llm.openai_endpoint.url")
)
- search_config["openai_endpoint_api_key"] = (
- settings_manager.get_setting("llm.openai_endpoint.api_key")
- )
elif provider == "openai":
search_config["openai_api_key"] = settings_manager.get_setting(
"llm.openai.api_key"
@@ -308,7 +353,9 @@ def _start_benchmark_sync(data, username, session_id):
# Coerce and constrain field types
evaluation_config = {}
if "provider" in raw and isinstance(raw["provider"], str):
- evaluation_config["provider"] = raw["provider"][:64]
+ evaluation_config["provider"] = normalize_grader_provider(
+ raw["provider"][:64]
+ )
if "model_name" in raw and isinstance(raw["model_name"], str):
evaluation_config["model_name"] = raw["model_name"][:256]
if "temperature" in raw:
@@ -327,7 +374,7 @@ def _start_benchmark_sync(data, username, session_id):
pass
else:
# Read evaluation config from database settings
- evaluation_provider = normalize_provider(
+ evaluation_provider = normalize_grader_provider(
settings_manager.get_setting(
"benchmark.evaluation.provider", "openai_endpoint"
)
@@ -355,11 +402,6 @@ def _start_benchmark_sync(data, username, session_id):
"https://openrouter.ai/api/v1",
)
)
- evaluation_config["openai_endpoint_api_key"] = (
- settings_manager.get_setting(
- "llm.openai_endpoint.api_key"
- )
- )
elif evaluation_provider == "openai":
evaluation_config["openai_api_key"] = (
settings_manager.get_setting("llm.openai.api_key")
@@ -369,6 +411,12 @@ def _start_benchmark_sync(data, username, session_id):
settings_manager.get_setting("llm.anthropic.api_key")
)
+ grader_key_error = _grader_key_error(
+ evaluation_config, settings_manager
+ )
+ if grader_key_error is not None:
+ return grader_key_error
+
# Create benchmark run
benchmark_run_id = benchmark_service.create_benchmark_run(
run_name=run_name,
@@ -1084,9 +1132,6 @@ def _start_benchmark_simple_sync(data, username, session_id):
search_config["openai_endpoint_url"] = (
settings_manager.get_setting("llm.openai_endpoint.url")
)
- search_config["openai_endpoint_api_key"] = (
- settings_manager.get_setting("llm.openai_endpoint.api_key")
- )
elif provider == "openai":
search_config["openai_api_key"] = settings_manager.get_setting(
"llm.openai.api_key"
@@ -1097,7 +1142,7 @@ def _start_benchmark_simple_sync(data, username, session_id):
)
# Read evaluation config from database settings
- evaluation_provider = normalize_provider(
+ evaluation_provider = normalize_grader_provider(
settings_manager.get_setting(
"benchmark.evaluation.provider", "openai_endpoint"
)
@@ -1125,9 +1170,6 @@ def _start_benchmark_simple_sync(data, username, session_id):
"https://openrouter.ai/api/v1",
)
)
- evaluation_config["openai_endpoint_api_key"] = (
- settings_manager.get_setting("llm.openai_endpoint.api_key")
- )
elif evaluation_provider == "openai":
evaluation_config["openai_api_key"] = (
settings_manager.get_setting("llm.openai.api_key")
@@ -1137,6 +1179,12 @@ def _start_benchmark_simple_sync(data, username, session_id):
settings_manager.get_setting("llm.anthropic.api_key")
)
+ grader_key_error = _grader_key_error(
+ evaluation_config, settings_manager
+ )
+ if grader_key_error is not None:
+ return grader_key_error
+
# Create and start benchmark
benchmark_run_id = benchmark_service.create_benchmark_run(
run_name=f"Quick Benchmark - {data.get('run_name', '')}",
diff --git a/src/local_deep_research/web/templates/pages/benchmark.html b/src/local_deep_research/web/templates/pages/benchmark.html
index b68e1e86ea..6f1040115a 100644
--- a/src/local_deep_research/web/templates/pages/benchmark.html
+++ b/src/local_deep_research/web/templates/pages/benchmark.html
@@ -245,6 +245,20 @@
class="ldr-form-control"
placeholder="https://openrouter.ai/api/v1" value="{{ eval_settings.evaluation_endpoint_url }}">
<span class="ldr-input-help">API endpoint for evaluation model</span>
+
+ <label for="evaluation_api_key" style="margin-top: 10px;">Endpoint API Key</label>
+ <div style="display: flex; gap: 8px;">
+ <input type="password" id="evaluation_api_key"
+ name="evaluation_api_key"
+ class="ldr-form-control"
+ autocomplete="new-password"
+ data-key-saved="{{ 'true' if eval_settings.evaluation_api_key_saved else 'false' }}"
+ placeholder="{{ 'A key is saved. Enter a new key to replace it' if eval_settings.evaluation_api_key_saved else 'Enter the evaluation endpoint API key' }}">
+ <button type="button" id="evaluation_api_key_clear"
+ class="ldr-btn ldr-btn-outline"
+ aria-label="Clear the saved evaluation endpoint API key">Clear</button>
+ </div>
+ <span class="ldr-input-help">Optional key for this evaluation endpoint. Leave blank to reuse the research key when both endpoints have the same scheme, host and port. Local endpoints can run without a key.</span>
</div>
<!-- Evaluation Temperature -->
@@ -2474,6 +2488,25 @@ function setupEvaluationEventHandlers() {
});
}
+ // Endpoint API key handlers. The saved key is never sent back to the
+ // page, so an empty field means "keep the saved key"; the Clear button
+ // removes it.
+ const evaluationApiKeyInput = document.getElementById('evaluation_api_key');
+ if (evaluationApiKeyInput) {
+ evaluationApiKeyInput.addEventListener('change', function() {
+ const draft = this.value;
+ const value = draft.trim();
+ if (!value) return;
+ saveEvaluationSetting('benchmark.evaluation.api_key', value).then(saved => {
+ if (saved) setEvaluationApiKeySaved(true, draft);
+ });
+ });
+ }
+ const evaluationApiKeyClear = document.getElementById('evaluation_api_key_clear');
+ if (evaluationApiKeyClear) {
+ evaluationApiKeyClear.addEventListener('click', clearEvaluationApiKey);
+ }
+
// Temperature change handler
if (evaluationTemperatureInput) {
evaluationTemperatureInput.addEventListener('change', function() {
@@ -2594,6 +2627,28 @@ function loadEvaluationSettings() {
}
}
+function setEvaluationApiKeySaved(saved, submittedDraft) {
+ const input = document.getElementById('evaluation_api_key');
+ if (!input) return;
+ if (input.value === submittedDraft) input.value = '';
+ input.dataset.keySaved = saved ? 'true' : 'false';
+ input.placeholder = saved
+ ? 'A key is saved. Enter a new key to replace it'
+ : 'Enter the evaluation endpoint API key';
+}
+
+// Remove the saved grader key. DELETE drops the stored row; a PUT of ""
+// would be ignored for a password setting (the settings API reads an empty
+// password field as "left untouched") while still answering 200.
+function clearEvaluationApiKey() {
+ const draft = document.getElementById('evaluation_api_key')?.value;
+ return saveEvaluationSetting('benchmark.evaluation.api_key', undefined, 'DELETE')
+ .then(cleared => {
+ if (cleared) setEvaluationApiKeySaved(false, draft);
+ return cleared;
+ });
+}
+
function setEvaluationDefaults() {
console.log('Setting evaluation defaults');
if (evaluationProviderSelect) {
@@ -2609,9 +2664,12 @@ function setEvaluationDefaults() {
if (evaluationModelInput) evaluationModelInput.value = 'anthropic/claude-3.7-sonnet';
if (evaluationEndpointInput) evaluationEndpointInput.value = 'https://openrouter.ai/api/v1';
if (evaluationTemperatureInput) evaluationTemperatureInput.value = 0;
+ // Defaults carry no grader key; the saved one is removed with Clear.
+ const evaluationApiKeyInput = document.getElementById('evaluation_api_key');
+ if (evaluationApiKeyInput) evaluationApiKeyInput.value = '';
}
-function saveEvaluationSetting(key, value) {
+function saveEvaluationSetting(key, value, method = 'PUT') {
saveEvaluationSetting.pending = (saveEvaluationSetting.pending || 0) + 1;
saveEvaluationSetting.failedKeys ||= new Set();
const save = () => {
@@ -2623,24 +2681,30 @@ function saveEvaluationSetting(key, value) {
let request;
try {
request = fetch(`/settings/api/${key}`, {
- method: 'PUT',
+ method,
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': csrfToken
},
- body: JSON.stringify({ value })
+ ...(method === 'DELETE' ? {} : { body: JSON.stringify({ value }) })
});
} catch (error) {
request = Promise.reject(error);
}
return request
.then(async response => {
- const data = await response.json();
- // The settings PUT route returns a message on success,
- // including idempotent no-ops. It does not return a
- // success boolean.
- if (response.ok !== true || typeof data?.message !== 'string') {
- throw new Error('Evaluation setting was not saved');
+ if (method === 'DELETE') {
+ // A missing stored value already satisfies Clear.
+ if (response.ok !== true && response.status !== 404) {
+ throw new Error('Evaluation setting was not cleared');
+ }
+ } else {
+ const data = await response.json();
+ // The settings PUT route returns a message on success,
+ // including idempotent no-ops.
+ if (response.ok !== true || typeof data?.message !== 'string') {
+ throw new Error('Evaluation setting was not saved');
+ }
}
saveEvaluationSetting.failedKeys.delete(key);
if (key === 'benchmark.evaluation.endpoint_url') {
diff --git a/tests/api/test_research_functions_endpoint_key.py b/tests/api/test_research_functions_endpoint_key.py
new file mode 100644
index 0000000000..62ef771682
--- /dev/null
+++ b/tests/api/test_research_functions_endpoint_key.py
@@ -0,0 +1,283 @@
+"""A key passed in the same Python API call as ``openai_endpoint_url`` reaches it.
+
+``quick_summary(provider="openai_endpoint", api_key=K,
+openai_endpoint_url=X)`` names both the endpoint and its key. The
+``custom_endpoint`` overlay must not treat that ``K`` as the stored key of a
+different endpoint and withhold it. A key that only comes from
+``settings_snapshot`` (or stored settings) is still withheld on a different
+origin, and when both exist the call's ``api_key`` wins.
+
+The langchain client class, the search engine and the search system are
+patched; every endpoint is a loopback URL.
+"""
+
+from unittest.mock import MagicMock, patch
+
+import pytest
+from langchain_core.language_models.fake_chat_models import FakeListChatModel
+
+from local_deep_research.api import research_functions
+from local_deep_research.config.thread_settings import settings_context
+from local_deep_research.llm.providers.base import OPTIONAL_API_KEY_PLACEHOLDER
+from local_deep_research.settings.manager import SnapshotSettingsContext
+
+OPENAI_BASE_CHAT = "local_deep_research.llm.providers.openai_base.ChatOpenAI"
+VLLM_URL = "http://localhost:8000/v1"
+SNAPSHOT_KEY = "sk-from-the-snapshot"
+CALL_KEY = "sk-passed-with-the-url"
+
+
[email protected](autouse=True, scope="module")
+def _ensure_providers_registered():
+ from local_deep_research.llm.providers import discover_providers
+
+ discover_providers(force_refresh=True)
+
+
+def _snapshot(key=SNAPSHOT_KEY):
+ # The stored endpoint is elsewhere: OpenRouter, the shipped default.
+ return {
+ "llm.provider": {"value": "openai_endpoint", "ui_element": "select"},
+ "llm.model": {"value": "m", "ui_element": "text"},
+ "llm.supports_max_tokens": {"value": True, "ui_element": "checkbox"},
+ "llm.max_tokens": {"value": 4096, "ui_element": "number"},
+ "rate_limiting.llm_enabled": {"value": False, "ui_element": "checkbox"},
+ "search.tool": {"value": "searxng", "ui_element": "select"},
+ "llm.openai_endpoint.url": {
+ "value": "https://openrouter.ai/api/v1",
+ "ui_element": "text",
+ },
+ "llm.openai_endpoint.api_key": {"value": key, "ui_element": "password"},
+ }
+
+
+def _client_kwargs(**init_kwargs):
+ with (
+ patch(
+ OPENAI_BASE_CHAT, return_value=FakeListChatModel(responses=["ok"])
+ ) as mock_chat,
+ patch.object(research_functions, "get_search", MagicMock()),
+ patch.object(research_functions, "AdvancedSearchSystem", MagicMock()),
+ ):
+ research_functions._init_search_system(
+ model_name="m",
+ provider="openai_endpoint",
+ openai_endpoint_url=VLLM_URL,
+ **init_kwargs,
+ )
+ return mock_chat.call_args.kwargs
+
+
+class TestInitSearchSystemCallKey:
+ @pytest.mark.parametrize("provider", ["openai_endpoint", None])
+ def test_call_endpoint_is_shared_with_later_snapshot_consumers(
+ self, monkeypatch, provider
+ ):
+ from local_deep_research.config.llm_config import get_llm
+
+ monkeypatch.setenv(
+ "LDR_LLM_OPENAI_ENDPOINT_URL", "http://localhost:9100/v1"
+ )
+ with (
+ patch(
+ OPENAI_BASE_CHAT,
+ return_value=FakeListChatModel(responses=["ok"]),
+ ) as mock_chat,
+ patch.object(research_functions, "get_search", MagicMock()),
+ patch.object(research_functions, "AdvancedSearchSystem") as system,
+ ):
+ research_functions._init_search_system(
+ model_name="m",
+ provider=provider,
+ openai_endpoint_url=VLLM_URL,
+ api_key=CALL_KEY,
+ settings_snapshot=_snapshot(),
+ )
+ downstream_snapshot = system.call_args.kwargs["settings_snapshot"]
+ get_llm(
+ provider="openai_endpoint",
+ model_name="m",
+ settings_snapshot=downstream_snapshot,
+ )
+
+ assert [
+ (call.kwargs["base_url"], call.kwargs["api_key"])
+ for call in mock_chat.call_args_list
+ ] == [(VLLM_URL, CALL_KEY), (VLLM_URL, CALL_KEY)]
+
+ def test_key_passed_with_the_url_reaches_that_url(self):
+ kwargs = _client_kwargs(
+ settings_snapshot=_snapshot(key=CALL_KEY), api_key=CALL_KEY
+ )
+ assert kwargs["base_url"] == VLLM_URL
+ assert kwargs["api_key"] == CALL_KEY
+
+ def test_snapshot_only_key_is_still_withheld_on_another_origin(self):
+ kwargs = _client_kwargs(settings_snapshot=_snapshot())
+ assert kwargs["base_url"] == VLLM_URL
+ assert kwargs["api_key"] == OPTIONAL_API_KEY_PLACEHOLDER
+
+ def test_call_key_wins_over_a_snapshot_key(self):
+ kwargs = _client_kwargs(settings_snapshot=_snapshot(), api_key=CALL_KEY)
+ assert kwargs["api_key"] == CALL_KEY
+
+ def test_call_key_is_not_bound_for_another_provider(self):
+ """api_key belongs to the named provider; for a non-endpoint
+ provider it must not land in llm.openai_endpoint.api_key."""
+ snapshot = _snapshot()
+ snapshot["llm.provider"] = {"value": "ollama", "ui_element": "select"}
+ captured = {}
+
+ def fake_get_llm(**kwargs):
+ captured.update(kwargs)
+ return MagicMock()
+
+ with (
+ patch.object(research_functions, "get_llm", fake_get_llm),
+ patch.object(research_functions, "get_search", MagicMock()),
+ patch.object(
+ research_functions, "AdvancedSearchSystem", MagicMock()
+ ),
+ ):
+ research_functions._init_search_system(
+ model_name="m",
+ openai_endpoint_url=VLLM_URL,
+ api_key=CALL_KEY,
+ settings_snapshot=snapshot,
+ )
+ assert captured["openai_endpoint_api_key"] is None
+ bound = captured["settings_snapshot"]["llm.openai_endpoint.api_key"]
+ assert bound != CALL_KEY
+
+
+class TestInitSearchSystemCallKeyLateProvider:
+ """The call key must survive when the provider resolves only later.
+
+ Two reachable shapes used the call URL while dropping ``api_key``:
+ ``settings_snapshot=None`` (the provider resolves from the thread
+ settings context or get_llm's own defaults) and a snapshot without
+ ``llm.provider`` (the drop left the overlay writing the call URL into
+ the snapshot keyless).
+ """
+
+ def test_call_key_is_forwarded_when_the_provider_is_unresolved(self):
+ captured = {}
+
+ def fake_get_llm(**kwargs):
+ captured.update(kwargs)
+ return MagicMock()
+
+ with (
+ patch.object(research_functions, "get_llm", fake_get_llm),
+ patch.object(research_functions, "get_search", MagicMock()),
+ patch.object(
+ research_functions, "AdvancedSearchSystem", MagicMock()
+ ),
+ ):
+ research_functions._init_search_system(
+ model_name="m",
+ openai_endpoint_url=VLLM_URL,
+ api_key=CALL_KEY,
+ settings_snapshot=None,
+ )
+ assert captured["openai_endpoint_api_key"] == CALL_KEY
+
+ def test_call_key_reaches_the_url_without_a_settings_snapshot(self):
+ ctx = SnapshotSettingsContext(
+ {
+ "llm.provider": {
+ "value": "openai_endpoint",
+ "ui_element": "select",
+ }
+ }
+ )
+ with (
+ settings_context(ctx),
+ patch(
+ OPENAI_BASE_CHAT,
+ return_value=FakeListChatModel(responses=["ok"]),
+ ) as mock_chat,
+ patch.object(research_functions, "get_search", MagicMock()),
+ patch.object(
+ research_functions, "AdvancedSearchSystem", MagicMock()
+ ),
+ ):
+ research_functions._init_search_system(
+ model_name="m",
+ openai_endpoint_url=VLLM_URL,
+ api_key=CALL_KEY,
+ settings_snapshot=None,
+ )
+ assert [
+ (call.kwargs["base_url"], call.kwargs["api_key"])
+ for call in mock_chat.call_args_list
+ ] == [(VLLM_URL, CALL_KEY)]
+
+ def test_call_key_is_bound_when_the_snapshot_lacks_a_provider(self):
+ snapshot = _snapshot()
+ del snapshot["llm.provider"]
+ captured = {}
+
+ def fake_get_llm(**kwargs):
+ captured.update(kwargs)
+ return MagicMock()
+
+ with (
+ patch.object(research_functions, "get_llm", fake_get_llm),
+ patch.object(research_functions, "get_search", MagicMock()),
+ patch.object(
+ research_functions, "AdvancedSearchSystem", MagicMock()
+ ),
+ ):
+ research_functions._init_search_system(
+ model_name="m",
+ openai_endpoint_url=VLLM_URL,
+ api_key=CALL_KEY,
+ settings_snapshot=snapshot,
+ )
+ assert captured["openai_endpoint_api_key"] == CALL_KEY
+ bound = captured["settings_snapshot"]
+ assert bound["llm.openai_endpoint.url"] == VLLM_URL
+ assert bound["llm.openai_endpoint.api_key"] == CALL_KEY
+
+
+class _Stop(Exception):
+ pass
+
+
[email protected]("entry", ["quick_summary", "generate_report"])
+def test_public_entry_points_forward_the_call_key(entry):
+ seen = {}
+
+ def fake_init(**kwargs):
+ seen.update(kwargs)
+ raise _Stop
+
+ with patch.object(research_functions, "_init_search_system", fake_init):
+ with pytest.raises(_Stop):
+ getattr(research_functions, entry)(
+ "q",
+ api_key=CALL_KEY,
+ openai_endpoint_url=VLLM_URL,
+ settings_snapshot=_snapshot(),
+ )
+ assert seen["api_key"] == CALL_KEY
+ assert seen["openai_endpoint_url"] == VLLM_URL
+
+
+def test_detailed_research_forwards_the_call_key():
+ seen = {}
+
+ def fake_init(**kwargs):
+ seen.update(kwargs)
+ raise _Stop
+
+ with patch.object(research_functions, "_init_search_system", fake_init):
+ with pytest.raises(_Stop):
+ research_functions.detailed_research(
+ "q",
+ api_key=CALL_KEY,
+ openai_endpoint_url=VLLM_URL,
+ settings_snapshot=_snapshot(),
+ )
+ assert seen["api_key"] == CALL_KEY
diff --git a/tests/api/test_settings_utils.py b/tests/api/test_settings_utils.py
index e3b304c4f2..7866af42e3 100644
--- a/tests/api/test_settings_utils.py
+++ b/tests/api/test_settings_utils.py
@@ -445,6 +445,38 @@ class TestCreateSettingsSnapshot:
)
assert snapshot["new.dict"]["ui_element"] == "json"
+ def test_internal_underscore_keys_are_refused(self):
+ """Internal underscore keys are refused."""
+ with pytest.raises(ValueError, match="internal snapshot key"):
+ create_settings_snapshot(overrides={"_username": "attacker"})
+ with pytest.raises(ValueError, match="internal snapshot key"):
+ create_settings_snapshot(
+ overrides={
+ "_openai_endpoint_key_owner_url": "https://attacker.example:443",
+ "llm.openai_endpoint.url": "https://attacker.example/v1",
+ }
+ )
+
+ def test_same_call_endpoint_key_matches_a_normalized_provider(self):
+ """Same call endpoint key matches a normalized provider."""
+ for provider in (
+ "openai_endpoint",
+ "OPENAI_ENDPOINT",
+ "OpenAI_Endpoint ",
+ ):
+ snapshot = create_settings_snapshot(
+ provider=provider,
+ api_key="sk-call-key",
+ overrides={
+ "llm.openai_endpoint.url": "http://localhost:8000/v1"
+ },
+ )
+ assert snapshot["llm.openai_endpoint.api_key"] == "sk-call-key"
+ assert (
+ snapshot["_openai_endpoint_key_owner_url"]
+ == "http://localhost:8000"
+ )
+
class TestExtractSettingValue:
"""Tests for extract_setting_value function."""
diff --git a/tests/benchmarks/test_grader_endpoint_key.py b/tests/benchmarks/test_grader_endpoint_key.py
new file mode 100644
index 0000000000..6efbd83f34
--- /dev/null
+++ b/tests/benchmarks/test_grader_endpoint_key.py
@@ -0,0 +1,549 @@
+"""The benchmark grader only reuses the research endpoint key on the same origin.
+
+The grader defaults to ``openai_endpoint`` at ``benchmark.evaluation.endpoint_url``
+(OpenRouter). Its key comes from ``benchmark.evaluation.api_key``; the
+research key ``llm.openai_endpoint.api_key`` is reused only when the grader
+endpoint has the same origin as ``llm.openai_endpoint.url``.
+
+The decision tests patch ``graders.get_llm`` and inspect what it receives,
+so no client is built and no network is touched. The integration test runs
+the real ``get_llm`` with the langchain client class patched, on loopback
+URLs only.
+"""
+
+from unittest.mock import MagicMock, patch
+
+import pytest
+from langchain_core.language_models.fake_chat_models import FakeListChatModel
+
+from local_deep_research.benchmarks import graders
+from local_deep_research.config.llm_config import LLMNotConfiguredError
+from local_deep_research.config.openai_endpoint_binding import (
+ resolve_openai_endpoint_override_key,
+)
+from local_deep_research.config.thread_settings import settings_context
+from local_deep_research.settings.manager import SnapshotSettingsContext
+
+RESEARCH_KEY = "sk-research-gateway-key"
+GRADER_KEY = "sk-grader-key"
+GATEWAY_URL = "https://llm-gateway.corp.example/v1"
+OPENROUTER_URL = "https://openrouter.ai/api/v1"
+
+
+def _snapshot(research_url=GATEWAY_URL, grader_key=None, grader_url=None):
+ snap = {
+ "llm.openai_endpoint.url": {"value": research_url},
+ "llm.openai_endpoint.api_key": {
+ "value": RESEARCH_KEY,
+ "ui_element": "password",
+ },
+ }
+ if grader_url is not None:
+ snap["benchmark.evaluation.endpoint_url"] = {"value": grader_url}
+ if grader_key is not None:
+ snap["benchmark.evaluation.api_key"] = {
+ "value": grader_key,
+ "ui_element": "password",
+ }
+ return snap
+
+
+class TestGraderKeyResolution:
+ def test_default_grader_on_another_origin_does_not_get_research_key(self):
+ with patch.object(graders, "get_llm") as mock_get_llm:
+ with pytest.raises(LLMNotConfiguredError) as exc:
+ graders.get_evaluation_llm(settings_snapshot=_snapshot())
+
+ mock_get_llm.assert_not_called()
+ message = str(exc.value)
+ assert "benchmark.evaluation.api_key" in message
+ assert RESEARCH_KEY not in message
+
+ def test_same_origin_grader_reuses_research_key(self):
+ with patch.object(graders, "get_llm") as mock_get_llm:
+ mock_get_llm.return_value = MagicMock()
+ graders.get_evaluation_llm(
+ # Different path and host case, same origin.
+ custom_config={
+ "openai_endpoint_url": "https://LLM-Gateway.corp.example/v1/"
+ },
+ settings_snapshot=_snapshot(),
+ )
+
+ kwargs = mock_get_llm.call_args.kwargs
+ assert kwargs["openai_endpoint_api_key"] == RESEARCH_KEY
+
+ def test_grader_key_setting_is_used_for_another_origin(self):
+ with patch.object(graders, "get_llm") as mock_get_llm:
+ mock_get_llm.return_value = MagicMock()
+ graders.get_evaluation_llm(
+ settings_snapshot=_snapshot(grader_key=GRADER_KEY)
+ )
+
+ kwargs = mock_get_llm.call_args.kwargs
+ assert kwargs["openai_endpoint_url"] == OPENROUTER_URL
+ assert kwargs["openai_endpoint_api_key"] == GRADER_KEY
+ assert RESEARCH_KEY not in repr(
+ {k: v for k, v in kwargs.items() if k != "settings_snapshot"}
+ )
+
+ def test_grader_key_setting_wins_on_the_same_origin(self):
+ with patch.object(graders, "get_llm") as mock_get_llm:
+ mock_get_llm.return_value = MagicMock()
+ graders.get_evaluation_llm(
+ settings_snapshot=_snapshot(
+ research_url=OPENROUTER_URL, grader_key=GRADER_KEY
+ )
+ )
+
+ assert mock_get_llm.call_args.kwargs["openai_endpoint_api_key"] == (
+ GRADER_KEY
+ )
+
+ def test_custom_config_api_key_is_forwarded_as_endpoint_key(self):
+ with patch.object(graders, "get_llm") as mock_get_llm:
+ mock_get_llm.return_value = MagicMock()
+ graders.get_evaluation_llm(
+ custom_config={"api_key": GRADER_KEY},
+ settings_snapshot=_snapshot(),
+ )
+
+ kwargs = mock_get_llm.call_args.kwargs
+ assert "api_key" not in kwargs
+ assert kwargs["openai_endpoint_api_key"] == GRADER_KEY
+
+ def test_no_research_key_and_no_grader_key_proceeds_without_a_key(self):
+ snapshot = _snapshot()
+ snapshot["llm.openai_endpoint.api_key"] = {"value": ""}
+ with patch.object(graders, "get_llm") as mock_get_llm:
+ mock_get_llm.return_value = MagicMock()
+ graders.get_evaluation_llm(settings_snapshot=snapshot)
+
+ assert mock_get_llm.call_args.kwargs["openai_endpoint_api_key"] == ""
+
+ def test_non_endpoint_grader_is_unaffected(self):
+ with patch.object(graders, "get_llm") as mock_get_llm:
+ mock_get_llm.return_value = MagicMock()
+ graders.get_evaluation_llm(
+ custom_config={"provider": "openai", "model_name": "m"},
+ settings_snapshot=_snapshot(),
+ )
+
+ assert "openai_endpoint_api_key" not in mock_get_llm.call_args.kwargs
+
+
+class TestGraderWithAnEnvironmentResearchKey:
+ """Grader With An Environment Research Key."""
+
+ ENV_KEY = "sk-operator-env-key"
+
+ @pytest.fixture(autouse=True)
+ def _env(self, monkeypatch):
+ monkeypatch.setenv("LDR_LLM_OPENAI_ENDPOINT_API_KEY", self.ENV_KEY)
+ monkeypatch.delenv("LDR_LLM_OPENAI_ENDPOINT_URL", raising=False)
+ monkeypatch.delenv("LDR_BENCHMARK_EVALUATION_API_KEY", raising=False)
+
+ def test_default_grader_does_not_get_the_env_key(self):
+ with patch.object(graders, "get_llm") as mock_get_llm:
+ with pytest.raises(LLMNotConfiguredError) as exc:
+ graders.get_evaluation_llm(settings_snapshot=_snapshot())
+
+ mock_get_llm.assert_not_called()
+ assert self.ENV_KEY not in str(exc.value)
+
+ def test_default_grader_with_an_empty_saved_url_raises(self):
+ """An empty saved URL means api.openai.com, not the OpenRouter grader."""
+ with patch.object(graders, "get_llm") as mock_get_llm:
+ with pytest.raises(LLMNotConfiguredError):
+ graders.get_evaluation_llm(
+ settings_snapshot=_snapshot(research_url="")
+ )
+
+ mock_get_llm.assert_not_called()
+
+ def test_grader_on_the_saved_url_gets_the_env_key(self):
+ with patch.object(graders, "get_llm") as mock_get_llm:
+ mock_get_llm.return_value = MagicMock()
+ graders.get_evaluation_llm(
+ settings_snapshot=_snapshot(grader_url=GATEWAY_URL)
+ )
+
+ kwargs = mock_get_llm.call_args.kwargs
+ assert kwargs["openai_endpoint_api_key"] == self.ENV_KEY
+
+
+class TestGraderKeyOnTheThreadContextPath:
+ """The documented Python-API shape: ``settings_snapshot=None``, thread context.
+
+ ``evaluate_simpleqa`` / ``compare_configurations`` / ``SimpleQAEvaluator``
+ reach ``resolve_grader_endpoint_api_key`` with ``settings_snapshot=None``
+ while a thread settings context is bound. The key resolves through that
+ context (``get_setting_from_snapshot``'s fallback), so the key's owner —
+ the configured ``llm.openai_endpoint.url`` — must resolve through the
+ SAME source. Otherwise the key is withheld from its own endpoint
+ (falsifying the error message's remedy: "point the grader at the
+ research endpoint (llm.openai_endpoint.url)") and, worse, the provider
+ default origin is treated as the owner and DOES receive it.
+ """
+
+ @pytest.fixture(autouse=True)
+ def _ctx(self, monkeypatch):
+ monkeypatch.delenv("LDR_LLM_OPENAI_ENDPOINT_URL", raising=False)
+ monkeypatch.delenv("LDR_LLM_OPENAI_ENDPOINT_API_KEY", raising=False)
+ ctx = SnapshotSettingsContext(
+ {
+ "llm.openai_endpoint.url": {
+ "value": GATEWAY_URL,
+ "ui_element": "text",
+ },
+ "llm.openai_endpoint.api_key": {
+ "value": RESEARCH_KEY,
+ "ui_element": "password",
+ },
+ "benchmark.evaluation.endpoint_url": {
+ "value": GATEWAY_URL,
+ "ui_element": "text",
+ },
+ }
+ )
+ with settings_context(ctx):
+ yield
+
+ def test_grader_on_the_research_endpoint_gets_the_research_key(self):
+ with patch.object(graders, "get_llm") as mock_get_llm:
+ mock_get_llm.return_value = MagicMock()
+ graders.get_evaluation_llm(settings_snapshot=None)
+
+ kwargs = mock_get_llm.call_args.kwargs
+ assert kwargs["openai_endpoint_url"] == GATEWAY_URL
+ assert kwargs["openai_endpoint_api_key"] == RESEARCH_KEY
+
+ def test_grader_config_pointed_at_the_research_endpoint_gets_the_key(self):
+ """The remedy in GRADER_KEY_ERROR_MESSAGE, followed literally."""
+ with patch.object(graders, "get_llm") as mock_get_llm:
+ mock_get_llm.return_value = MagicMock()
+ graders.get_evaluation_llm(
+ custom_config={"openai_endpoint_url": GATEWAY_URL},
+ settings_snapshot=None,
+ )
+
+ assert mock_get_llm.call_args.kwargs["openai_endpoint_api_key"] == (
+ RESEARCH_KEY
+ )
+
+ def test_key_is_withheld_from_foreign_and_default_origins(self):
+ """A foreign origin — including the provider default — gets no key.
+
+ The provider default (https://api.openai.com/v1) is not the key's
+ owner just because it is where the provider goes unconfigured: a
+ default is reached only when it is the saved URL. Here the saved
+ URL is the gateway, so the default must be refused like any other
+ foreign origin.
+ """
+ for grader_url in (
+ "https://api.openai.com/v1",
+ OPENROUTER_URL,
+ ):
+ assert resolve_openai_endpoint_override_key(grader_url, None) == (
+ "",
+ True,
+ )
+ with patch.object(graders, "get_llm") as mock_get_llm:
+ with pytest.raises(LLMNotConfiguredError) as exc:
+ graders.get_evaluation_llm(
+ custom_config={"openai_endpoint_url": grader_url},
+ settings_snapshot=None,
+ )
+ mock_get_llm.assert_not_called()
+ assert str(exc.value) == graders.GRADER_KEY_ERROR_MESSAGE
+ assert RESEARCH_KEY not in str(exc.value)
+
+
+class TestGraderKeyBoundToGraderEndpoint:
+ """benchmark.evaluation.api_key only goes to benchmark.evaluation.endpoint_url."""
+
+ JUDGE_URL = "https://judge.example/v1"
+
+ def test_grader_key_is_not_sent_to_another_config_url(self):
+ with patch.object(graders, "get_llm") as mock_get_llm:
+ with pytest.raises(LLMNotConfiguredError):
+ graders.get_evaluation_llm(
+ custom_config={
+ "openai_endpoint_url": "https://elsewhere.example/v1"
+ },
+ settings_snapshot=_snapshot(
+ grader_key=GRADER_KEY, grader_url=self.JUDGE_URL
+ ),
+ )
+ mock_get_llm.assert_not_called()
+
+ @pytest.mark.parametrize(
+ "custom_config",
+ [
+ {"provider": "openai_endpoint"}, # request-supplied config
+ {"openai_endpoint_url": None},
+ None,
+ ],
+ ids=["request-config", "explicit-none-url", "no-config"],
+ )
+ def test_config_without_url_uses_the_configured_grader_endpoint(
+ self, custom_config
+ ):
+ with patch.object(graders, "get_llm") as mock_get_llm:
+ mock_get_llm.return_value = MagicMock()
+ graders.get_evaluation_llm(
+ custom_config=custom_config,
+ settings_snapshot=_snapshot(
+ grader_key=GRADER_KEY, grader_url=self.JUDGE_URL
+ ),
+ )
+
+ kwargs = mock_get_llm.call_args.kwargs
+ assert kwargs["openai_endpoint_url"] == self.JUDGE_URL
+ assert kwargs["openai_endpoint_api_key"] == GRADER_KEY
+
+ def test_preflight_raises_the_fixed_message_without_building_a_client(
+ self,
+ ):
+ with patch.object(graders, "get_llm") as mock_get_llm:
+ with pytest.raises(LLMNotConfiguredError) as exc:
+ graders.check_grader_endpoint_key(
+ {"provider": "openai_endpoint"}, _snapshot()
+ )
+ mock_get_llm.assert_not_called()
+ assert str(exc.value) == graders.GRADER_KEY_ERROR_MESSAGE
+ assert "different origin (scheme, host or port)" in str(exc.value)
+
+ def test_preflight_passes_when_the_grader_key_matches(self):
+ graders.check_grader_endpoint_key(
+ None, _snapshot(grader_key=GRADER_KEY)
+ )
+
+
+class TestGraderKeyReachesClient:
+ """End to end through the real get_llm, loopback URLs only."""
+
+ @pytest.fixture(autouse=True)
+ def _providers(self):
+ from local_deep_research.llm.providers import discover_providers
+
+ discover_providers(force_refresh=True)
+
+ def _build(self, snapshot, grader_url):
+ snapshot = {
+ "llm.supports_max_tokens": True,
+ "llm.max_tokens": 4096,
+ "rate_limiting.llm_enabled": False,
+ "search.tool": "searxng",
+ **snapshot,
+ }
+ with patch(
+ "local_deep_research.llm.providers.openai_base.ChatOpenAI",
+ return_value=FakeListChatModel(responses=["ok"]),
+ ) as mock_chat:
+ graders.get_evaluation_llm(
+ custom_config={
+ "model_name": "judge-model",
+ "openai_endpoint_url": grader_url,
+ },
+ settings_snapshot=snapshot,
+ )
+ return mock_chat.call_args.kwargs
+
+ def test_grader_key_reaches_client_for_another_origin(self):
+ kwargs = self._build(
+ _snapshot(
+ research_url="http://localhost:9000/v1",
+ grader_key=GRADER_KEY,
+ grader_url="http://localhost:8000/v1",
+ ),
+ "http://localhost:8000/v1",
+ )
+ assert kwargs["base_url"] == "http://localhost:8000/v1"
+ assert kwargs["api_key"] == GRADER_KEY
+
+ def test_research_key_reaches_client_for_the_same_origin(self):
+ kwargs = self._build(
+ _snapshot(research_url="http://localhost:9000/v1"),
+ "http://localhost:9000/other/",
+ )
+ assert kwargs["api_key"] == RESEARCH_KEY
+
+
+class TestKeylessLocalGrader:
+ def test_local_grader_without_a_key_runs_keyless(self):
+ """A local grader (e.g. Ollama) needs no key; the research key on
+ another origin is withheld but grading is not refused."""
+ with patch.object(graders, "get_llm") as mock_get_llm:
+ mock_get_llm.return_value = MagicMock()
+ graders.get_evaluation_llm(
+ custom_config={
+ "openai_endpoint_url": "http://localhost:11434/v1"
+ },
+ settings_snapshot=_snapshot(),
+ )
+
+ kwargs = mock_get_llm.call_args.kwargs
+ assert kwargs["openai_endpoint_api_key"] == ""
+ assert RESEARCH_KEY not in repr(
+ {k: v for k, v in kwargs.items() if k != "settings_snapshot"}
+ )
+
+ @pytest.mark.parametrize(
+ "url", ["http://192.168.1.20:8000/v1", "http://gpu-box.local:8000/v1"]
+ )
+ def test_private_address_grader_runs_keyless(self, url):
+ with patch.object(graders, "get_llm") as mock_get_llm:
+ mock_get_llm.return_value = MagicMock()
+ graders.get_evaluation_llm(
+ custom_config={"openai_endpoint_url": url},
+ settings_snapshot=_snapshot(),
+ )
+ assert mock_get_llm.call_args.kwargs["openai_endpoint_api_key"] == ""
+
+ def test_error_message_explains_keyless_graders(self):
+ assert "localhost" in graders.GRADER_KEY_ERROR_MESSAGE
+ assert "placeholder" in graders.GRADER_KEY_ERROR_MESSAGE
+
+
+class TestRunnerPrecheck:
+ @pytest.fixture(autouse=True)
+ def _pin_data_directory(self, tmp_path, monkeypatch):
+ """Keep benchmark output out of the real user data directory.
+
+ run_benchmark resolves its output directory inside LDR_DATA_DIR and
+ creates it before loading the dataset.
+ """
+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))
+
+ def test_run_benchmark_refuses_before_loading_the_dataset(self, tmp_path):
+ from local_deep_research.benchmarks import runners
+
+ with (
+ patch.object(runners, "DatasetRegistry") as registry,
+ patch.object(runners, "load_dataset") as legacy_loader,
+ patch.object(runners, "quick_summary") as research,
+ ):
+ with pytest.raises(LLMNotConfiguredError):
+ runners.run_benchmark(
+ "simpleqa",
+ num_examples=1,
+ settings_snapshot=_snapshot(),
+ output_dir=str(tmp_path),
+ )
+ registry.create_dataset.assert_not_called()
+ legacy_loader.assert_not_called()
+ research.assert_not_called()
+
+ def test_run_benchmark_without_evaluation_skips_the_check(self, tmp_path):
+ from local_deep_research.benchmarks import runners
+
+ with (
+ patch.object(runners, "check_grader_endpoint_key") as check,
+ patch.object(
+ runners.DatasetRegistry,
+ "create_dataset",
+ side_effect=RuntimeError("stop"),
+ ),
+ patch.object(
+ runners, "load_dataset", side_effect=RuntimeError("stop")
+ ),
+ ):
+ with pytest.raises(RuntimeError, match="stop"):
+ runners.run_benchmark(
+ "simpleqa",
+ num_examples=1,
+ run_evaluation=False,
+ output_dir=str(tmp_path),
+ )
+ check.assert_not_called()
+
+ def test_simpleqa_evaluator_checks_before_research(self, tmp_path):
+ from local_deep_research.benchmarks.evaluators import simpleqa
+
+ with (
+ patch.object(
+ graders,
+ "check_grader_endpoint_key",
+ side_effect=LLMNotConfiguredError("no key"),
+ ),
+ patch.object(simpleqa, "DatasetRegistry") as registry,
+ ):
+ with pytest.raises(LLMNotConfiguredError):
+ simpleqa.SimpleQAEvaluator()._run_with_dataset_class(
+ system_config={}, num_examples=1, output_dir=str(tmp_path)
+ )
+ registry.create_dataset.assert_not_called()
+
+
+class TestBenchmarkFunctionsGraderKey:
+ @pytest.mark.parametrize(
+ ("fn", "runner"),
+ [
+ ("evaluate_simpleqa", "run_simpleqa_benchmark"),
+ ("evaluate_browsecomp", "run_browsecomp_benchmark"),
+ ("evaluate_xbench_deepsearch", "run_xbench_deepsearch_benchmark"),
+ ],
+ )
+ def test_evaluation_api_key_reaches_the_grader_config(self, fn, runner):
+ from local_deep_research.benchmarks import benchmark_functions
+
+ with (
+ patch.object(benchmark_functions, runner) as run,
+ patch.object(
+ benchmark_functions,
+ "get_setting_from_snapshot",
+ return_value=None,
+ ),
+ ):
+ run.return_value = {}
+ getattr(benchmark_functions, fn)(
+ num_examples=1, evaluation_api_key=GRADER_KEY
+ )
+ assert run.call_args.kwargs["evaluation_config"]["api_key"] == (
+ GRADER_KEY
+ )
+
+
+ "provider", ['"openai_endpoint"', " 'OpenAI_Endpoint' ", "OPENAI_ENDPOINT"]
+)
+def test_quoted_provider_grades_against_the_grader_endpoint(provider):
+ """get_llm strips quotes from the provider; the grader must normalise it
+ the same way, or a quoted provider skips the grader-endpoint fill and
+ get_llm grades against the built-in OpenRouter URL."""
+ grader_url = "http://localhost:11434/v1"
+ with patch.object(graders, "get_llm") as mock_get_llm:
+ mock_get_llm.return_value = MagicMock()
+ graders.get_evaluation_llm(
+ custom_config={"provider": provider},
+ settings_snapshot=_snapshot(grader_url=grader_url),
+ )
+
+ kwargs = mock_get_llm.call_args.kwargs
+ assert kwargs["openai_endpoint_url"] == grader_url
+ assert kwargs["provider"] == "openai_endpoint"
+ assert RESEARCH_KEY not in repr(
+ {k: v for k, v in kwargs.items() if k != "settings_snapshot"}
+ )
+
+
[email protected]("provider", ['""', "''", "", " ", None])
+def test_provider_that_normalises_to_nothing_uses_the_grader_endpoint(
+ provider,
+):
+ """An empty or quotes-only grader provider means the same as an unset
+ one: the openai_endpoint default at benchmark.evaluation.endpoint_url.
+ It must not keep the built-in OpenRouter URL or fall back to the
+ research provider."""
+ grader_url = "http://localhost:11434/v1"
+ with patch.object(graders, "get_llm") as mock_get_llm:
+ mock_get_llm.return_value = MagicMock()
+ graders.get_evaluation_llm(
+ custom_config={"provider": provider},
+ settings_snapshot=_snapshot(grader_url=grader_url),
+ )
+
+ kwargs = mock_get_llm.call_args.kwargs
+ assert kwargs["provider"] == "openai_endpoint"
+ assert kwargs["openai_endpoint_url"] == grader_url
diff --git a/tests/benchmarks/test_graders.py b/tests/benchmarks/test_graders.py
index fd91e2cae6..0d287bf138 100644
--- a/tests/benchmarks/test_graders.py
+++ b/tests/benchmarks/test_graders.py
@@ -169,7 +169,9 @@ class TestGetEvaluationLLM:
mock_get_llm.return_value = Mock()
settings_snapshot = {
- "llm.openai_endpoint.api_key": {"value": "test-api-key"}
+ "llm.openai_endpoint.api_key": {"value": "test-api-key"},
+ # Same origin as the default grader endpoint.
+ "llm.openai_endpoint.url": "https://openrouter.ai/api/v1",
}
get_evaluation_llm(settings_snapshot=settings_snapshot)
diff --git a/tests/benchmarks/test_graders_coverage.py b/tests/benchmarks/test_graders_coverage.py
index 1db35d3d1b..2cac4eab6b 100644
--- a/tests/benchmarks/test_graders_coverage.py
+++ b/tests/benchmarks/test_graders_coverage.py
@@ -54,7 +54,10 @@ class TestGetEvaluationLlm:
mock_get_llm.return_value = Mock()
from local_deep_research.benchmarks.graders import get_evaluation_llm
- snapshot = {"llm.openai_endpoint.api_key": {"value": "sk-test-key"}}
+ snapshot = {
+ "llm.openai_endpoint.api_key": {"value": "sk-test-key"},
+ "llm.openai_endpoint.url": "https://openrouter.ai/api/v1",
+ }
with patch(f"{MODULE}.logger") as mock_logger:
get_evaluation_llm(settings_snapshot=snapshot)
# With a valid api_key from snapshot, no "no API key found" warning
@@ -72,7 +75,10 @@ class TestGetEvaluationLlm:
mock_get_llm.return_value = Mock()
from local_deep_research.benchmarks.graders import get_evaluation_llm
- snapshot = {"llm.openai_endpoint.api_key": "sk-direct-key"}
+ snapshot = {
+ "llm.openai_endpoint.api_key": "sk-direct-key",
+ "llm.openai_endpoint.url": "https://openrouter.ai/api/v1",
+ }
with patch(f"{MODULE}.logger") as mock_logger:
get_evaluation_llm(settings_snapshot=snapshot)
no_key_warnings = [
diff --git a/tests/benchmarks/test_graders_extra_coverage.py b/tests/benchmarks/test_graders_extra_coverage.py
index a1685261a3..1b4af2e5af 100644
--- a/tests/benchmarks/test_graders_extra_coverage.py
+++ b/tests/benchmarks/test_graders_extra_coverage.py
@@ -513,7 +513,10 @@ class TestGetEvaluationLLM:
"""API key extracted from settings snapshot dict format."""
from local_deep_research.benchmarks.graders import get_evaluation_llm
- snapshot = {"llm.openai_endpoint.api_key": {"value": "sk-test-key-123"}}
+ snapshot = {
+ "llm.openai_endpoint.api_key": {"value": "sk-test-key-123"},
+ "llm.openai_endpoint.url": "https://openrouter.ai/api/v1",
+ }
with patch(f"{MODULE}.get_llm") as mock_get_llm:
mock_get_llm.return_value = MagicMock()
@@ -526,7 +529,10 @@ class TestGetEvaluationLLM:
"""API key as plain string (not dict) from snapshot."""
from local_deep_research.benchmarks.graders import get_evaluation_llm
- snapshot = {"llm.openai_endpoint.api_key": "sk-plain-key"}
+ snapshot = {
+ "llm.openai_endpoint.api_key": "sk-plain-key",
+ "llm.openai_endpoint.url": "https://openrouter.ai/api/v1",
+ }
with patch(f"{MODULE}.get_llm") as mock_get_llm:
mock_get_llm.return_value = MagicMock()
diff --git a/tests/benchmarks/test_graders_full_coverage.py b/tests/benchmarks/test_graders_full_coverage.py
index 087f98747c..bf22075d46 100644
--- a/tests/benchmarks/test_graders_full_coverage.py
+++ b/tests/benchmarks/test_graders_full_coverage.py
@@ -26,7 +26,10 @@ class TestGetEvaluationLlm:
"llm.openai_endpoint.api_key": {
"value": "sk-test-key",
"type": "string",
- }
+ },
+ # Same origin as the default grader endpoint, so the research
+ # key may be reused for grading.
+ "llm.openai_endpoint.url": "https://openrouter.ai/api/v1",
}
get_evaluation_llm(settings_snapshot=snapshot)
@@ -38,7 +41,10 @@ class TestGetEvaluationLlm:
"""Extracts API key from settings_snapshot when value is a string."""
from local_deep_research.benchmarks.graders import get_evaluation_llm
- snapshot = {"llm.openai_endpoint.api_key": "sk-direct-key"}
+ snapshot = {
+ "llm.openai_endpoint.api_key": "sk-direct-key",
+ "llm.openai_endpoint.url": "https://openrouter.ai/api/v1",
+ }
get_evaluation_llm(settings_snapshot=snapshot)
mock_get_llm.assert_called_once()
diff --git a/tests/config/test_openai_endpoint_binding.py b/tests/config/test_openai_endpoint_binding.py
new file mode 100644
index 0000000000..95e468e0d7
--- /dev/null
+++ b/tests/config/test_openai_endpoint_binding.py
@@ -0,0 +1,1025 @@
+"""The ``openai_endpoint`` key follows a URL override only on the same origin.
+
+Covers the shared binder (``config/openai_endpoint_binding.py``) through its
+real entry points: ``overlay_runtime_settings`` (the ``custom_endpoint``
+research overlay), ``create_settings_snapshot`` (the Python API's
+``settings_override=`` raw snapshot write), ``_init_search_system`` (the
+Python API), and the re-check in ``get_llm``. The langchain client class is
+patched and every URL is a loopback address, so nothing leaves the machine.
+"""
+
+from unittest.mock import MagicMock, patch
+
+import pytest
+from langchain_core.language_models.fake_chat_models import FakeListChatModel
+
+from local_deep_research.api.settings_utils import create_settings_snapshot
+from local_deep_research.config.llm_config import get_llm
+from local_deep_research.config.openai_endpoint_binding import (
+ OPENAI_ENDPOINT_KEY_OWNER_MARKER,
+ OPENAI_ENDPOINT_SAVED_URL_MARKER,
+ bind_openai_endpoint_override,
+ resolve_openai_endpoint_override_key,
+)
+from local_deep_research.llm.providers.base import OPTIONAL_API_KEY_PLACEHOLDER
+from local_deep_research.utilities.type_utils import overlay_runtime_settings
+
+OPENAI_BASE_CHAT = "local_deep_research.llm.providers.openai_base.ChatOpenAI"
+RESEARCH_KEY = "sk-research-endpoint-key"
+STORED_URL = "http://localhost:9000/v1"
+OTHER_URL = "http://localhost:8000/v1"
+SAME_ORIGIN_URL = "http://localhost:9000/other/"
+KEY = "llm.openai_endpoint.api_key"
+URL = "llm.openai_endpoint.url"
+
+
[email protected](autouse=True, scope="module")
+def _ensure_providers_registered():
+ from local_deep_research.llm.providers import discover_providers
+
+ discover_providers(force_refresh=True)
+
+
+def _envelope_snapshot(url=STORED_URL, key=RESEARCH_KEY):
+ """A snapshot shaped like SettingsManager.get_all_settings()."""
+ return {
+ "llm.supports_max_tokens": {"value": True, "ui_element": "checkbox"},
+ "llm.max_tokens": {"value": 4096, "ui_element": "number"},
+ "rate_limiting.llm_enabled": {"value": False, "ui_element": "checkbox"},
+ "search.tool": {"value": "searxng", "ui_element": "select"},
+ URL: {"value": url, "ui_element": "text"},
+ KEY: {"value": key, "ui_element": "password"},
+ }
+
+
+def _client_kwargs(snapshot, **get_llm_kwargs):
+ with patch(
+ OPENAI_BASE_CHAT, return_value=FakeListChatModel(responses=["ok"])
+ ) as mock_chat:
+ get_llm(
+ provider="openai_endpoint",
+ model_name="m",
+ settings_snapshot=snapshot,
+ **get_llm_kwargs,
+ )
+ return mock_chat.call_args.kwargs
+
+
+class TestOverlayRuntimeSettings:
+ def test_custom_endpoint_on_another_origin_clears_the_key(self):
+ snapshot = _envelope_snapshot()
+ overlay_runtime_settings(snapshot, custom_endpoint=OTHER_URL)
+
+ assert snapshot[URL]["value"] == OTHER_URL
+ # Raw "", not an envelope: an envelope read would re-apply an
+ # LDR_LLM_OPENAI_ENDPOINT_API_KEY override.
+ assert snapshot[KEY] == ""
+ assert snapshot[OPENAI_ENDPOINT_KEY_OWNER_MARKER] == (
+ "http://localhost:9000"
+ )
+
+ def test_custom_endpoint_on_the_same_origin_keeps_the_key(self):
+ snapshot = _envelope_snapshot()
+ overlay_runtime_settings(snapshot, custom_endpoint=SAME_ORIGIN_URL)
+
+ assert snapshot[URL]["value"] == SAME_ORIGIN_URL
+ assert snapshot[KEY]["value"] == RESEARCH_KEY
+
+ def test_overlay_then_get_llm_with_the_same_override_sends_no_key(self):
+ """The caller pattern: overlay first, then get_llm(openai_endpoint_url=)."""
+ snapshot = _envelope_snapshot()
+ overlay_runtime_settings(snapshot, custom_endpoint=OTHER_URL)
+
+ kwargs = _client_kwargs(snapshot, openai_endpoint_url=OTHER_URL)
+ assert kwargs["base_url"] == OTHER_URL
+ assert kwargs["api_key"] == OPTIONAL_API_KEY_PLACEHOLDER
+
+ def test_key_restored_after_overlay_does_not_follow_the_override(self):
+ """apply_environment_overrides_to_snapshot can write the stored key
+ back after the overlay; get_llm re-checks the recorded owner."""
+ snapshot = _envelope_snapshot()
+ overlay_runtime_settings(snapshot, custom_endpoint=OTHER_URL)
+ snapshot[KEY] = RESEARCH_KEY # what an env re-application does
+
+ kwargs = _client_kwargs(snapshot)
+ assert kwargs["base_url"] == OTHER_URL
+ assert kwargs["api_key"] == OPTIONAL_API_KEY_PLACEHOLDER
+
+ def test_rebinding_back_to_the_owner_origin_keeps_the_key(self):
+ snapshot = _envelope_snapshot()
+ overlay_runtime_settings(snapshot, custom_endpoint=SAME_ORIGIN_URL)
+ overlay_runtime_settings(snapshot, custom_endpoint=STORED_URL)
+
+ kwargs = _client_kwargs(snapshot, openai_endpoint_url=STORED_URL)
+ assert kwargs["api_key"] == RESEARCH_KEY
+
+
+class TestReBindingAfterACrossOriginBind:
+ def test_rebinding_back_to_the_owner_does_not_restore_the_key(self):
+ """Documented fail-closed: the cleared key is not kept anywhere in
+ the snapshot, so it cannot come back. A run that needs it again
+ starts from a fresh snapshot."""
+ snapshot = _envelope_snapshot()
+ overlay_runtime_settings(snapshot, custom_endpoint=OTHER_URL)
+ overlay_runtime_settings(snapshot, custom_endpoint=STORED_URL)
+
+ kwargs = _client_kwargs(snapshot, openai_endpoint_url=STORED_URL)
+ assert kwargs["base_url"] == STORED_URL
+ assert kwargs["api_key"] == OPTIONAL_API_KEY_PLACEHOLDER
+ assert RESEARCH_KEY not in repr(snapshot)
+
+
+class TestEnvironmentKey:
+ """LDR_LLM_OPENAI_ENDPOINT_API_KEY is applied on envelope reads."""
+
+ ENV_KEY = "sk-from-the-environment"
+
+ @pytest.fixture(autouse=True)
+ def _env_key(self, monkeypatch):
+ monkeypatch.setenv("LDR_LLM_OPENAI_ENDPOINT_API_KEY", self.ENV_KEY)
+ monkeypatch.delenv("LDR_LLM_OPENAI_ENDPOINT_URL", raising=False)
+
+ def test_env_key_reaches_the_stored_endpoint(self):
+ kwargs = _client_kwargs(_envelope_snapshot(key="db-key"))
+ assert kwargs["api_key"] == self.ENV_KEY
+
+ def test_env_key_does_not_follow_a_cross_origin_overlay(self):
+ snapshot = _envelope_snapshot(key="db-key")
+ overlay_runtime_settings(snapshot, custom_endpoint=OTHER_URL)
+
+ kwargs = _client_kwargs(snapshot, openai_endpoint_url=OTHER_URL)
+ assert kwargs["api_key"] == OPTIONAL_API_KEY_PLACEHOLDER
+
+ def test_env_key_written_back_at_dispatch_does_not_follow_the_overlay(
+ self,
+ ):
+ """research_service re-applies env overrides after the overlay."""
+ from local_deep_research.settings.manager import (
+ apply_environment_overrides_to_snapshot,
+ )
+
+ snapshot = _envelope_snapshot(key="db-key")
+ overlay_runtime_settings(snapshot, custom_endpoint=OTHER_URL)
+ dispatched = apply_environment_overrides_to_snapshot(snapshot)
+ # The binder's cleared "" sits under an owner marker; the env pass
+ # leaves it in place instead of writing the env key back.
+ assert dispatched[KEY] == ""
+
+ kwargs = _client_kwargs(dispatched, openai_endpoint_url=OTHER_URL)
+ assert kwargs["api_key"] == OPTIONAL_API_KEY_PLACEHOLDER
+
+
+class TestInitSearchSystem:
+ """The Python API overlays the URL before calling get_llm."""
+
+ def _client_kwargs(self, override):
+ from local_deep_research.api import research_functions
+
+ snapshot = _envelope_snapshot()
+ with (
+ patch(
+ OPENAI_BASE_CHAT,
+ return_value=FakeListChatModel(responses=["ok"]),
+ ) as mock_chat,
+ patch.object(research_functions, "get_search", MagicMock()),
+ patch.object(
+ research_functions, "AdvancedSearchSystem", MagicMock()
+ ),
+ ):
+ research_functions._init_search_system(
+ model_name="m",
+ provider="openai_endpoint",
+ openai_endpoint_url=override,
+ settings_snapshot=snapshot,
+ )
+ # The caller's snapshot is copied, never modified.
+ assert snapshot[KEY]["value"] == RESEARCH_KEY
+ return mock_chat.call_args.kwargs
+
+ def test_different_origin_override_does_not_receive_the_key(self):
+ kwargs = self._client_kwargs(OTHER_URL)
+ assert kwargs["base_url"] == OTHER_URL
+ assert kwargs["api_key"] == OPTIONAL_API_KEY_PLACEHOLDER
+
+ def test_same_origin_override_reuses_the_key(self):
+ kwargs = self._client_kwargs(SAME_ORIGIN_URL)
+ assert kwargs["api_key"] == RESEARCH_KEY
+
+
+class TestStoredUrlFallback:
+ def test_no_stored_url_means_the_provider_default_owns_the_key(self):
+ snapshot = {KEY: RESEARCH_KEY}
+ assert resolve_openai_endpoint_override_key(
+ "https://api.openai.com/v1", snapshot
+ ) == (RESEARCH_KEY, False)
+ assert resolve_openai_endpoint_override_key(OTHER_URL, snapshot) == (
+ "",
+ True,
+ )
+
+ def test_whitespace_stored_url_is_not_the_provider_default(self):
+ """The provider normalises " " into a host-less URL, not the default."""
+ snapshot = {URL: " ", KEY: RESEARCH_KEY}
+ assert resolve_openai_endpoint_override_key(
+ "https://api.openai.com/v1", snapshot
+ ) == ("", True)
+
+ @pytest.mark.parametrize(
+ ("owner", "expected"),
+ [
+ (
+ "https://sample:[email protected]/custom/v1?key=sample",
+ "https://gateway.example:443",
+ ),
+ ("http://[::1]:8080/custom/v1", "http://[::1]:8080"),
+ ],
+ )
+ def test_owner_metadata_keeps_only_the_origin(self, owner, expected):
+ snapshot = _envelope_snapshot(url=owner)
+ overlay_runtime_settings(snapshot, custom_endpoint=OTHER_URL)
+ assert snapshot[OPENAI_ENDPOINT_KEY_OWNER_MARKER] == expected
+
+ def test_invalid_owner_stays_unmatched_after_another_overlay(self):
+ snapshot = _envelope_snapshot(url="https://gateway.example:invalid/v1")
+ overlay_runtime_settings(snapshot, custom_endpoint=OTHER_URL)
+ assert snapshot[OPENAI_ENDPOINT_KEY_OWNER_MARKER] == ""
+ snapshot[KEY] = RESEARCH_KEY
+ overlay_runtime_settings(snapshot, custom_endpoint=OTHER_URL)
+ assert snapshot[KEY] == ""
+ assert snapshot[OPENAI_ENDPOINT_KEY_OWNER_MARKER] == ""
+
+
+class TestForgedOwnerMarker:
+ def test_a_marker_that_did_not_come_from_the_binder_is_refused(self):
+ """A marker that did not come from the binder is refused."""
+ snapshot = _envelope_snapshot()
+ snapshot[OPENAI_ENDPOINT_KEY_OWNER_MARKER] = (
+ "https://attacker.example/v1"
+ )
+ assert resolve_openai_endpoint_override_key(
+ "https://attacker.example/v1", snapshot
+ ) == ("", True)
+
+ # The binder's own canonical record is honoured by the same check.
+ snapshot[OPENAI_ENDPOINT_KEY_OWNER_MARKER] = "http://localhost:9000"
+ assert resolve_openai_endpoint_override_key(STORED_URL, snapshot) == (
+ RESEARCH_KEY,
+ False,
+ )
+
+
+class TestSnapshotlessExplicitKey:
+ def test_explicit_key_applies_without_a_snapshot(self):
+ kwargs = _client_kwargs(
+ None,
+ openai_endpoint_url=OTHER_URL,
+ openai_endpoint_api_key="sk-explicit",
+ )
+ assert kwargs["api_key"] == "sk-explicit"
+
+ def test_key_only_call_without_a_snapshot_is_still_refused(self):
+ from local_deep_research.security.egress.policy import (
+ PolicyDeniedError,
+ )
+
+ with pytest.raises(PolicyDeniedError):
+ get_llm(
+ provider="openai_endpoint",
+ model_name="m",
+ openai_endpoint_api_key="sk-explicit",
+ settings_snapshot=None,
+ )
+
+
+class TestCreateSettingsSnapshotOverride:
+ """The ``settings_override`` raw snapshot write goes through the binder.
+
+ ``quick_summary(..., settings=..., settings_override={
+ "llm.openai_endpoint.url": ...})`` and friends build their snapshot with
+ ``create_settings_snapshot``, which used to write the URL verbatim: the
+ stored key then rode along to whatever URL the override named, with no
+ owner marker and without ``get_llm``'s binding guard ever firing.
+ """
+
+ def _quick_summary_client_kwargs(self, settings, settings_override):
+ from local_deep_research.api import research_functions
+
+ with (
+ patch(
+ OPENAI_BASE_CHAT,
+ return_value=FakeListChatModel(responses=["ok"]),
+ ) as mock_chat,
+ patch.object(research_functions, "get_search", MagicMock()),
+ patch.object(
+ research_functions, "AdvancedSearchSystem", MagicMock()
+ ),
+ ):
+ research_functions.quick_summary(
+ "q",
+ model_name="m",
+ provider="openai_endpoint",
+ settings=settings,
+ settings_override=settings_override,
+ )
+ return mock_chat.call_args.kwargs
+
+ def test_a_stored_key_does_not_follow_a_snapshot_url_override(self):
+ """A stored key does not follow a snapshot url override."""
+ kwargs = self._quick_summary_client_kwargs(
+ settings=_envelope_snapshot(),
+ settings_override={URL: OTHER_URL},
+ )
+
+ assert kwargs["base_url"] == OTHER_URL
+ assert kwargs["api_key"] == OPTIONAL_API_KEY_PLACEHOLDER
+ assert RESEARCH_KEY not in repr(kwargs)
+
+ def test_a_same_origin_snapshot_override_keeps_the_key_and_binds_it(self):
+ """A same origin snapshot override keeps the key and binds it."""
+ snapshot = _envelope_snapshot()
+ snapshot = create_settings_snapshot(
+ overrides={URL: SAME_ORIGIN_URL}, base_settings=snapshot
+ )
+
+ assert snapshot[OPENAI_ENDPOINT_KEY_OWNER_MARKER] == (
+ "http://localhost:9000"
+ )
+ kwargs = _client_kwargs(snapshot)
+ assert kwargs["base_url"] == SAME_ORIGIN_URL
+ assert kwargs["api_key"] == RESEARCH_KEY
+
+ def test_the_env_override_keeps_the_key_only_while_it_is_policy(
+ self, monkeypatch
+ ):
+ """The env override keeps the key only while it is policy."""
+ env_url = "http://localhost:9100/v1"
+ monkeypatch.setenv("LDR_LLM_OPENAI_ENDPOINT_URL", env_url)
+ snapshot = create_settings_snapshot(
+ overrides={URL: OTHER_URL}, base_settings=_envelope_snapshot()
+ )
+ kwargs = _client_kwargs(snapshot)
+ assert kwargs["base_url"] == env_url
+ assert kwargs["api_key"] == RESEARCH_KEY
+
+ monkeypatch.delenv("LDR_LLM_OPENAI_ENDPOINT_URL")
+ kwargs = _client_kwargs(snapshot)
+ assert kwargs["base_url"] == OTHER_URL
+ assert kwargs["api_key"] == OPTIONAL_API_KEY_PLACEHOLDER
+
+ def test_custom_endpoint_after_a_snapshot_override_stays_withheld(self):
+ """Custom endpoint after a snapshot override stays withheld."""
+ snapshot = create_settings_snapshot(
+ overrides={URL: OTHER_URL}, base_settings=_envelope_snapshot()
+ )
+ overlay_runtime_settings(
+ snapshot, custom_endpoint="http://localhost:8000/other/"
+ )
+
+ kwargs = _client_kwargs(snapshot)
+ assert kwargs["base_url"] == "http://localhost:8000/other/"
+ assert kwargs["api_key"] == OPTIONAL_API_KEY_PLACEHOLDER
+
+ def test_a_key_named_in_the_same_call_binds_to_the_override(self):
+ """A key named in the same call binds to the override."""
+ snapshot = create_settings_snapshot(
+ overrides={URL: OTHER_URL, KEY: "sk-with-the-url"},
+ base_settings=_envelope_snapshot(),
+ )
+
+ assert snapshot[OPENAI_ENDPOINT_KEY_OWNER_MARKER] == (
+ "http://localhost:8000"
+ )
+ kwargs = _client_kwargs(snapshot)
+ assert kwargs["base_url"] == OTHER_URL
+ assert kwargs["api_key"] == "sk-with-the-url"
+ assert RESEARCH_KEY not in repr(snapshot)
+
+ def test_a_forged_owner_marker_in_overrides_is_refused(self):
+ """A forged owner marker in overrides is refused."""
+ with pytest.raises(ValueError, match="internal snapshot key"):
+ create_settings_snapshot(
+ overrides={
+ OPENAI_ENDPOINT_KEY_OWNER_MARKER: (
+ "https://attacker.example:443"
+ ),
+ URL: "https://attacker.example/v1",
+ },
+ base_settings=_envelope_snapshot(),
+ )
+ # The refusal covers every internal key, not just the known marker.
+ with pytest.raises(ValueError, match="internal snapshot key"):
+ create_settings_snapshot(
+ overrides={"_username": "attacker"},
+ base_settings=_envelope_snapshot(),
+ )
+
+ def test_a_transient_env_url_never_re_owns_the_key(self, monkeypatch):
+ """A transient env url never re owns the key."""
+ monkeypatch.setenv(
+ "LDR_LLM_OPENAI_ENDPOINT_URL", "http://localhost:9100/v1"
+ )
+ snapshot = create_settings_snapshot(
+ overrides={URL: "http://localhost:9100/anything"},
+ base_settings=_envelope_snapshot(),
+ )
+ # Operator policy while the env is set: the key is kept for the
+ # effective (env) URL.
+ kwargs = _client_kwargs(snapshot)
+ assert kwargs["api_key"] == RESEARCH_KEY
+
+ monkeypatch.delenv("LDR_LLM_OPENAI_ENDPOINT_URL")
+ # The env's former origin is foreign now: the same snapshot must
+ # not hand the key over.
+ kwargs = _client_kwargs(snapshot)
+ assert kwargs["api_key"] == OPTIONAL_API_KEY_PLACEHOLDER
+
+ # ... and a later settings_override naming that origin must not
+ # ride the key either.
+ snapshot = create_settings_snapshot(
+ overrides={URL: "http://localhost:9100/anything"},
+ base_settings=snapshot,
+ )
+ kwargs = _client_kwargs(snapshot)
+ assert kwargs["api_key"] == OPTIONAL_API_KEY_PLACEHOLDER
+ assert RESEARCH_KEY not in repr(snapshot)
+
+ def test_after_the_env_is_gone_the_key_follows_its_configured_origin(
+ self, monkeypatch
+ ):
+ """After the env is gone the key follows its configured origin."""
+ monkeypatch.setenv(
+ "LDR_LLM_OPENAI_ENDPOINT_URL", "http://localhost:9100/v1"
+ )
+ snapshot = create_settings_snapshot(
+ overrides={URL: "http://localhost:9100/anything"},
+ base_settings=_envelope_snapshot(),
+ )
+ kwargs = _client_kwargs(snapshot)
+ assert kwargs["api_key"] == RESEARCH_KEY
+
+ monkeypatch.delenv("LDR_LLM_OPENAI_ENDPOINT_URL")
+ snapshot = create_settings_snapshot(
+ overrides={URL: "http://localhost:9000/again/"},
+ base_settings=snapshot,
+ )
+ kwargs = _client_kwargs(snapshot)
+ assert kwargs["base_url"] == "http://localhost:9000/again/"
+ assert kwargs["api_key"] == RESEARCH_KEY
+
+ def test_binder_written_markers_still_bind_across_calls(self):
+ """Binder written markers still bind across calls."""
+ snapshot = create_settings_snapshot(
+ overrides={URL: SAME_ORIGIN_URL}, base_settings=_envelope_snapshot()
+ )
+ assert snapshot[OPENAI_ENDPOINT_KEY_OWNER_MARKER] == (
+ "http://localhost:9000"
+ )
+ snapshot = create_settings_snapshot(
+ overrides={URL: "http://localhost:9000/third/"},
+ base_settings=snapshot,
+ )
+ kwargs = _client_kwargs(snapshot)
+ assert kwargs["base_url"] == "http://localhost:9000/third/"
+ assert kwargs["api_key"] == RESEARCH_KEY
+
+ # The restored key must not follow a foreign override just because
+ # the base's URL entry already points at that origin.
+ snapshot = create_settings_snapshot(
+ overrides={URL: OTHER_URL}, base_settings=_envelope_snapshot()
+ )
+ snapshot[KEY] = RESEARCH_KEY # what an env write-back does
+ snapshot = create_settings_snapshot(
+ overrides={URL: "http://localhost:8000/second/"},
+ base_settings=snapshot,
+ )
+ kwargs = _client_kwargs(snapshot)
+ assert kwargs["api_key"] == OPTIONAL_API_KEY_PLACEHOLDER
+
+
+def _web_dispatch_client_kwargs(custom_endpoint):
+ """The web research flow for ``custom_endpoint``, up to the LLM client.
+
+ ``get_all_settings(include_environment_overrides=False)`` envelopes,
+ the route's ``custom_endpoint`` overlay, the dispatch-time
+ ``apply_environment_overrides_to_snapshot`` and overlay, then
+ ``get_llm(openai_endpoint_url=custom_endpoint)``.
+ """
+ from local_deep_research.settings.manager import (
+ apply_environment_overrides_to_snapshot,
+ )
+
+ snapshot = _envelope_snapshot(key="db-key")
+ overlay_runtime_settings(snapshot, custom_endpoint=custom_endpoint)
+ snapshot = apply_environment_overrides_to_snapshot(snapshot)
+ overlay_runtime_settings(snapshot, custom_endpoint=custom_endpoint)
+ return _client_kwargs(snapshot, openai_endpoint_url=custom_endpoint)
+
+
+class TestEnvironmentSuppliedKeyAtDispatch:
+ """An ``LDR_LLM_OPENAI_ENDPOINT_API_KEY`` is the operator's, not the DB's.
+
+ The web research flow captures its snapshot with
+ ``include_environment_overrides=False`` (raw DB envelopes), overlays
+ ``custom_endpoint``, re-applies the environment at dispatch
+ (``apply_environment_overrides_to_snapshot``), overlays again and then
+ calls ``get_llm(openai_endpoint_url=custom_endpoint)``. The owner the
+ first overlay records comes from the stored URL; it must never authorise
+ the env key, which follows only the env URL's origin.
+ """
+
+ ENV_KEY = "sk-operator-env-key"
+ ENV_URL = "http://localhost:9100/v1"
+
+ @pytest.fixture(autouse=True)
+ def _env(self, monkeypatch):
+ monkeypatch.setenv("LDR_LLM_OPENAI_ENDPOINT_API_KEY", self.ENV_KEY)
+ monkeypatch.setenv("LDR_LLM_OPENAI_ENDPOINT_URL", self.ENV_URL)
+
+ def test_env_key_does_not_follow_a_custom_endpoint_on_the_stored_origin(
+ self,
+ ):
+ """Env key does not follow a custom endpoint on the stored origin."""
+ kwargs = _web_dispatch_client_kwargs(SAME_ORIGIN_URL)
+ assert kwargs["base_url"] == SAME_ORIGIN_URL
+ assert kwargs["api_key"] == OPTIONAL_API_KEY_PLACEHOLDER
+ assert self.ENV_KEY not in repr(kwargs)
+
+ def test_env_key_follows_a_custom_endpoint_on_the_env_origin(self):
+ kwargs = _web_dispatch_client_kwargs("http://localhost:9100/x/")
+ assert kwargs["base_url"] == "http://localhost:9100/x/"
+ assert kwargs["api_key"] == self.ENV_KEY
+
+ def test_env_key_with_an_env_url_does_not_go_to_a_default_url(self):
+ """Env key with an env url does not go to a default url."""
+ snapshot = _envelope_snapshot(key="db-key")
+ for url in (
+ "https://openrouter.ai/api/v1",
+ "https://api.openai.com/v1",
+ ):
+ assert resolve_openai_endpoint_override_key(url, snapshot) == (
+ "",
+ True,
+ )
+
+ def test_a_call_key_survives_env_re_application(self):
+ """A call key survives env re application."""
+ from local_deep_research.config.openai_endpoint_binding import (
+ bind_openai_endpoint_override,
+ )
+ from local_deep_research.settings.manager import (
+ apply_environment_overrides_to_snapshot,
+ )
+
+ snapshot = _envelope_snapshot(key="db-key")
+ bind_openai_endpoint_override(
+ snapshot, OTHER_URL, explicit_key="sk-call-key"
+ )
+ snapshot = apply_environment_overrides_to_snapshot(snapshot)
+ assert snapshot[KEY] == "sk-call-key"
+
+ kwargs = _client_kwargs(snapshot, openai_endpoint_url=OTHER_URL)
+ assert kwargs["base_url"] == OTHER_URL
+ assert kwargs["api_key"] == "sk-call-key"
+
+ def test_the_env_key_under_a_call_marker_is_withheld(self):
+ """The env key under a call marker is withheld."""
+ from local_deep_research.config.openai_endpoint_binding import (
+ bind_openai_endpoint_override,
+ )
+
+ snapshot = _envelope_snapshot(key="db-key")
+ bind_openai_endpoint_override(
+ snapshot, OTHER_URL, explicit_key="sk-call-key"
+ )
+ snapshot[KEY] = self.ENV_KEY
+
+ kwargs = _client_kwargs(snapshot, openai_endpoint_url=OTHER_URL)
+ assert kwargs["base_url"] == OTHER_URL
+ assert kwargs["api_key"] == OPTIONAL_API_KEY_PLACEHOLDER
+
+
+class TestSameCallKeyOwner:
+ """Which origin a key named with a ``settings_override`` URL belongs to."""
+
+ @pytest.mark.parametrize("url_override", ["", None])
+ def test_an_emptied_url_override_keeps_the_same_call_key(
+ self, url_override
+ ):
+ """An emptied url override keeps the same call key."""
+ snapshot = create_settings_snapshot(
+ overrides={URL: url_override, KEY: "CALLER"}
+ )
+ assert snapshot[OPENAI_ENDPOINT_KEY_OWNER_MARKER] == (
+ "https://api.openai.com:443"
+ )
+ assert resolve_openai_endpoint_override_key(
+ "https://api.openai.com/v1", snapshot
+ ) == ("CALLER", False)
+
+ snapshot = create_settings_snapshot(
+ overrides={URL: url_override, KEY: "CALLER"},
+ base_settings=_envelope_snapshot(),
+ )
+ kwargs = _client_kwargs(snapshot)
+ assert kwargs["base_url"] == "https://api.openai.com/v1"
+ assert kwargs["api_key"] == "CALLER"
+ assert RESEARCH_KEY not in repr(snapshot)
+
+ def test_a_same_call_key_is_owned_by_its_url_not_the_env_url(
+ self, monkeypatch
+ ):
+ """A same call key is owned by its url not the env url."""
+ monkeypatch.setenv(
+ "LDR_LLM_OPENAI_ENDPOINT_URL", "http://localhost:9100/v1"
+ )
+ snapshot = create_settings_snapshot(
+ overrides={URL: OTHER_URL, KEY: "sk-with-the-url"},
+ base_settings=_envelope_snapshot(),
+ )
+ assert snapshot[OPENAI_ENDPOINT_KEY_OWNER_MARKER] == (
+ "http://localhost:8000"
+ )
+
+ monkeypatch.delenv("LDR_LLM_OPENAI_ENDPOINT_URL")
+ kwargs = _client_kwargs(snapshot)
+ assert kwargs["base_url"] == OTHER_URL
+ assert kwargs["api_key"] == "sk-with-the-url"
+
+
+class TestEnvironmentKeyWithoutAnEnvUrl:
+ """``LDR_LLM_OPENAI_ENDPOINT_API_KEY`` alone follows the saved URL only.
+
+ A plain ``get_llm()`` sends the env key to the saved
+ ``llm.openai_endpoint.url`` (``test_env_key_reaches_the_stored_endpoint``);
+ every binding path must give the same answer for that destination and
+ withhold the key from any other.
+ """
+
+ ENV_KEY = "sk-operator-env-key"
+
+ @pytest.fixture(autouse=True)
+ def _env(self, monkeypatch):
+ monkeypatch.setenv("LDR_LLM_OPENAI_ENDPOINT_API_KEY", self.ENV_KEY)
+ monkeypatch.delenv("LDR_LLM_OPENAI_ENDPOINT_URL", raising=False)
+
+ def test_web_research_on_the_saved_url_keeps_the_env_key(self):
+ """The web route always passes the saved URL as ``custom_endpoint``."""
+ kwargs = _web_dispatch_client_kwargs(STORED_URL)
+ assert kwargs["base_url"] == STORED_URL
+ assert kwargs["api_key"] == self.ENV_KEY
+
+ def test_custom_endpoint_elsewhere_withholds_the_env_key(self):
+ kwargs = _web_dispatch_client_kwargs(OTHER_URL)
+ assert kwargs["base_url"] == OTHER_URL
+ assert kwargs["api_key"] == OPTIONAL_API_KEY_PLACEHOLDER
+ assert self.ENV_KEY not in repr(kwargs)
+
+ def test_only_the_saved_origin_is_allowed(self):
+ snapshot = _envelope_snapshot(key="db-key")
+ assert resolve_openai_endpoint_override_key(
+ SAME_ORIGIN_URL, snapshot
+ ) == (self.ENV_KEY, False)
+ for url in (
+ "https://openrouter.ai/api/v1",
+ "https://api.openai.com/v1",
+ ):
+ assert resolve_openai_endpoint_override_key(url, snapshot) == (
+ "",
+ True,
+ )
+
+ def test_a_call_marker_does_not_stand_in_for_the_saved_url(self):
+ """A call marker does not stand in for the saved url."""
+ from local_deep_research.config.openai_endpoint_binding import (
+ bind_openai_endpoint_override,
+ )
+
+ snapshot = _envelope_snapshot(key="db-key")
+ bind_openai_endpoint_override(
+ snapshot, OTHER_URL, explicit_key="sk-call-key"
+ )
+ snapshot[KEY] = self.ENV_KEY
+
+ kwargs = _client_kwargs(snapshot, openai_endpoint_url=OTHER_URL)
+ assert kwargs["api_key"] == OPTIONAL_API_KEY_PLACEHOLDER
+
+ def test_an_owner_marker_without_a_saved_record_fails_closed(self):
+ """An owner marker without a saved record fails closed."""
+ snapshot = {
+ URL: "https://call.example/v1",
+ KEY: {"value": "", "ui_element": "password"},
+ OPENAI_ENDPOINT_KEY_OWNER_MARKER: "https://call.example:443",
+ }
+ assert resolve_openai_endpoint_override_key(
+ "https://call.example/v1", snapshot
+ ) == ("", True)
+
+ def test_a_non_canonical_saved_record_is_refused(self):
+ """Only the binder's ``scheme://host:port`` saved record is trusted."""
+ from local_deep_research.config.openai_endpoint_binding import (
+ OPENAI_ENDPOINT_SAVED_URL_MARKER,
+ )
+
+ snapshot = _envelope_snapshot(key="")
+ snapshot[OPENAI_ENDPOINT_KEY_OWNER_MARKER] = "http://localhost:9000"
+ snapshot[OPENAI_ENDPOINT_SAVED_URL_MARKER] = "https://call.example/v1"
+ assert resolve_openai_endpoint_override_key(
+ "https://call.example/v1", snapshot
+ ) == ("", True)
+
+ def test_an_empty_saved_url_means_the_provider_default(self):
+ """An empty saved url means the provider default."""
+ snapshot = _envelope_snapshot(url="", key="")
+ assert resolve_openai_endpoint_override_key(
+ "https://api.openai.com/v1", snapshot
+ ) == (self.ENV_KEY, False)
+ assert resolve_openai_endpoint_override_key(
+ "https://openrouter.ai/api/v1", snapshot
+ ) == ("", True)
+
+ def test_a_missing_key_entry_counts_as_the_env_key(self):
+ """A missing key entry counts as the env key."""
+ from local_deep_research.config.openai_endpoint_binding import (
+ _key_is_env_supplied,
+ )
+
+ assert _key_is_env_supplied({URL: STORED_URL}) is True
+ assert _key_is_env_supplied({URL: STORED_URL, KEY: "sk-raw"}) is False
+
+
+class TestSameCallKeyOwnerAndTheEnvironment:
+ """The same-call key's owner for an emptied or blank URL override."""
+
+ def test_an_env_key_does_not_replace_the_same_call_key(self, monkeypatch):
+ """An env key does not replace the same call key."""
+ monkeypatch.setenv("LDR_LLM_OPENAI_ENDPOINT_API_KEY", "sk-env-key")
+ monkeypatch.delenv("LDR_LLM_OPENAI_ENDPOINT_URL", raising=False)
+ snapshot = create_settings_snapshot(
+ overrides={URL: "", KEY: "CALLER"},
+ base_settings=_envelope_snapshot(),
+ )
+ assert snapshot[OPENAI_ENDPOINT_KEY_OWNER_MARKER] == (
+ "https://api.openai.com:443"
+ )
+ kwargs = _client_kwargs(snapshot)
+ assert kwargs["base_url"] == "https://api.openai.com/v1"
+ assert kwargs["api_key"] == "CALLER"
+
+ def test_an_emptied_url_under_an_env_url_is_owned_by_the_env_url(
+ self, monkeypatch
+ ):
+ """An emptied url under an env url is owned by the env url."""
+ monkeypatch.setenv(
+ "LDR_LLM_OPENAI_ENDPOINT_URL", "http://localhost:9100/v1"
+ )
+ snapshot = create_settings_snapshot(
+ overrides={URL: "", KEY: "CALLER"},
+ base_settings=_envelope_snapshot(),
+ )
+ assert snapshot[OPENAI_ENDPOINT_KEY_OWNER_MARKER] == (
+ "http://localhost:9100"
+ )
+ kwargs = _client_kwargs(snapshot)
+ assert kwargs["base_url"] == "http://localhost:9100/v1"
+ assert kwargs["api_key"] == "CALLER"
+
+ def test_a_whitespace_url_override_records_no_owner(self, monkeypatch):
+ """A blank URL the provider cannot reach owns nothing."""
+ monkeypatch.delenv("LDR_LLM_OPENAI_ENDPOINT_URL", raising=False)
+ snapshot = create_settings_snapshot(
+ overrides={URL: " ", KEY: "CALLER"},
+ base_settings=_envelope_snapshot(),
+ )
+ assert snapshot[OPENAI_ENDPOINT_KEY_OWNER_MARKER] == ""
+ assert resolve_openai_endpoint_override_key(
+ "https://api.openai.com/v1", snapshot
+ ) == ("", True)
+
+
+class TestRecordingOnTheThreadContextPath:
+ """A transient env URL is never recorded, even when the fallback is active.
+
+ With ``settings_snapshot=None`` (get_llm binds the binder on an empty
+ copy) or a snapshot without its own URL entry, the owner resolves
+ through ``get_setting_from_snapshot``'s thread-settings-context
+ fallback — the same source the key read uses. A context that applies
+ live ``LDR_*`` overrides on read (as the DB-backed settings managers
+ do) then surfaces the operator's ``LDR_LLM_OPENAI_ENDPOINT_URL``.
+ That value is fine for a live decision — ``_key_may_follow``'s env rule
+ grants exactly its origin while the variable is set and nothing after —
+ but the owner and saved-URL MARKERS are records that outlive the
+ variable, so the recording path must fail closed to "no owner" instead
+ of writing the env origin down.
+ """
+
+ ENV_URL = "http://localhost:9100/v1"
+
+ @pytest.fixture(autouse=True)
+ def _env(self, monkeypatch):
+ monkeypatch.setenv("LDR_LLM_OPENAI_ENDPOINT_URL", self.ENV_URL)
+ monkeypatch.delenv("LDR_LLM_OPENAI_ENDPOINT_API_KEY", raising=False)
+
+ def test_transient_env_url_is_never_recorded_as_owner_or_saved_url(self):
+ from local_deep_research.api.settings_utils import (
+ InMemorySettingsManager,
+ )
+ from local_deep_research.config.openai_endpoint_binding import (
+ OPENAI_ENDPOINT_SAVED_URL_MARKER,
+ _configured_openai_endpoint_url,
+ bind_openai_endpoint_override,
+ )
+ from local_deep_research.config.thread_settings import settings_context
+
+ with settings_context(InMemorySettingsManager()):
+ # The fallback is active and the context surfaces the live
+ # env URL (that is what a DB-backed context returns under an
+ # LDR_* override) ...
+ assert _configured_openai_endpoint_url({}) == self.ENV_URL
+
+ snapshot = {}
+ bind_openai_endpoint_override(snapshot, OTHER_URL)
+
+ # ... but no record names its origin.
+ env_origin = "http://localhost:9100"
+ assert snapshot[OPENAI_ENDPOINT_KEY_OWNER_MARKER] == ""
+ assert snapshot[OPENAI_ENDPOINT_SAVED_URL_MARKER] == ""
+ assert env_origin not in repr(snapshot)
+
+ def test_a_same_origin_call_key_still_binds_with_the_fallback_active(self):
+ """The fallback keeps working for values that are not the env URL.
+
+ The suppression is about the transient env value only: the
+ explicit-key branch records the URL the key was named for, and the
+ env policy still applies at decision time.
+ """
+ from local_deep_research.api.settings_utils import (
+ InMemorySettingsManager,
+ )
+ from local_deep_research.config.openai_endpoint_binding import (
+ bind_openai_endpoint_override,
+ )
+ from local_deep_research.config.thread_settings import settings_context
+
+ with settings_context(InMemorySettingsManager()):
+ snapshot = {}
+ bind_openai_endpoint_override(
+ snapshot, OTHER_URL, explicit_key="sk-with-the-url"
+ )
+
+ assert snapshot[OPENAI_ENDPOINT_KEY_OWNER_MARKER] == (
+ "http://localhost:8000"
+ )
+ assert snapshot[KEY] == "sk-with-the-url"
+
+
+class TestEmptyConfiguredUrlWithNoEnvUrl:
+ """Empty Configured Url With No Env Url."""
+
+ CONTEXT_KEY = "sk-context-key"
+ DEFAULT_URL = "https://api.openai.com/v1"
+ DEFAULT_ORIGIN = "https://api.openai.com:443"
+
+ @pytest.mark.parametrize("endpoint_url", [DEFAULT_URL, ""])
+ def test_the_provider_default_is_recorded_and_the_key_survives(
+ self, endpoint_url, monkeypatch
+ ):
+ monkeypatch.delenv("LDR_LLM_OPENAI_ENDPOINT_URL", raising=False)
+ monkeypatch.delenv("LDR_LLM_OPENAI_ENDPOINT_API_KEY", raising=False)
+ from local_deep_research.api.settings_utils import (
+ InMemorySettingsManager,
+ )
+ from local_deep_research.config.thread_settings import settings_context
+
+ manager = InMemorySettingsManager()
+ manager.set_setting("llm.openai_endpoint.url", "")
+ manager.set_setting("llm.openai_endpoint.api_key", self.CONTEXT_KEY)
+ with settings_context(manager):
+ snapshot = {}
+ bind_openai_endpoint_override(snapshot, endpoint_url)
+
+ # The empty configured URL IS the provider default, so that is
+ # what the markers must record — not "" ("no owner").
+ assert snapshot[OPENAI_ENDPOINT_KEY_OWNER_MARKER] == (
+ self.DEFAULT_ORIGIN
+ )
+ assert snapshot[OPENAI_ENDPOINT_SAVED_URL_MARKER] == (
+ self.DEFAULT_ORIGIN
+ )
+ # The key is owned by the endpoint it was configured for ...
+ assert resolve_openai_endpoint_override_key(
+ self.DEFAULT_URL, snapshot
+ ) == (self.CONTEXT_KEY, False)
+
+ # ... the re-check performed by every later bind keeps it ...
+ bind_openai_endpoint_override(snapshot, None)
+ assert snapshot.get(KEY) in (None, self.CONTEXT_KEY)
+
+ # ... and resolve keeps working at the default origin.
+ assert resolve_openai_endpoint_override_key(
+ self.DEFAULT_URL, snapshot
+ ) == (self.CONTEXT_KEY, False)
+
+
+class TestEnvValuesAreNeverRecordedAsStoredOwnership:
+ """Env Values Are Never Recorded As Stored Ownership."""
+
+ ENV_URL = "http://localhost:9100/v1"
+ ENV_ORIGIN = "http://localhost:9100"
+
+ @pytest.fixture(autouse=True)
+ def _env(self, monkeypatch):
+ monkeypatch.setenv("LDR_LLM_OPENAI_ENDPOINT_URL", self.ENV_URL)
+ monkeypatch.delenv("LDR_LLM_OPENAI_ENDPOINT_API_KEY", raising=False)
+
+ def _assert_no_env_record(self, snapshot, monkeypatch):
+ # The stored key is still there — only its ownership record is in
+ # question.
+ assert snapshot[KEY]["value"] == RESEARCH_KEY
+ # Operator policy while the variable is set is untouched ...
+ assert resolve_openai_endpoint_override_key(self.ENV_URL, snapshot) == (
+ RESEARCH_KEY,
+ False,
+ )
+ # ... but no marker may name the env origin for a stored key.
+ assert snapshot[OPENAI_ENDPOINT_KEY_OWNER_MARKER] == ""
+ assert snapshot[OPENAI_ENDPOINT_SAVED_URL_MARKER] == ""
+ assert self.ENV_ORIGIN not in repr(snapshot)
+ # Once the variable is gone, nothing recorded authorises its
+ # former origin: the stored key is withheld from it.
+ monkeypatch.delenv("LDR_LLM_OPENAI_ENDPOINT_URL")
+ assert resolve_openai_endpoint_override_key(self.ENV_URL, snapshot) == (
+ "",
+ True,
+ )
+
+ def test_a_value_an_env_pass_wrote_into_the_entry_is_not_recorded(
+ self, monkeypatch
+ ):
+ """The documented env pass writes env values into raw entries.
+
+ ``apply_environment_overrides_to_snapshot`` materialising an
+ ``LDR_*`` value into a snapshot entry is relied-on behaviour
+ elsewhere; the binder must not read that value "as stored" into
+ its ownership records.
+ """
+ from local_deep_research.settings.manager import (
+ apply_environment_overrides_to_snapshot,
+ )
+
+ base = apply_environment_overrides_to_snapshot(_envelope_snapshot())
+ assert base[URL]["value"] == self.ENV_URL
+
+ snapshot = create_settings_snapshot(
+ overrides={URL: OTHER_URL}, base_settings=base
+ )
+ self._assert_no_env_record(snapshot, monkeypatch)
+
+ def test_a_materialized_env_value_is_not_recorded(self, monkeypatch):
+ """``create_settings_snapshot`` materialises the env-applied URL
+ into a missing ``llm.openai_endpoint.url`` entry one line before
+ the binder reads it "as stored" (api/settings_utils.py).
+ """
+ from local_deep_research.api.settings_utils import (
+ InMemorySettingsManager,
+ )
+ from local_deep_research.config.thread_settings import settings_context
+
+ with settings_context(InMemorySettingsManager()):
+ snapshot = create_settings_snapshot(
+ overrides={URL: OTHER_URL},
+ base_settings={
+ KEY: {"value": RESEARCH_KEY, "ui_element": "password"}
+ },
+ )
+ self._assert_no_env_record(snapshot, monkeypatch)
+
+
+def test_bound_snapshot_keeps_its_configured_key_across_environment_changes(
+ monkeypatch,
+):
+ from local_deep_research.config.openai_endpoint_binding import (
+ bind_openai_endpoint_override,
+ )
+ from local_deep_research.settings.manager import (
+ apply_environment_overrides_to_snapshot,
+ )
+
+ monkeypatch.delenv("LDR_LLM_OPENAI_ENDPOINT_API_KEY", raising=False)
+ monkeypatch.delenv("LDR_LLM_OPENAI_ENDPOINT_URL", raising=False)
+ snapshot = _envelope_snapshot()
+ bind_openai_endpoint_override(snapshot, SAME_ORIGIN_URL, keep_envelope=True)
+ monkeypatch.setenv("LDR_LLM_OPENAI_ENDPOINT_API_KEY", "synthetic-env-key")
+ monkeypatch.setenv("LDR_LLM_OPENAI_ENDPOINT_URL", OTHER_URL)
+ dispatched = apply_environment_overrides_to_snapshot(snapshot)
+ assert resolve_openai_endpoint_override_key(OTHER_URL, dispatched) == (
+ "synthetic-env-key",
+ False,
+ )
+
+ monkeypatch.delenv("LDR_LLM_OPENAI_ENDPOINT_API_KEY")
+ monkeypatch.delenv("LDR_LLM_OPENAI_ENDPOINT_URL")
+ bind_openai_endpoint_override(dispatched, STORED_URL)
+ assert resolve_openai_endpoint_override_key(STORED_URL, dispatched) == (
+ RESEARCH_KEY,
+ False,
+ )
diff --git a/tests/config/test_openai_endpoint_key_binding.py b/tests/config/test_openai_endpoint_key_binding.py
new file mode 100644
index 0000000000..ec075afd33
--- /dev/null
+++ b/tests/config/test_openai_endpoint_key_binding.py
@@ -0,0 +1,142 @@
+"""The ``openai_endpoint`` API key stays bound to its configured origin.
+
+``get_llm(openai_endpoint_url=...)`` overlays a per-call endpoint onto the
+settings snapshot. The provider reads its key from
+``llm.openai_endpoint.api_key``, which belongs to ``llm.openai_endpoint.url``.
+These tests pin that the stored key only follows an override that resolves
+to the same origin (scheme, host, port), and that an explicit
+``openai_endpoint_api_key`` is what the client receives otherwise.
+
+Only the langchain client class is patched; settings resolution, the
+overlay, the egress gate and the provider factory run for real. Every URL is
+a loopback address, so nothing leaves the machine.
+"""
+
+import pytest
+from unittest.mock import patch
+
+from langchain_core.language_models.fake_chat_models import FakeListChatModel
+
+from local_deep_research.config.llm_config import get_llm
+from local_deep_research.llm.providers.base import OPTIONAL_API_KEY_PLACEHOLDER
+
+OPENAI_BASE_CHAT = "local_deep_research.llm.providers.openai_base.ChatOpenAI"
+
+RESEARCH_KEY = "sk-research-endpoint-key"
+GRADER_KEY = "sk-separate-grader-key"
+
+
[email protected](autouse=True, scope="module")
+def _ensure_providers_registered():
+ from local_deep_research.llm.providers import discover_providers
+
+ discover_providers(force_refresh=True)
+
+
+def _snapshot(research_url="http://localhost:9000/v1", **overrides):
+ snap = {
+ "llm.supports_max_tokens": True,
+ "llm.max_tokens": 4096,
+ "rate_limiting.llm_enabled": False,
+ "search.tool": "searxng",
+ "llm.openai_endpoint.api_key": RESEARCH_KEY,
+ }
+ if research_url is not None:
+ snap["llm.openai_endpoint.url"] = research_url
+ snap.update(overrides)
+ return snap
+
+
+def _client_kwargs(snapshot, **get_llm_kwargs):
+ with patch(
+ OPENAI_BASE_CHAT, return_value=FakeListChatModel(responses=["ok"])
+ ) as mock_chat:
+ get_llm(
+ provider="openai_endpoint",
+ model_name="judge-model",
+ settings_snapshot=snapshot,
+ **get_llm_kwargs,
+ )
+ return mock_chat.call_args.kwargs
+
+
+class TestDifferentOriginWithholdsStoredKey:
+ @pytest.mark.parametrize(
+ "override",
+ [
+ "http://localhost:8000/v1", # different port
+ "http://127.0.0.1:9000/v1", # different host text
+ "https://localhost:9000/v1", # different scheme
+ ],
+ )
+ def test_override_on_another_origin_does_not_receive_research_key(
+ self, override
+ ):
+ snapshot = _snapshot()
+ kwargs = _client_kwargs(snapshot, openai_endpoint_url=override)
+
+ assert kwargs["base_url"] == override
+ assert kwargs["api_key"] != RESEARCH_KEY
+ assert kwargs["api_key"] == OPTIONAL_API_KEY_PLACEHOLDER
+ # The caller's snapshot is left untouched.
+ assert snapshot["llm.openai_endpoint.api_key"] == RESEARCH_KEY
+
+ def test_unset_research_url_compares_against_provider_default(self):
+ """With no stored URL the key belongs to the provider default."""
+ kwargs = _client_kwargs(
+ _snapshot(research_url=None),
+ openai_endpoint_url="http://localhost:8000/v1",
+ )
+ assert kwargs["api_key"] == OPTIONAL_API_KEY_PLACEHOLDER
+
+
+class TestSameOriginReusesStoredKey:
+ @pytest.mark.parametrize(
+ ("research_url", "override"),
+ [
+ ("http://localhost:9000/v1", "http://localhost:9000/v1"),
+ # Path and trailing slash do not change the origin.
+ ("http://localhost:9000/v1", "http://localhost:9000/other/path/"),
+ # Host case does not change the origin.
+ ("http://localhost:9000/v1", "http://LocalHost:9000/v1"),
+ # An explicit default port equals the implicit one.
+ ("http://localhost/v1", "http://localhost:80/v1"),
+ ],
+ )
+ def test_same_origin_override_reuses_research_key(
+ self, research_url, override
+ ):
+ kwargs = _client_kwargs(
+ _snapshot(research_url=research_url),
+ openai_endpoint_url=override,
+ )
+ assert kwargs["api_key"] == RESEARCH_KEY
+
+
+class TestExplicitEndpointKey:
+ def test_explicit_key_is_sent_to_a_different_origin(self):
+ kwargs = _client_kwargs(
+ _snapshot(),
+ openai_endpoint_url="http://localhost:8000/v1",
+ openai_endpoint_api_key=GRADER_KEY,
+ )
+ assert kwargs["base_url"] == "http://localhost:8000/v1"
+ assert kwargs["api_key"] == GRADER_KEY
+
+ def test_explicit_key_wins_over_same_origin_research_key(self):
+ kwargs = _client_kwargs(
+ _snapshot(),
+ openai_endpoint_url="http://localhost:9000/v1",
+ openai_endpoint_api_key=GRADER_KEY,
+ )
+ assert kwargs["api_key"] == GRADER_KEY
+
+ def test_non_string_explicit_key_is_rejected(self):
+ with pytest.raises(ValueError, match="openai_endpoint_api_key"):
+ get_llm(
+ provider="openai_endpoint",
+ model_name="judge-model",
+ openai_endpoint_url="http://localhost:9000/v1",
+ openai_endpoint_api_key=123,
+ settings_snapshot=_snapshot(),
+ )
diff --git a/tests/js/pages/benchmark-grader-key-clear.test.js b/tests/js/pages/benchmark-grader-key-clear.test.js
new file mode 100644
index 0000000000..282e7b752c
--- /dev/null
+++ b/tests/js/pages/benchmark-grader-key-clear.test.js
@@ -0,0 +1,206 @@
+/**
+ * The benchmark page's "Clear" for the grader API key must remove the stored
+ * key. A PUT of {"value": ""} is answered 200 by the settings API but ignored
+ * for a password setting (an empty password field means "left untouched"),
+ * so Clear has to use DELETE and only report success when the server agrees.
+ */
+
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+
+const TEMPLATE_PATH = resolve(
+ __dirname,
+ '../../../src/local_deep_research/web/templates/pages/benchmark.html',
+);
+
+function extractFunction(source, name) {
+ const signature = new RegExp(`(?:async\\s+)?function\\s+${name}\\s*\\(`);
+ const match = signature.exec(source);
+ if (!match) throw new Error(`Function ${name} not found in template`);
+
+ const openBrace = source.indexOf('{', match.index + match[0].length);
+ let depth = 0;
+ for (let index = openBrace; index < source.length; index += 1) {
+ if (source[index] === '{') depth += 1;
+ if (source[index] === '}') {
+ depth -= 1;
+ if (depth === 0) return source.slice(match.index, index + 1);
+ }
+ }
+ throw new Error(`Function ${name} has an unterminated body`);
+}
+
+function compileControls() {
+ const template = readFileSync(TEMPLATE_PATH, 'utf8');
+ const source = [
+ 'setEvaluationApiKeySaved',
+ 'clearEvaluationApiKey',
+ 'saveEvaluationSetting',
+ 'setupEvaluationEventHandlers',
+ ].map(name => extractFunction(template, name)).join('\n');
+ // Repository-owned template code, not user input.
+ const factory = new Function( // eslint-disable-line no-new-func
+ 'csrfToken',
+ `const evaluationProviderSelect = null;
+ const evaluationModelInput = null;
+ const evaluationEndpointInput = null;
+ const evaluationTemperatureInput = null;
+ ${source}
+ return {clearEvaluationApiKey, saveEvaluationSetting,
+ setEvaluationApiKeySaved, setupEvaluationEventHandlers};`,
+ );
+ return factory('csrf-benchmark');
+}
+
+function response(status) {
+ return {
+ ok: status >= 200 && status < 300,
+ status,
+ json: vi.fn().mockResolvedValue({ message: 'ok' }),
+ };
+}
+
+function enterDraft(value) {
+ const field = document.getElementById('evaluation_api_key');
+ field.value = value;
+ field.dispatchEvent(new Event('input'));
+}
+
+describe('benchmark grader key Clear', () => {
+ let input;
+
+ beforeEach(() => {
+ document.body.innerHTML = '<input id="evaluation_api_key" type="password">';
+ input = document.getElementById('evaluation_api_key');
+ });
+
+ afterEach(() => {
+ document.body.replaceChildren();
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+ });
+
+ it('deletes the stored key instead of writing an empty value', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(response(200));
+ vi.stubGlobal('fetch', fetchMock);
+ const controls = compileControls();
+
+ await expect(controls.clearEvaluationApiKey()).resolves.toBe(true);
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ const [url, init] = fetchMock.mock.calls[0];
+ expect(url).toBe('/settings/api/benchmark.evaluation.api_key');
+ expect(init.method).toBe('DELETE');
+ expect(init.body).toBeUndefined();
+ expect(init.headers['X-CSRFToken']).toBe('csrf-benchmark');
+ expect(input.dataset.keySaved).toBe('false');
+ });
+
+ it('treats "no stored key" (404) as cleared', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(response(404)));
+ const controls = compileControls();
+
+ await expect(controls.clearEvaluationApiKey()).resolves.toBe(true);
+ expect(input.dataset.keySaved).toBe('false');
+ });
+
+ it('does not report a refused delete as cleared', async () => {
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(response(403)));
+ const controls = compileControls();
+ input.dataset.keySaved = 'true';
+
+ await expect(controls.clearEvaluationApiKey()).resolves.toBe(false);
+ expect(input.dataset.keySaved).toBe('true');
+ });
+
+ it('finishes a queued save before Clear removes the stored value', async () => {
+ let finishSave;
+ let stored = null;
+ const fetchMock = vi.fn((_url, init) => {
+ if (init.method === 'PUT') {
+ return new Promise(resolveSave => {
+ finishSave = () => {
+ stored = JSON.parse(init.body).value;
+ resolveSave(response(200));
+ };
+ });
+ }
+ stored = null;
+ return Promise.resolve(response(200));
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const controls = compileControls();
+ controls.setupEvaluationEventHandlers();
+ enterDraft('synthetic-first-value');
+ input.dispatchEvent(new Event('change'));
+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));
+
+ const clearing = controls.clearEvaluationApiKey();
+ await Promise.resolve();
+ const requestsBeforeSaveFinished = fetchMock.mock.calls.length;
+ const pendingBeforeSaveFinished = controls.saveEvaluationSetting.pending;
+ finishSave();
+ await controls.saveEvaluationSetting.queue;
+ await clearing;
+
+ expect(requestsBeforeSaveFinished).toBe(1);
+ expect(pendingBeforeSaveFinished).toBe(2);
+ expect(fetchMock.mock.calls.map(([, init]) => init.method)).toEqual(['PUT', 'DELETE']);
+ expect(stored).toBeNull();
+ expect(controls.saveEvaluationSetting.pending).toBe(0);
+ expect(input.dataset.keySaved).toBe('false');
+ });
+
+ it('keeps a newer draft when an older save completes', async () => {
+ let finishSave;
+ vi.stubGlobal('fetch', vi.fn(() => new Promise(resolveSave => {
+ finishSave = () => resolveSave(response(200));
+ })));
+ const controls = compileControls();
+ controls.setupEvaluationEventHandlers();
+ enterDraft('synthetic-first-value');
+ input.dispatchEvent(new Event('change'));
+ await vi.waitFor(() => expect(finishSave).toBeTypeOf('function'));
+
+ enterDraft('synthetic-newer-draft');
+ finishSave();
+ await controls.saveEvaluationSetting.queue;
+ await Promise.resolve();
+
+ expect(input.value).toBe('synthetic-newer-draft');
+ expect(input.dataset.keySaved).toBe('true');
+ });
+
+ it('keeps a newer draft when Clear completes', async () => {
+ let finishClear;
+ vi.stubGlobal('fetch', vi.fn(() => new Promise(resolveClear => {
+ finishClear = () => resolveClear(response(200));
+ })));
+ const controls = compileControls();
+ enterDraft('synthetic-first-value');
+ const clearing = controls.clearEvaluationApiKey();
+ await vi.waitFor(() => expect(finishClear).toBeTypeOf('function'));
+
+ enterDraft('synthetic-newer-draft');
+ finishClear();
+ await clearing;
+
+ expect(input.value).toBe('synthetic-newer-draft');
+ expect(input.dataset.keySaved).toBe('false');
+ });
+
+ it('tracks a refused Clear until a later successful mutation', async () => {
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ vi.stubGlobal('fetch', vi.fn()
+ .mockResolvedValueOnce(response(403))
+ .mockResolvedValueOnce(response(200)));
+ const controls = compileControls();
+
+ await expect(controls.clearEvaluationApiKey()).resolves.toBe(false);
+ expect(controls.saveEvaluationSetting.pending).toBe(0);
+ expect(controls.saveEvaluationSetting.failedKeys.has('benchmark.evaluation.api_key')).toBe(true);
+ await expect(controls.clearEvaluationApiKey()).resolves.toBe(true);
+ expect(controls.saveEvaluationSetting.failedKeys.size).toBe(0);
+ });
+});
diff --git a/tests/settings/golden_master_settings.json b/tests/settings/golden_master_settings.json
index f8bdbb01e4..3482a47a34 100644
--- a/tests/settings/golden_master_settings.json
+++ b/tests/settings/golden_master_settings.json
@@ -636,6 +636,20 @@
"value": 1,
"visible": true
},
+ "benchmark.evaluation.api_key": {
+ "category": "benchmark",
+ "description": "API key for the OpenAI-compatible evaluation endpoint. Leave blank to reuse the research endpoint key when its endpoint settings permit it. Local and private evaluation endpoints can run without a key; use a placeholder for other keyless endpoints.",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Evaluation Endpoint API Key",
+ "options": null,
+ "step": null,
+ "type": "APP",
+ "ui_element": "password",
+ "value": "",
+ "visible": true
+ },
"benchmark.evaluation.endpoint_url": {
"category": "benchmark",
"description": "Endpoint URL for evaluation model (when using OpenAI-compatible APIs)",
diff --git a/tests/theme_tests/test_accent_ink_contrast.py b/tests/theme_tests/test_accent_ink_contrast.py
index 7dbd76b0a8..e8abc1dd1e 100644
--- a/tests/theme_tests/test_accent_ink_contrast.py
+++ b/tests/theme_tests/test_accent_ink_contrast.py
@@ -960,14 +960,14 @@ _STATE_COLORS = (
"var(--bg-tertiary, #444)",
)
DYNAMIC_INLINE_STYLES = {
- # benchmark.html L1428 (createExpandableText): the two halves of an
- # expandable answer, one shown and one hidden.
- ("templates/pages/benchmark.html", 1430, "display"): (
+ # benchmark.html, createExpandableText: the two halves of an
+ # expandable answer, one shown and one hidden (keys carry the lines).
+ ("templates/pages/benchmark.html", 1444, "display"): (
"isExpanded ? 'none' : 'inline'",
("none", "inline"),
None,
),
- ("templates/pages/benchmark.html", 1431, "display"): (
+ ("templates/pages/benchmark.html", 1445, "display"): (
"isExpanded ? 'inline' : 'none'",
("inline", "none"),
None,
diff --git a/tests/ui_tests/test_benchmark_ci.js b/tests/ui_tests/test_benchmark_ci.js
index b97b9f6ed4..43cf278606 100644
--- a/tests/ui_tests/test_benchmark_ci.js
+++ b/tests/ui_tests/test_benchmark_ci.js
@@ -116,7 +116,7 @@ const BenchmarkDashboardTests = {
async startBenchmarkButton(page, baseUrl) {
// The real start control is #start-benchmark-btn: a submit button inside
- // form#benchmark-form labelled "Start Benchmark" (benchmark.html:296). The
+ // form#benchmark-form labelled "Start Benchmark" (benchmark.html). The
// old test fuzzy-matched any button whose text contained start/run/begin.
await navigateTo(page, `${baseUrl}/benchmark/`);
await page.waitForSelector('#start-benchmark-btn', { timeout: 15000 });
diff --git a/tests/utilities/test_endpoint_origin.py b/tests/utilities/test_endpoint_origin.py
new file mode 100644
index 0000000000..fb31d0941c
--- /dev/null
+++ b/tests/utilities/test_endpoint_origin.py
@@ -0,0 +1,74 @@
+"""Origin comparison used to bind an endpoint API key to its endpoint."""
+
+import pytest
+
+from local_deep_research.utilities.url_utils import (
+ endpoint_origin,
+ same_endpoint_origin,
+)
+
+
+class TestEndpointOrigin:
+ def test_default_https_port_is_filled_in(self):
+ assert endpoint_origin("https://openrouter.ai/api/v1") == (
+ "https",
+ "openrouter.ai",
+ 443,
+ )
+
+ def test_scheme_less_url_is_normalized_like_the_provider(self):
+ # normalize_url picks http for private hosts.
+ assert endpoint_origin("localhost:8000") == ("http", "localhost", 8000)
+
+ @pytest.mark.parametrize("value", [None, "", " ", 123])
+ def test_unparseable_values_have_no_origin(self, value):
+ assert endpoint_origin(value) is None
+
+
+class TestSameEndpointOrigin:
+ @pytest.mark.parametrize(
+ ("a", "b"),
+ [
+ # case
+ ("https://OpenRouter.AI/api/v1", "https://openrouter.ai/api/v1"),
+ # default ports
+ (
+ "https://openrouter.ai:443/api/v1",
+ "https://openrouter.ai/api/v1",
+ ),
+ ("http://gateway.internal:80/v1", "http://gateway.internal/v1"),
+ # trailing slash and path
+ ("https://openrouter.ai/api/v1/", "https://openrouter.ai"),
+ ("https://openrouter.ai/other", "https://openrouter.ai/api/v1"),
+ # trailing dot on the host
+ ("https://openrouter.ai./api/v1", "https://openrouter.ai/api/v1"),
+ ],
+ )
+ def test_equivalent_urls_share_an_origin(self, a, b):
+ assert same_endpoint_origin(a, b)
+ assert same_endpoint_origin(b, a)
+
+ @pytest.mark.parametrize(
+ ("a", "b"),
+ [
+ ("https://gateway.corp.example/v1", "https://openrouter.ai/api/v1"),
+ ("http://openrouter.ai/api/v1", "https://openrouter.ai/api/v1"),
+ (
+ "https://openrouter.ai:8443/api/v1",
+ "https://openrouter.ai/api/v1",
+ ),
+ ("https://api.openrouter.ai/v1", "https://openrouter.ai/api/v1"),
+ # userinfo cannot smuggle a different host past the comparison
+ (
+ "https://[email protected]/api/v1",
+ "https://openrouter.ai/api/v1",
+ ),
+ ],
+ )
+ def test_different_origins_do_not_match(self, a, b):
+ assert not same_endpoint_origin(a, b)
+ assert not same_endpoint_origin(b, a)
+
+ def test_two_unparseable_urls_never_match(self):
+ assert not same_endpoint_origin(None, None)
+ assert not same_endpoint_origin("", "")
diff --git a/tests/web/routers/test_api_v1_real_call_path.py b/tests/web/routers/test_api_v1_real_call_path.py
index c5da5fb896..b75f8824d3 100644
--- a/tests/web/routers/test_api_v1_real_call_path.py
+++ b/tests/web/routers/test_api_v1_real_call_path.py
@@ -49,11 +49,18 @@ ANALYZE_DOCUMENTS_PATH = "/api/v1/analyze_documents"
HEALTH_PATH = "/api/v1/health"
DOCS_PATH = "/api/v1/"
-# Planted in the user's own encrypted settings DB. Its presence in the
-# snapshot that reaches the layer below proves the snapshot is THIS user's,
-# not an empty dict or the JSON defaults.
-TRACER_KEY = "app.enable_api"
-TRACER_MARKER = "_ldr_call_path_tracer"
+# Planted in the user's own encrypted settings DB with a value unique to that
+# user. Finding that value in the snapshot that reaches the layer below
+# proves the snapshot is THIS user's, with their stored value unchanged —
+# not an empty dict, the JSON defaults or another user's settings.
+#
+# Not underscore-prefixed on purpose: names starting with "_" are reserved
+# for run metadata written by the code that owns it (such as the
+# openai_endpoint key-owner marker), and SettingsManager.get_all_settings
+# skips settings rows with such names. RESERVED_ROW_KEY is planted the same
+# way and must NOT arrive.
+TRACER_KEY = "test.ldr_call_path_tracer"
+RESERVED_ROW_KEY = "_ldr_call_path_tracer"
QUERY = "What is quantum computing?"
COLLECTION = "physics_papers"
@@ -154,20 +161,19 @@ def _api_user(live_app):
def _plant_tracer(username):
- """Write a uniquely-valued setting into the user's encrypted DB.
-
- ``app.enable_api`` is used because ``require_api_access`` already reads
- it, so it is guaranteed to be in the snapshot; the marker value is what
- identifies the snapshot as this user's.
- """
+ """Store ``TRACER_KEY`` and ``RESERVED_ROW_KEY`` in the user's encrypted
+ DB, both with a value unique to ``username``; return that value."""
from local_deep_research.database.session_context import get_user_db_session
from local_deep_research.settings import SettingsManager
+ tracer_value = f"tracer-{username}"
with get_user_db_session(username, password=ACCOUNT_PASSWORD) as db_session:
manager = SettingsManager(db_session)
- assert manager.set_setting(TRACER_MARKER, "tracer-value"), (
- f"could not seed {TRACER_MARKER} for {username}"
- )
+ for key in (TRACER_KEY, RESERVED_ROW_KEY):
+ assert manager.set_setting(key, tracer_value), (
+ f"could not seed {key} for {username}"
+ )
+ return tracer_value
def _post(client, path, body):
@@ -421,9 +427,18 @@ class TestGenerateReportRealCallPath:
"""``_init_search_system``'s ``get_llm(settings_snapshot=...)`` call
is what raised in #4396. A revert of the user-context injection in
``api_generate_report`` fails loudly here rather than passing as a
- green mock test."""
+ green mock test.
+
+ The tracer was once named ``_ldr_call_path_tracer``. When
+ ``get_all_settings`` started skipping ``_``-named settings rows
+ (that namespace is run metadata, so a stored row must not be able
+ to pose as it), that tracer stopped reaching any snapshot even
+ though the caller's own snapshot still arrived. The tracer is now an
+ ordinary key whose per-user value has to arrive unchanged. The
+ ``_``-named row is still planted, and must stay out of the
+ snapshot."""
client, username = _api_user(live_app)
- _plant_tracer(username)
+ tracer_value = _plant_tracer(username)
response, init_kwargs, _report = _post_generate_report(client)
@@ -437,9 +452,15 @@ class TestGenerateReportRealCallPath:
"_init_search_system received no settings_snapshot — this is "
"exactly the #4396 regression."
)
- assert TRACER_MARKER in snapshot, (
+ assert snapshot.get(TRACER_KEY) == tracer_value, (
"the snapshot reaching _init_search_system is not the caller's "
- f"own: {sorted(snapshot)[:10]}"
+ f"own: {TRACER_KEY}={snapshot.get(TRACER_KEY)!r}, "
+ f"first keys {sorted(snapshot)[:10]}"
+ )
+ assert RESERVED_ROW_KEY not in snapshot, (
+ f"the stored row {RESERVED_ROW_KEY!r} reached _init_search_system;"
+ " '_'-named keys are run metadata and never come from settings "
+ "rows"
)
def test_username_reaches_init_search_system(self, live_app):
diff --git a/tests/web/routers/test_benchmark_grader_key_precheck.py b/tests/web/routers/test_benchmark_grader_key_precheck.py
new file mode 100644
index 0000000000..a6be29c9a2
--- /dev/null
+++ b/tests/web/routers/test_benchmark_grader_key_precheck.py
@@ -0,0 +1,153 @@
+"""``/benchmark/api/start`` and ``/start-simple`` refuse a grader with no key.
+
+Grading errors are recorded per example, so without the pre-check a
+benchmark whose grader endpoint has no matching key would run every
+example's research and then fail to grade each one. The routes resolve the
+grader key up front (same code as the grader) and return a 400 with a fixed
+message instead.
+"""
+
+from unittest.mock import patch
+
+import pytest
+
+from local_deep_research.benchmarks.graders import GRADER_KEY_ERROR_MESSAGE
+from tests.web.routers.test_benchmark_routes_coverage_port import (
+ _clear_overrides, # noqa: F401 (autouse fixture)
+ _client,
+ _csrf,
+ _make_app,
+ _patch_auth_and_db,
+)
+
+RESEARCH_KEY = "sk-research-gateway-key"
+
+
+def _all_settings(grader_key=None):
+ snapshot = {
+ "llm.openai_endpoint.url": {
+ "value": "https://llm-gateway.corp.example/v1",
+ "ui_element": "text",
+ },
+ "llm.openai_endpoint.api_key": {
+ "value": RESEARCH_KEY,
+ "ui_element": "password",
+ },
+ "benchmark.evaluation.provider": {
+ "value": "openai_endpoint",
+ "ui_element": "select",
+ },
+ "benchmark.evaluation.endpoint_url": {
+ "value": "https://openrouter.ai/api/v1",
+ "ui_element": "text",
+ },
+ }
+ if grader_key is not None:
+ snapshot["benchmark.evaluation.api_key"] = {
+ "value": grader_key,
+ "ui_element": "password",
+ }
+ return snapshot
+
+
+def _post(path, all_settings, extra_body=None):
+ app = _make_app()
+ with _patch_auth_and_db() as (mock_svc, mgr, _db):
+ mgr.get_all_settings.return_value = all_settings
+ with patch(
+ "local_deep_research.database.session_passwords.session_password_store"
+ ) as mock_pw:
+ mock_pw.get_session_password.return_value = "pw123"
+ mock_svc.create_benchmark_run.return_value = 42
+ mock_svc.start_benchmark.return_value = True
+ client = _client(app, isolate_rate_limit=True)
+ resp = client.post(
+ path,
+ json={
+ "run_name": "r",
+ "datasets_config": {"simpleqa": {"count": 1}},
+ **(extra_body or {}),
+ },
+ headers=_csrf(client),
+ )
+ return resp, mock_svc
+
+
+ "path", ("/benchmark/api/start", "/benchmark/api/start-simple")
+)
+def test_grader_without_a_matching_key_is_refused_before_the_run(path):
+ resp, mock_svc = _post(path, _all_settings())
+
+ assert resp.status_code == 400, resp.text
+ assert resp.json()["error"] == GRADER_KEY_ERROR_MESSAGE
+ assert RESEARCH_KEY not in resp.text
+ mock_svc.create_benchmark_run.assert_not_called()
+ mock_svc.start_benchmark.assert_not_called()
+
+
+ "path", ("/benchmark/api/start", "/benchmark/api/start-simple")
+)
+def test_grader_with_its_own_key_starts(path):
+ resp, mock_svc = _post(path, _all_settings(grader_key="sk-grader"))
+
+ assert resp.status_code == 200, resp.text
+ mock_svc.create_benchmark_run.assert_called_once()
+
+
+PROVIDER_ONLY = {"evaluation_config": {"provider": "openai_endpoint"}}
+
+
+def test_provider_only_request_config_is_checked_against_the_grader_endpoint():
+ """A request-supplied evaluation_config cannot carry a URL; the grader
+ uses benchmark.evaluation.endpoint_url, and the pre-check covers it."""
+ resp, mock_svc = _post(
+ "/benchmark/api/start", _all_settings(), PROVIDER_ONLY
+ )
+
+ assert resp.status_code == 400, resp.text
+ assert resp.json()["error"] == GRADER_KEY_ERROR_MESSAGE
+ mock_svc.create_benchmark_run.assert_not_called()
+
+
+def test_provider_only_request_config_with_a_grader_key_starts():
+ resp, mock_svc = _post(
+ "/benchmark/api/start",
+ _all_settings(grader_key="sk-grader"),
+ PROVIDER_ONLY,
+ )
+
+ assert resp.status_code == 200, resp.text
+ assert mock_svc.create_benchmark_run.call_args.kwargs[
+ "evaluation_config"
+ ] == {"provider": "openai_endpoint"}
+
+
+ "provider", ["", " ", '""', "''", '"OpenAI_Endpoint"']
+)
+def test_request_provider_uses_the_grader_default(provider):
+ resp, mock_svc = _post(
+ "/benchmark/api/start",
+ _all_settings(),
+ {"evaluation_config": {"provider": provider}},
+ )
+ assert resp.status_code == 400
+ assert resp.json()["error"] == GRADER_KEY_ERROR_MESSAGE
+ mock_svc.create_benchmark_run.assert_not_called()
+
+
+ "provider", ["", " ", '""', "''", '"OpenAI_Endpoint"']
+)
+def test_request_provider_is_saved_in_canonical_form(provider):
+ resp, mock_svc = _post(
+ "/benchmark/api/start",
+ _all_settings(grader_key="synthetic-grader-key"),
+ {"evaluation_config": {"provider": provider}},
+ )
+ assert resp.status_code == 200
+ assert mock_svc.create_benchmark_run.call_args.kwargs[
+ "evaluation_config"
+ ] == {"provider": "openai_endpoint"}
diff --git a/tests/web/routers/test_benchmark_routes_coverage_port.py b/tests/web/routers/test_benchmark_routes_coverage_port.py
index 512875afcd..5585fb068e 100644
--- a/tests/web/routers/test_benchmark_routes_coverage_port.py
+++ b/tests/web/routers/test_benchmark_routes_coverage_port.py
@@ -610,7 +610,7 @@ class TestStartBenchmark:
search_config["openai_endpoint_url"]
== "http://localhost:8080"
)
- assert search_config["openai_endpoint_api_key"] == "sk-test"
+ assert "openai_endpoint_api_key" not in search_config
def test_start_success_openai_provider(self):
app = _make_app()
diff --git a/tests/web/services/test_research_service_endpoint_key_binding.py b/tests/web/services/test_research_service_endpoint_key_binding.py
new file mode 100644
index 0000000000..2fa444ff14
--- /dev/null
+++ b/tests/web/services/test_research_service_endpoint_key_binding.py
@@ -0,0 +1,86 @@
+"""The research worker's ``custom_endpoint`` does not carry the stored key away.
+
+``run_research_process`` overlays ``custom_endpoint`` onto the run's
+snapshot (``overlay_runtime_settings``) and then calls
+``get_llm(openai_endpoint_url=custom_endpoint, settings_snapshot=<that
+snapshot>)``. The stored ``llm.openai_endpoint.api_key`` must be cleared in
+that snapshot when ``custom_endpoint`` is on a different origin, and kept on
+the same origin.
+
+Network: ``get_llm`` and ``AdvancedSearchSystem`` are mocked, so nothing is
+contacted.
+"""
+
+from contextlib import ExitStack
+from unittest.mock import MagicMock, patch
+
+from local_deep_research.web.services import research_service
+from tests.web.services.helpers import (
+ MODULE,
+ _base_run_patches,
+ _egress_and_search_patches,
+ _get_raw_run_research_process,
+)
+
+RESEARCH_KEY = "sk-research-gateway-key"
+STORED_URL = "https://llm-gateway.corp.example/v1"
+
+
+def _snapshot_given_to_get_llm(custom_endpoint):
+ system = MagicMock()
+ system.analyze_topic.side_effect = RuntimeError("stop after get_llm")
+ get_llm = MagicMock(return_value=MagicMock())
+
+ patches = _base_run_patches()
+ assert MODULE == research_service.__name__
+ patches[f"{MODULE}.get_llm"] = get_llm
+ patches[f"{MODULE}.AdvancedSearchSystem"] = MagicMock(return_value=system)
+
+ snapshot = {
+ "llm.provider": {"value": "openai_endpoint", "ui_element": "select"},
+ "llm.model": {"value": "m", "ui_element": "text"},
+ "search.tool": {"value": "searxng", "ui_element": "select"},
+ "llm.openai_endpoint.url": {"value": STORED_URL, "ui_element": "text"},
+ "llm.openai_endpoint.api_key": {
+ "value": RESEARCH_KEY,
+ "ui_element": "password",
+ },
+ }
+ with ExitStack() as stack:
+ for cm in _egress_and_search_patches():
+ stack.enter_context(cm)
+ for target, mock_obj in patches.items():
+ stack.enter_context(patch(target, mock_obj))
+ _get_raw_run_research_process()(
+ 1,
+ "test query",
+ "quick",
+ username="user1",
+ settings_snapshot=snapshot,
+ search_engine="searxng",
+ model_provider="openai_endpoint",
+ model="m",
+ custom_endpoint=custom_endpoint,
+ )
+
+ assert get_llm.called, "the worker never built its LLM"
+ kwargs = get_llm.call_args.kwargs
+ assert kwargs["openai_endpoint_url"] == custom_endpoint
+ return kwargs["settings_snapshot"]
+
+
+def _key(snapshot):
+ raw = snapshot["llm.openai_endpoint.api_key"]
+ return raw["value"] if isinstance(raw, dict) else raw
+
+
+def test_custom_endpoint_on_another_origin_clears_the_stored_key():
+ snapshot = _snapshot_given_to_get_llm("https://elsewhere.example/v1")
+ assert _key(snapshot) == ""
+
+
+def test_custom_endpoint_on_the_same_origin_keeps_the_stored_key():
+ snapshot = _snapshot_given_to_get_llm(
+ "https://LLM-Gateway.corp.example/v1/"
+ )
+ assert _key(snapshot) == RESEARCH_KEY