~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(api): reject retrievers/llms params on public REST research endpoints (#5533)
LearningCircuit97ac69959bab
diff --git a/changelog.d/+api-reject-registry-params.bugfix.md b/changelog.d/+api-reject-registry-params.bugfix.mdnew file mode 100644index 0000000000..5116ccd8dd--- /dev/null+++ b/changelog.d/+api-reject-registry-params.bugfix.md@@ -0,0 +1 @@+The public REST endpoints `/api/v1/quick_summary` and `/api/v1/generate_report` now reject the `retrievers` and `llms` request-body parameters with HTTP 400 instead of forwarding them. A JSON body cannot carry a live retriever or LLM object, so any value supplied on those keys was necessarily the wrong type: it either surfaced as an opaque 500 or lodged a broken entry in the caller's own registry namespace, breaking that user's later requests for the lifetime of the worker process. Registry entries are already scoped per user (#5539), so no other user was ever affected. The in-process Python API is unaffected and still accepts real `retrievers=`/`llms=` objects.diff --git a/src/local_deep_research/web/routers/api_v1.py b/src/local_deep_research/web/routers/api_v1.pyindex 9269b8d275..55ce7f5b6f 100644--- a/src/local_deep_research/web/routers/api_v1.py+++ b/src/local_deep_research/web/routers/api_v1.py@@ -81,11 +81,388 @@ def _scrub_error_fields(results: Dict[str, Any]) -> None:# an opaque 500. Validating up front turns that into a clear 400.# username/settings_snapshot are excluded because they are server-set by# _load_user_context_into_params (and overwritten if a body supplied-# them); programmatic_mode stays accepted as the documented body-# override.-_ANALYZE_DOCUMENTS_PARAMS = frozenset(- inspect.signature(analyze_documents).parameters-) - {"query", "collection_name", "username", "settings_snapshot"}+# them).+#+# ``programmatic_mode`` is ALSO subtracted here, even though it is a+# genuine declared parameter of analyze_documents (unlike+# username/settings_snapshot it would otherwise survive the allowlist+# derivation untouched). It is the same identity/audit-plumbing knob+# documented at length on ``_IDENTITY_PLUMBING_PARAMS`` below for+# quick_summary/generate_report: ``_load_user_context_into_params`` sets+# ``params.setdefault("programmatic_mode", False)`` specifically so+# authenticated REST calls default to DB-backed metrics/rate-limit+# persistence, and ``setdefault`` means an explicit body value is+# respected rather than overridden — so leaving it in this+# signature-derived allowlist would let a caller opt their own+# analyze_documents calls out of the audit trail and DB-backed+# rate-limit accounting, the identical gap closed for quick_summary/+# generate_report via ``_REJECTED_BODY_PARAMS``. Rejecting it here (via+# subtraction, since analyze_documents' allowlist is derive-then-permit+# rather than the reject-list ``_reject_unsafe_body_params`` uses) closes+# it on this third endpoint too.+#+# ``research_id``/``research_context`` are not declared parameters of+# analyze_documents at all (checked against the signature below), so+# there is nothing else in ``_IDENTITY_PLUMBING_PARAMS`` to subtract+# here today — but any future analyze_documents parameter matching one of+# those names should be audited the same way before being allowed+# through.+_ANALYZE_DOCUMENTS_PARAMS = (+ frozenset(inspect.signature(analyze_documents).parameters)+ - {"query", "collection_name", "username", "settings_snapshot"}+ - {+ "research_id",+ "programmatic_mode",+ "research_context",+ }+)+++# Request-body keys that quick_summary/generate_report accept as declared+# Python parameters but must NEVER be forwarded from the HTTP path.+# ``retrievers``/``llms`` are registered into the retriever registry+# (web_search_engines/retriever_registry.py) and the LLM registry+# (llm/llm_registry.py) the moment they reach the research function.+#+# This is NOT a cross-user problem. Both registries are namespaced per user+# (#5539), and the ``username`` used at those registration sites is+# server-set from the authenticated session (``require_api_access`` /+# ``_load_user_context_into_params`` below) — never read from the request+# body. A value posted here can therefore only land in the poster's OWN+# namespace, and reads resolve own-namespace-first without ever surfacing+# another user's entries.+#+# What rejecting these keys prevents is a self-inflicted type confusion. A+# JSON body can only carry scalars, never a live BaseRetriever /+# BaseChatModel, so every value that can arrive here is the wrong type: a+# string registers successfully and then fails later, when something tries+# to use it as a retriever; a dict raises ValueError out of+# register_multiple, which the endpoint's catch-all turns into an opaque+# 500. Either way the bad entry persists in that user's namespace for the+# process lifetime, so the user's own later requests keep tripping over it.+# A 400 naming the offending key is the honest answer.+#+# It is also a regression guard: if the per-user namespacing were ever+# removed or bypassed, unvalidated body values would again reach a shared+# registry. Filtering at the HTTP boundary keeps that regression+# unreachable from the public API, and costs nothing, because no legitimate+# caller can express these objects in JSON to begin with.+#+# These must be rejected EXPLICITLY, not via the _ANALYZE_DOCUMENTS_PARAMS+# signature-derived-allowlist pattern: that pattern works there only+# because analyze_documents has no ``retrievers``/``llms`` parameter;+# reusing that derivation here would ADMIT them, since they ARE declared+# parameters of quick_summary/generate_report.+#+# Only the HTTP body path is filtered: in-process Python-SDK / internal+# callers still pass ``retrievers=``/``llms=`` directly (with real objects)+# and are unaffected.+_REGISTRY_PARAMS = frozenset({"retrievers", "llms"})+++# ``progress_callback`` is Callable-typed on ``generate_report``'s own+# signature, and reaches ``_init_search_system`` from ``quick_summary`` too+# via its **kwargs pass-through — quick_summary never declares the+# parameter itself, but nothing strips it before it lands in+# ``_init_search_system(progress_callback=...)``. A JSON body can only carry+# scalars/dicts/lists/null, never a live callable, so this is the same+# "wrong type reaches a registry" shape as retrievers/llms above, except it+# fails even more quietly: the value is simply assigned to+# ``system.progress_callback`` (search_system.py:set_progress_callback) and+# only blows up with "... object is not callable" deep inside the strategy+# loop, mid-research — the exact opaque 500 this module exists to prevent.+_CALLABLE_PARAMS = frozenset({"progress_callback"})+++# ``openai_endpoint_url`` is declared on ``_init_search_system`` (not on+# quick_summary/generate_report themselves — it reaches them via their+# **kwargs pass-through, same route as progress_callback above) and is+# forwarded UNCONDITIONALLY: ``_init_search_system`` passes it straight to+# ``get_llm(openai_endpoint_url=...)`` with no gate. This is NOT in the same+# bucket as ``provider``/``temperature``/``max_search_results`` below —+# those three are dead because they are only read inside quick_summary's/+# generate_report's own ``if "settings_snapshot" not in kwargs:`` branch,+# which the REST path always skips (``_load_user_context_into_params``+# unconditionally sets ``params["settings_snapshot"]`` before the research+# function runs). ``openai_endpoint_url`` never passes through that branch+# at all, so it is live on every REST call.+#+# Traced effect (config/llm_config.py ``get_llm``, ~lines 120-132): when the+# resolved ``provider == "openai_endpoint"``, a non-null+# ``openai_endpoint_url`` OVERLAYS ``settings_snapshot["llm.openai_endpoint.+# url"]`` for that call — the exact settings key the user's stored+# ``llm.openai_endpoint`` provider (URL *and* its API key) is read from. A+# caller whose stored ``llm.provider`` is ``openai_endpoint`` can therefore+# redirect that run's prompts, and the account's already-configured+# endpoint API key, to ANY host of the caller's choosing, gated only by the+# egress-policy PEP (which treats ``openai_endpoint`` as non-local and does+# not pin it to the stored URL). This is real credential/endpoint steering,+# not a self-inflicted type-confusion footgun like the classes above — it+# must be rejected outright, not merely documented as a no-op.+_CREDENTIAL_STEERING_PARAMS = frozenset({"openai_endpoint_url"})+++# ``research_id``, ``programmatic_mode``, and ``research_context`` are+# identity/audit plumbing that the REST path already manages itself;+# accepting a caller-supplied value only reopens control the server+# deliberately took away.+#+# - ``research_id``: a declared parameter of ``quick_summary`` (reached via+# plain kwargs on ``generate_report``, which never declares it). When+# absent, quick_summary generates a fresh UUID and returns it in the+# response body for correlation — a caller never needs to supply one on+# this path. Worse, the two research functions disagree on what a+# caller-supplied value affects: quick_summary threads it into BOTH+# ``search_context["research_id"]`` (what search_tracker.py's SearchCall+# rows key on) AND ``_init_search_system(research_id=...)`` (what+# token_counter.py's TokenUsage rows key on), but generate_report always+# mints its own fresh UUID for ``search_context`` while still forwarding+# any caller-supplied ``research_id`` from kwargs to ``_init_search_system``+# alone. A caller-controlled value on generate_report therefore+# split-brains the two metrics tables for that run — SearchCall rows land+# under the server ID, TokenUsage rows land under the caller's ID — with+# no way for the caller to know that in advance. Per-user DB isolation+# (#5539) keeps this inside the poster's own account, but it is a+# needless, caller-invisible way to corrupt one's own metrics history for+# zero REST-path benefit.+# - ``programmatic_mode``: not declared on quick_summary/generate_report at+# all (kwargs-only, reaching ``_init_search_system`` and then+# ``AdvancedSearchSystem``). ``_load_user_context_into_params`` below+# uses ``setdefault("programmatic_mode", False)`` specifically so+# authenticated REST calls default to DB-backed persistence — its own+# docstring notes an explicit body override is "respected", which is+# exactly the gap closed here. ``AdvancedSearchSystem.__init__`` logs+# "Running in programmatic mode - database operations and metrics+# tracking disabled. Rate limiting, search metrics, and persistence+# features will not be available." when true (search_system.py). A+# caller who sets this on the REST path can make their own calls opt out+# of the audit trail and DB-backed rate-limit accounting the authenticated+# path exists to provide — the request still counts against the slowapi+# per-route limiter, but leaves nothing else behind. The REST path should+# be the one deciding this, not the request body.+# - ``research_context``: a declared parameter of ``_init_search_system``+# forwarded via **kwargs from both quick_summary and generate_report.+# quick_summary is safe: it unconditionally overwrites+# ``init_kwargs["research_context"] = search_context`` (its own+# server-built metrics dict) right before calling+# ``_init_search_system``, so a caller-supplied value in the body is+# always clobbered. generate_report has no equivalent overwrite — it+# forwards ``**kwargs`` straight into ``_init_search_system``, so a+# caller-supplied ``research_context`` reaches+# ``get_llm(research_context=...)`` (config/llm_config.py) untouched.+# That is a caller-controlled value of unconstrained JSON type reaching+# code that both mutates it (``research_context["context_limit"] = ...``)+# — a non-dict, e.g. a string or int, raises TypeError there and+# surfaces as an opaque 500 — and, if it is a dict, hands it to+# ``TokenCounter`` (metrics/token_counter.py), which reads+# ``username``/``user_password``/``research_query``/``research_mode``+# etc. straight out of it for the metrics rows it writes. A caller can+# therefore inject arbitrary metadata (including a password-shaped+# value) into their own metrics history, or 500 the request outright,+# from a key the REST path never needed exposed. Same shape as+# ``research_id``/``programmatic_mode`` above: server-managed identity+# plumbing, not a lever the request body should control.+# - ``research_mode`` is read straight out of ``**kwargs`` by+# quick_summary (``kwargs.get("research_mode", "quick")``) and written+# into the metrics ``search_context`` as the row's mode label, while+# generate_report hardcodes its own value — so a body-supplied value+# only mislabels the caller's metrics history. Server-managed, same+# tier.+_IDENTITY_PLUMBING_PARAMS = frozenset(+ {"research_id", "programmatic_mode", "research_context", "research_mode"}+)+++# Declared parameters of quick_summary/generate_report (or bare **kwargs+# keys they read) that have NO effect when posted over the public REST+# path, so accepting them only invites confusion or, if the invariant below+# is ever weakened, reopens the exact settings-injection class already+# excluded for username/settings_snapshot elsewhere in this module:+#+# - ``settings``/``settings_override``/``api_key``/``provider``/+# ``max_search_results`` are only ever consumed inside+# quick_summary's/generate_report's own+# ``if "settings_snapshot" not in kwargs:`` branch, to build a snapshot+# from scratch. On the REST path that branch is always skipped, because+# ``_load_user_context_into_params`` below unconditionally overwrites+# ``params["settings_snapshot"]`` with the caller's own server-loaded+# snapshot BEFORE the research function ever runs — so these five are+# dead weight in the request body, not levers a caller can pull.+#+# ``max_search_results`` cannot be rescued by threading it into the+# settings snapshot instead (the way ``search_tool`` already works):+# ``get_search`` has its own ``max_results: int = 10`` default, always+# forwarded by ``_init_search_system``, so a snapshot key would be+# silently shadowed by it — a pre-existing bug in the internal API+# shared by the programmatic SDK, the web app, and the MCP server, out+# of scope for a REST-boundary fix and not safe to patch here.+# ``provider`` is not blocked this way (``_init_search_system``'s own+# default is ``None``, so ``get_llm`` does fall back to the snapshot)+# but is rejected anyway for symmetry: neither has ever been a+# documented REST parameter (unlike ``temperature`` — see+# ``_ACCEPTED_BUT_INEFFECTIVE_PARAMS`` below), so there is no+# backward-compatibility reason to keep accepting either.+# - ``user_password``/``metadata`` are not declared parameters at all; they+# are read directly out of **kwargs. ``user_password`` gets stashed+# verbatim into the metrics ``search_context`` dict (a password-shaped+# value written to the metrics store); ``metadata`` is read nowhere and+# silently dropped. Neither does anything useful over HTTP either.+#+# No legitimate REST caller can rely on a no-op, so rejecting these costs+# nothing — same argument as for _REGISTRY_PARAMS.+_DEAD_OR_CONFUSING_PARAMS = frozenset(+ {+ "settings",+ "settings_override",+ "api_key",+ "user_password",+ "metadata",+ "provider",+ "max_search_results",+ }+)+++# ``temperature`` is dead on quick_summary/generate_report for the exact+# same reason as ``_DEAD_OR_CONFUSING_PARAMS`` above: it is only read+# inside quick_summary's/generate_report's own+# ``if "settings_snapshot" not in kwargs:`` branch, which the REST path+# always skips, AND ``_init_search_system`` calls ``get_llm(temperature=``+# with its OWN hardcoded ``temperature: float = 0.7`` default (never+# ``None``), so even threading a caller's value into the settings snapshot+# instead would not rescue it — ``get_llm``'s+# ``if temperature is None: <fall back to settings_snapshot>`` branch never+# fires.+#+# Unlike the rest of that set, though, ``temperature`` is a PUBLICLY+# DOCUMENTED REST parameter: it was listed in this module's own+# ``GET /api/v1`` ``parameters`` dict for both endpoints, and release notes+# 1.8.1 tells callers migrating off the removed ``quick_summary_test``+# endpoint to "call /quick_summary with search_tool, iterations, and+# temperature set explicitly". Hard-400ing it (as the rest of+# ``_DEAD_OR_CONFUSING_PARAMS`` correctly does — no legitimate caller ever+# relied on those) would therefore break existing callers who followed our+# own documentation. So ``temperature`` gets the honest-and-non-breaking+# treatment instead: the request still succeeds, but the value is popped+# out of ``params`` before the research function is called (see+# ``_pop_ineffective_params``) — it truly cannot reach quick_summary/+# generate_report — and the response carries a ``warnings`` entry naming+# it and pointing callers who actually need temperature control at+# ``POST /api/v1/analyze_documents``, where it IS honored+# (``analyze_documents`` reads it directly, outside the dead+# ``settings_snapshot``-from-scratch branch above).+_ACCEPTED_BUT_INEFFECTIVE_PARAMS = frozenset({"temperature"})+++# The full class of request-body keys that must never reach+# quick_summary/generate_report from the public REST path. See+# _REGISTRY_PARAMS, _CALLABLE_PARAMS, _CREDENTIAL_STEERING_PARAMS,+# _IDENTITY_PLUMBING_PARAMS, and _DEAD_OR_CONFUSING_PARAMS above for what+# each group protects against.+#+# This audit spans all THREE REST endpoints that forward a request body+# into a research function, not just these two:+# - quick_summary / generate_report (api_quick_summary / api_generate_report+# below) enforce this class via ``_reject_unsafe_body_params`` and this+# ``_REJECTED_BODY_PARAMS`` reject-list.+# - analyze_documents (api_analyze_documents below) uses a different+# mechanism — a signature-derived ALLOWlist (``_ANALYZE_DOCUMENTS_PARAMS``)+# rather than a reject-list, because it has no **kwargs to smuggle+# unlisted keys through. Members of ``_IDENTITY_PLUMBING_PARAMS`` that+# are also declared parameters of ``analyze_documents`` (currently just+# ``programmatic_mode`` — see the comment above+# ``_ANALYZE_DOCUMENTS_PARAMS``) are explicitly subtracted from that+# allowlist so the same identity/audit-plumbing protection applies there+# too, even though they never appear in this reject-list union.+# ``_REGISTRY_PARAMS``/``_CALLABLE_PARAMS``/``_CREDENTIAL_STEERING_PARAMS``+# need no equivalent subtraction: none of retrievers/llms/+# progress_callback/openai_endpoint_url is a declared parameter of+# analyze_documents, so the allowlist derivation already excludes them.+#+# This is genuinely the full class for quick_summary/generate_report: every+# OTHER **kwargs-forwarded key that reaches _init_search_system from the+# REST body has been traced below and found to be a legitimate, harmless+# public knob — kept forwarded, not rejected:+#+# - ``model_name`` — selects which model string to request from the+# caller's OWN already-configured provider/API key; no host or+# credential is chosen by this value. It is explicitly documented as a+# public parameter of POST /api/v1/generate_report in+# ``api_v1_documentation`` above.+# - ``search_strategy`` — selects which strategy class runs+# (source_based/modular/etc.), all under the same user's settings+# snapshot and egress policy; no different privilege or destination.+# - ``questions_per_iteration`` — a research-depth tuning knob in the same+# family as the already-forwarded, already-documented ``iterations``;+# bounded by the same per-route rate limiting as any other call.+#+# ``search_tool`` and ``iterations`` are also forwarded but are not part of+# this audit: both are already documented public parameters+# (api_v1_documentation above) and were never in question.+_REJECTED_BODY_PARAMS = (+ _REGISTRY_PARAMS+ | _CALLABLE_PARAMS+ | _CREDENTIAL_STEERING_PARAMS+ | _IDENTITY_PLUMBING_PARAMS+ | _DEAD_OR_CONFUSING_PARAMS+)+++def _reject_unsafe_body_params(data: Dict[str, Any]) -> Optional[JSONResponse]:+ """Reject request-body keys that a JSON body cannot legitimately carry,+ that steer a live call to a caller-chosen endpoint/credential, that are+ identity/audit plumbing the REST path already manages itself, or that+ are silent no-ops (and only a source of confusion) over the public REST+ path.++ Returns a 400 ``JSONResponse`` the endpoint must return when any+ ``_REJECTED_BODY_PARAMS`` key is present in the body, or ``None`` when+ the body is clean. See ``_REJECTED_BODY_PARAMS`` for the rationale.+ """+ present = sorted(_REJECTED_BODY_PARAMS & set(data))+ if present:+ return JSONResponse(+ {+ "error": (+ "The following parameter(s) are not accepted via the "+ f"REST API: {', '.join(present)}. They either require "+ "a live Python object a JSON body cannot carry "+ "(retrievers/llms/progress_callback), steer the call's "+ "LLM endpoint/credentials to a caller-chosen host "+ "(openai_endpoint_url), are identity/audit plumbing the "+ "REST path already manages itself "+ "(research_id/programmatic_mode/research_context/"+ "research_mode), or "+ "have no effect "+ "when set from the REST path "+ "(settings/settings_override/api_key/user_password/"+ "metadata/provider/max_search_results); "+ "pass them via the in-process Python API instead."+ )+ },+ status_code=400,+ )+ return None+++def _pop_ineffective_params(params: Dict[str, Any]) -> list:+ """Strip ``_ACCEPTED_BUT_INEFFECTIVE_PARAMS`` keys out of ``params`` in+ place and return a caller-facing warning string per key removed.++ Unlike ``_reject_unsafe_body_params``, this never blocks the request —+ these keys are accepted for backward compatibility (see+ ``_ACCEPTED_BUT_INEFFECTIVE_PARAMS``) but popped here so they truly+ cannot reach the research function, same end state as a rejected+ param, just without breaking existing callers who send them.+ """+ warnings = []+ for key in sorted(_ACCEPTED_BUT_INEFFECTIVE_PARAMS & set(params)):+ params.pop(key, None)+ warnings.append(+ f"'{key}' was accepted but has no effect on this endpoint and "+ "was ignored; it only affects POST /api/v1/analyze_documents."+ )+ return warningsasync def require_api_access(@@ -273,8 +650,8 @@ def api_documentation("query": "Research query (required)","search_tool": "Search engine to use (optional)","iterations": "Number of search iterations (optional)",- "temperature": "LLM temperature (optional)","allow_default_settings": "Set to true to proceed with default settings (and NO egress policy) when your stored settings cannot be loaded; default is to refuse with 503 (optional)",+ "temperature": "Accepted for backward compatibility but has NO effect on this endpoint (dropped before the research call; a 'warnings' entry is returned when set) — use POST /api/v1/analyze_documents for temperature control (optional)",},},{@@ -286,8 +663,8 @@ def api_documentation("output_file": "Path to save report (optional)","searches_per_section": "Searches per report section (optional)","model_name": "LLM model to use (optional)",- "temperature": "LLM temperature (optional)","allow_default_settings": "Set to true to proceed with default settings (and NO egress policy) when your stored settings cannot be loaded; default is to refuse with 503 (optional)",+ "temperature": "Accepted for backward compatibility but has NO effect on this endpoint (dropped before the research call; a 'warnings' entry is returned when set) — use POST /api/v1/analyze_documents for temperature control (optional)",},},{@@ -433,6 +810,18 @@ async def api_quick_summary({"error": "Query must be a string"}, status_code=400)+ # Reject the whole unsafe-forwarding class (retrievers/llms/+ # progress_callback/openai_endpoint_url/research_id/programmatic_mode/+ # settings/settings_override/api_key/user_password/metadata/provider/+ # max_search_results) BEFORE building params. See _REJECTED_BODY_PARAMS+ # for why these can't be forwarded from the HTTP path. ``temperature``+ # is handled separately below: it is a documented public parameter, so+ # it is accepted (not 400ed) but stripped before it can reach+ # quick_summary — see _ACCEPTED_BUT_INEFFECTIVE_PARAMS.+ unsafe_param_error = _reject_unsafe_body_params(data)+ if unsafe_param_error is not None:+ return unsafe_param_error+# Opt-in escape hatch for programmatic callers: when settings can't be# loaded, proceed with defaults (empty snapshot → permissive scope) instead# of failing closed (503). Default False (fail closed) so a configured@@ -447,11 +836,15 @@ async def api_quick_summary(for k, v in data.items()if k not in ("query", "allow_default_settings")}- # Set reasonable defaults for API use. search_tool deliberately has+ # Set a reasonable default for API use. search_tool deliberately has# no default here: when omitted, quick_summary reads the user's- # configured search.tool from the settings snapshot.- params.setdefault("temperature", 0.7)+ # configured search.tool from the settings snapshot. ``temperature`` is+ # popped out (not defaulted) here — quick_summary only reads its own+ # temperature argument in the branch that builds a settings_snapshot+ # from scratch, which the REST path never takes, so it can't be+ # rescued by forwarding it; see _pop_ineffective_params.params.setdefault("iterations", 1)+ param_warnings = _pop_ineffective_params(params)error = await run_db_sync(_load_user_context_into_params, params, username, allow_default_settings@@ -480,6 +873,9 @@ async def api_quick_summary(# response leaves. See _scrub_error_fields for rationale._scrub_error_fields(converted)+ if param_warnings:+ converted["warnings"] = param_warnings+return convertedexcept TimeoutError:logger.exception("Request timed out")@@ -529,6 +925,18 @@ async def api_generate_report(return JSONResponse({"error": "Query must be a string"}, status_code=400)++ # Reject the whole unsafe-forwarding class (retrievers/llms/+ # progress_callback/openai_endpoint_url/research_id/programmatic_mode/+ # settings/settings_override/api_key/user_password/metadata/provider/+ # max_search_results) BEFORE building params. See _REJECTED_BODY_PARAMS+ # for why these can't be forwarded from the HTTP path. ``temperature``+ # is handled separately below: see api_quick_summary and+ # _ACCEPTED_BUT_INEFFECTIVE_PARAMS.+ unsafe_param_error = _reject_unsafe_body_params(data)+ if unsafe_param_error is not None:+ return unsafe_param_error+# See api_quick_summary for the allow_default_settings semantics# (opt-in escape hatch, strict ``is True``, excluded from params).allow_default_settings = data.get("allow_default_settings") is True@@ -538,7 +946,9 @@ async def api_generate_report(if k not in ("query", "allow_default_settings")}params.setdefault("searches_per_section", 1)- params.setdefault("temperature", 0.7)+ # ``temperature`` is popped out (not defaulted) here: see+ # api_quick_summary for why it's dead on the REST path.+ param_warnings = _pop_ineffective_params(params)error = await run_db_sync(_load_user_context_into_params, params, username, allow_default_settings@@ -571,6 +981,9 @@ async def api_generate_report(# error-carrying fields._scrub_error_fields(result)+ if param_warnings and isinstance(result, dict):+ result["warnings"] = param_warnings+return resultexcept TimeoutError:return JSONResponse(diff --git a/tests/api_tests/test_api_basic.py b/tests/api_tests/test_api_basic.pyindex 58ecb1aba6..fc46c14375 100644--- a/tests/api_tests/test_api_basic.py+++ b/tests/api_tests/test_api_basic.py@@ -59,7 +59,6 @@ class TestBasicAPI:"query": "test","search_tool": "wikipedia","iterations": 1,- "temperature": 0.7,}print(diff --git a/tests/api_tests/test_rest_api.py b/tests/api_tests/test_rest_api.pyindex b877dd9695..90f738b70a 100644--- a/tests/api_tests/test_rest_api.py+++ b/tests/api_tests/test_rest_api.py@@ -42,7 +42,6 @@ class TestRestAPI:"query": "Python","search_tool": "wikipedia","iterations": 1,- "temperature": 0.7,}response = authenticated_client.post(diff --git a/tests/api_tests/test_rest_api_simple.py b/tests/api_tests/test_rest_api_simple.pyindex 2f35cf7fe9..34e1ad6344 100644--- a/tests/api_tests/test_rest_api_simple.py+++ b/tests/api_tests/test_rest_api_simple.py@@ -67,7 +67,6 @@ class TestRestAPISimple:"query": "cat", # Single word, very common"search_tool": "wikipedia","iterations": 1,- "temperature": 0.7,}print("Making request...")diff --git a/tests/security/test_api_v1_boundary_fastapi.py b/tests/security/test_api_v1_boundary_fastapi.pyindex b53fe4cf9f..5a05d0f332 100644--- a/tests/security/test_api_v1_boundary_fastapi.py+++ b/tests/security/test_api_v1_boundary_fastapi.py@@ -28,6 +28,29 @@ against its real signature, with ``username`` and ``settings_snapshot``deliberately excluded so a caller cannot name the user whose settings andcredentials the run executes with.+``quick_summary``/``generate_report`` DO have ``**kwargs``, so an unknown+body key doesn't TypeError - it is silently forwarded to the research+function instead. ``_REJECTED_BODY_PARAMS`` denylists the specific keys+that are unsafe to forward: ``retrievers``/``llms`` (registry poisoning),+``progress_callback`` (Callable-typed - a string assigned to it blows up+mid-research as an opaque 500 the moment something tries to call it),+``openai_endpoint_url`` (live credential/endpoint steering - overlays the+account's stored ``llm.openai_endpoint`` URL and API key with a+caller-chosen host), ``research_id``/``programmatic_mode``/+``research_context`` (identity/audit plumbing the REST path already+manages itself), and+``settings``/``settings_override``/``api_key``/``user_password``/+``metadata``/``provider``/``max_search_results`` (silent no-ops on the+REST path, kept out so a future refactor can't quietly turn "no-op" into+"lever"). ``temperature`` is the one exception in that no-op family: it is+a PUBLICLY DOCUMENTED parameter (``GET /api/v1`` and release notes 1.8.1+both tell callers to pass it to ``/quick_summary``), so hard-400ing it+would break existing callers. It is accepted (200), stripped from+``params`` before the research call (so it still can't reach it), and the+response carries a ``warnings`` entry naming it. See+``_ACCEPTED_BUT_INEFFECTIVE_PARAMS`` in ``api_v1.py`` and+``TestIneffectiveButAcceptedParams`` below.+COVERAGE AREA 3 - CWE-209 scrub wiring--------------------------------------``tests/web/routers/test_api_v1_error_scrub.py`` covers ``_scrub_error_fields``@@ -565,6 +588,346 @@ class TestQueryTypeValidation:)+class TestRegistryParamsRejection:+ """Coverage area 2: ``retrievers``/``llms`` are rejected, not forwarded.++ Ported from PR #5533, which originally landed this guard on the Flask+ blueprint at ``src/local_deep_research/web/api.py``. That blueprint was+ unmounted by the FastAPI migration (#3299) and later deleted outright,+ so the guard never reached the endpoints that actually serve+ ``/api/v1/quick_summary`` and ``/api/v1/generate_report`` on current+ ``main`` - this class exercises the live ``api_v1.py`` implementation+ instead.++ ``retrievers``/``llms`` are declared parameters of ``quick_summary``/+ ``generate_report`` (see ``QUICK_SUMMARY_TARGET``/``GENERATE_REPORT_TARGET``+ in ``api/research_functions.py``) that get registered into the retriever+ registry / LLM registry the moment they reach the research function. A+ JSON body can never carry a live ``BaseRetriever``/``BaseChatModel``, so+ any value posted on these keys is necessarily the wrong type - this+ rejects it at the HTTP boundary with a 400 instead of letting it reach+ ``register_multiple`` (an opaque 500) or silently poison the caller's own+ registry namespace. ``analyze_documents`` has no ``retrievers``/``llms``+ parameter, so it is already covered by+ ``TestAnalyzeDocumentsParameterInjection``'s signature-derived allowlist+ and is not repeated here.+ """++ @pytest.mark.parametrize(+ "label,path,target",+ [+ ("quick_summary", QUICK_SUMMARY_PATH, QUICK_SUMMARY_TARGET),+ ("generate_report", GENERATE_REPORT_PATH, GENERATE_REPORT_TARGET),+ ],+ )+ @pytest.mark.parametrize(+ "body_extra",+ [+ {"retrievers": {"poison": "not-a-retriever"}},+ {"llms": {"poison": "not-an-llm"}},+ {+ "retrievers": {"poison": "not-a-retriever"},+ "llms": {"poison": "not-an-llm"},+ },+ ],+ ids=["retrievers", "llms", "both"],+ )+ def test_rejects_registry_params_with_400(+ self, live_app, label, path, target, body_extra+ ):+ client, _username = _api_user(live_app)++ with patch(target) as research_fn:+ research_fn.return_value = {"summary": "fine", "findings": []}+ resp = _post(client, path, {"query": QUERY, **body_extra})++ assert resp.status_code == 400, (+ f"{label}: expected a 400, got {resp.status_code} / "+ f"{resp.text[:300]}"+ )+ # The research function (and thus registration) must never run.+ assert research_fn.call_count == 0, (+ f"{label}: a registry param reached the research function"+ )+ error = resp.json()["error"]+ for key in body_extra:+ assert key in error, f"{label}: error must name {key!r}: {error!r}"++ @pytest.mark.parametrize(+ "label,path,body,target",+ [+ (+ "quick_summary",+ QUICK_SUMMARY_PATH,+ {"query": QUERY},+ QUICK_SUMMARY_TARGET,+ ),+ (+ "generate_report",+ GENERATE_REPORT_PATH,+ {"query": QUERY},+ GENERATE_REPORT_TARGET,+ ),+ ],+ ids=["quick_summary", "generate_report"],+ )+ def test_clean_request_without_registry_params_still_succeeds(+ self, live_app, label, path, body, target+ ):+ """Positive control: the guard doesn't reject legitimate requests."""+ client, _username = _api_user(live_app)++ with patch(target) as research_fn:+ research_fn.return_value = {"summary": "fine", "findings": []}+ resp = _post(client, path, body)++ assert resp.status_code == 200, f"{label}: {resp.text[:400]}"+ assert "retrievers" not in research_fn.call_args.kwargs+ assert "llms" not in research_fn.call_args.kwargs+++class TestUnsafeForwardParamsRejection:+ """Coverage area 2: the rest of the unvalidated-forwarding class.++ ``TestRegistryParamsRejection`` above covers ``retrievers``/``llms``.+ Rejecting only those two left the same *class* of bug open: ``params``+ for ``quick_summary``/``generate_report`` is still built as+ ``{k: v for k, v in body.items() if k not in (...)}``, forwarding every+ other body key straight to the research function.++ ``progress_callback`` is the sharpest instance: it is Callable-typed,+ a JSON body can never carry one, and unlike retrievers/llms it doesn't+ fail loudly at the registration site — the string gets assigned to+ ``system.progress_callback`` and only blows up deep inside the strategy+ loop, mid-research, as an opaque 500 (POSTing+ ``{"query": "x", "progress_callback": "boom"}`` reaches+ ``_init_search_system`` -> ``system.set_progress_callback("boom")``).++ ``settings``/``settings_override``/``api_key``/``user_password``/+ ``metadata`` round out the class: declared parameters (or bare+ **kwargs reads) that are silent no-ops over the REST path today, kept+ out anyway so no future refactor turns "no-op" back into "lever" the+ way it already is for username/settings_snapshot. See+ ``_REJECTED_BODY_PARAMS`` in ``api_v1.py`` for the full rationale.++ ``provider``/``max_search_results`` are the same no-op shape as+ ``api_key`` above: named parameters of ``quick_summary``/+ ``generate_report`` consumed only inside the+ ``if "settings_snapshot" not in kwargs:`` branch that the REST path+ never takes (``_load_user_context_into_params`` always injects a+ snapshot). See the ``_DEAD_OR_CONFUSING_PARAMS`` comment in+ ``api_v1.py`` for why these cannot simply be threaded into the+ settings snapshot instead. ``temperature`` is the same dead shape but+ is handled differently (200 + a ``warnings`` entry, not a 400) because+ it is a publicly documented parameter — see+ ``TestIneffectiveButAcceptedParams`` below, not this class.++ ``openai_endpoint_url`` is the opposite of a no-op: it is forwarded+ unconditionally (never gated behind the settings_snapshot branch+ above), and when the caller's stored ``llm.provider`` is+ ``openai_endpoint`` it OVERLAYS ``settings_snapshot["llm.openai_endpoint.+ url"]`` inside ``get_llm`` — steering that run's prompts, and the+ account's already-configured endpoint API key, to any host the caller+ names. See ``_CREDENTIAL_STEERING_PARAMS`` in ``api_v1.py``.++ ``research_id``/``programmatic_mode``/``research_context`` are+ identity/audit plumbing the REST path already manages itself: a+ caller-supplied ``research_id`` can split-brain a run's+ SearchCall/TokenUsage metrics rows on ``generate_report`` (which mints+ its own fresh id for one but not the other), ``programmatic_mode=true``+ lets a caller opt their own calls out of the DB-backed+ persistence/audit trail that ``_load_user_context_into_params``+ deliberately turns on for authenticated REST calls, and a+ caller-supplied ``research_context`` reaches+ ``get_llm(research_context=...)`` on ``generate_report`` (unlike+ ``quick_summary``, which always overwrites it with its own+ server-built metrics dict before calling ``_init_search_system``) -+ a non-dict value 500s where the code mutates it+ (``research_context["context_limit"] = ...``), and a dict value feeds+ caller-controlled ``username``/``user_password``/query metadata into+ ``TokenCounter``. See ``_IDENTITY_PLUMBING_PARAMS`` in ``api_v1.py``.+ """++ @pytest.mark.parametrize(+ "label,path,target",+ [+ ("quick_summary", QUICK_SUMMARY_PATH, QUICK_SUMMARY_TARGET),+ ("generate_report", GENERATE_REPORT_PATH, GENERATE_REPORT_TARGET),+ ],+ )+ @pytest.mark.parametrize(+ "key,value",+ [+ ("progress_callback", "boom"),+ ("settings", {"llm.provider": "openai"}),+ ("settings_override", {"llm.provider": "openai"}),+ ("api_key", "sk-not-really-a-key"),+ ("user_password", "not-really-a-password"),+ ("metadata", {"anything": "here"}),+ ("provider", "anthropic"),+ ("max_search_results", 5),+ ("openai_endpoint_url", "https://attacker.example.com/v1"),+ ("research_id", "attacker-chosen-research-id"),+ ("programmatic_mode", True),+ (+ "research_context",+ {"username": "attacker", "user_password": "not-a-password"},+ ),+ ("research_mode", "attacker-chosen-mode-label"),+ ],+ )+ def test_rejects_unsafe_forward_params_with_400(+ self, live_app, label, path, target, key, value+ ):+ client, _username = _api_user(live_app)++ with patch(target) as research_fn:+ research_fn.return_value = {"summary": "fine", "findings": []}+ resp = _post(client, path, {"query": QUERY, key: value})++ assert resp.status_code == 400, (+ f"{label}/{key}: expected a 400, got {resp.status_code} / "+ f"{resp.text[:300]}"+ )+ # The research function must never run with the unsafe key present.+ assert research_fn.call_count == 0, (+ f"{label}/{key}: an unsafe param reached the research function"+ )+ error = resp.json()["error"]+ assert key in error, (+ f"{label}/{key}: error must name {key!r}: {error!r}"+ )++ @pytest.mark.parametrize(+ "label,path,target",+ [+ ("quick_summary", QUICK_SUMMARY_PATH, QUICK_SUMMARY_TARGET),+ ("generate_report", GENERATE_REPORT_PATH, GENERATE_REPORT_TARGET),+ ],+ )+ def test_clean_request_with_documented_params_still_succeeds(+ self, live_app, label, path, target+ ):+ """Positive control: legitimate documented params still pass.++ Proves the new denylist doesn't collaterally reject ordinary+ request-configuration params that were never part of this bug+ class (they aren't Callable-typed and aren't dead no-ops).++ ``temperature`` is deliberately NOT included here either: it is a+ dead no-op on this REST path (see+ ``TestUnsafeForwardParamsRejection``'s docstring), just no longer a+ 400 — it belongs in ``TestIneffectiveButAcceptedParams`` below,+ which asserts the 200 + ``warnings`` + stripped-before-the-call+ behavior specifically. ``iterations``/``search_tool``/``model_name``/+ ``search_strategy``/``questions_per_iteration`` are real, live+ kwargs forwarded through quick_summary's/generate_report's+ ``**kwargs`` (never gated behind the settings_snapshot branch), so+ asserting against the mocked call here genuinely proves they reach+ the research function — unlike a dead param, where the same+ assertion would pass even though the value never has any+ downstream effect. The last three are the audited-allowed set from+ the ``_REJECTED_BODY_PARAMS`` comment block in ``api_v1.py``:+ traced into ``_init_search_system``/``get_llm``/``get_search`` and+ found to only select among the caller's OWN already-configured+ provider/model/strategy — no host or credential steering, unlike+ ``openai_endpoint_url``.+ """+ client, _username = _api_user(live_app)++ with patch(target) as research_fn:+ research_fn.return_value = {"summary": "fine", "findings": []}+ resp = _post(+ client,+ path,+ {+ "query": QUERY,+ "iterations": 2,+ "search_tool": "wikipedia",+ "model_name": "gpt-4o-mini",+ "search_strategy": "source_based",+ "questions_per_iteration": 2,+ },+ )++ assert resp.status_code == 200, f"{label}: {resp.text[:400]}"+ assert research_fn.call_args.kwargs["iterations"] == 2+ assert research_fn.call_args.kwargs["search_tool"] == "wikipedia"+ assert research_fn.call_args.kwargs["model_name"] == "gpt-4o-mini"+ assert research_fn.call_args.kwargs["search_strategy"] == "source_based"+ assert research_fn.call_args.kwargs["questions_per_iteration"] == 2+++class TestIneffectiveButAcceptedParams:+ """Coverage area 2: ``temperature`` is a documented no-op, not a 400.++ Unlike the dead no-ops in ``TestUnsafeForwardParamsRejection``,+ ``temperature`` was a PUBLICLY DOCUMENTED REST parameter (``GET+ /api/v1``'s own ``parameters`` dict, and release notes 1.8.1 telling+ callers migrating off the removed ``quick_summary_test`` endpoint to+ "call /quick_summary with search_tool, iterations, and temperature set+ explicitly"). Hard-400ing it would break existing callers who followed+ that documentation, so it takes the honest-and-non-breaking path+ instead: accepted (200), popped out of ``params`` before the research+ function is called so it genuinely cannot reach it, and the response+ carries a ``warnings`` entry naming it. See+ ``_ACCEPTED_BUT_INEFFECTIVE_PARAMS``/``_pop_ineffective_params`` in+ ``api_v1.py``.+ """++ @pytest.mark.parametrize(+ "label,path,target",+ [+ ("quick_summary", QUICK_SUMMARY_PATH, QUICK_SUMMARY_TARGET),+ ("generate_report", GENERATE_REPORT_PATH, GENERATE_REPORT_TARGET),+ ],+ )+ def test_temperature_succeeds_with_a_warning_and_is_stripped(+ self, live_app, label, path, target+ ):+ client, _username = _api_user(live_app)++ with patch(target) as research_fn:+ research_fn.return_value = {"summary": "fine", "findings": []}+ resp = _post(client, path, {"query": QUERY, "temperature": 0.1})++ assert resp.status_code == 200, (+ f"{label}: temperature must not be hard-rejected (it is a "+ f"documented parameter), got {resp.status_code} / "+ f"{resp.text[:300]}"+ )+ # It must still never reach the research function.+ assert "temperature" not in research_fn.call_args.kwargs, (+ f"{label}: temperature was forwarded to the research function "+ "despite being an accepted-but-ineffective param"+ )+ body = resp.json()+ assert any("temperature" in w for w in body.get("warnings", [])), (+ f"{label}: response must warn that temperature had no effect: "+ f"{body!r}"+ )++ @pytest.mark.parametrize(+ "label,path,target",+ [+ ("quick_summary", QUICK_SUMMARY_PATH, QUICK_SUMMARY_TARGET),+ ("generate_report", GENERATE_REPORT_PATH, GENERATE_REPORT_TARGET),+ ],+ )+ def test_no_warnings_key_when_nothing_ineffective_was_posted(+ self, live_app, label, path, target+ ):+ """Negative control: a clean request gets no ``warnings`` noise."""+ client, _username = _api_user(live_app)++ with patch(target) as research_fn:+ research_fn.return_value = {"summary": "fine", "findings": []}+ resp = _post(client, path, {"query": QUERY})++ assert resp.status_code == 200, f"{label}: {resp.text[:300]}"+ assert "warnings" not in resp.json()++class TestAnalyzeDocumentsParameterInjection:"""Coverage area 2: the ``analyze_documents`` body-key allowlist."""@@ -630,6 +993,7 @@ class TestAnalyzeDocumentsParameterInjection:[("username", "victim"),("settings_snapshot", {"llm.provider": "openai"}),+ ("programmatic_mode", True),],)def test_server_set_identity_parameters_cannot_be_supplied_by_the_caller(@@ -643,6 +1007,20 @@ class TestAnalyzeDocumentsParameterInjection:executes with - and, via ``settings_snapshot``, hand itself apermissive egress policy. They are excluded from the allowlist, sothey are rejected rather than honoured.++ ``programmatic_mode`` is different: it IS a genuine declared+ parameter of ``analyze_documents``, so it would otherwise survive+ the signature-derived allowlist untouched.+ ``_load_user_context_into_params`` sets it via ``setdefault``+ specifically so authenticated REST calls default to DB-backed+ metrics/rate-limit persistence, and ``setdefault`` means an+ explicit body value would be respected rather than overridden -+ letting a caller opt their own ``analyze_documents`` calls out of+ the audit trail and DB-backed rate-limit accounting, the same gap+ already closed for ``quick_summary``/``generate_report``. It must+ be explicitly subtracted from ``_ANALYZE_DOCUMENTS_PARAMS`` (see+ ``api_v1.py``) rather than merely excluded like+ ``username``/``settings_snapshot`` above."""client, _username = _api_user(live_app)diff --git a/tests/web/routers/test_api_v1_external_contract.py b/tests/web/routers/test_api_v1_external_contract.pyindex 1f9350d03f..cccbfa0805 100644--- a/tests/web/routers/test_api_v1_external_contract.py+++ b/tests/web/routers/test_api_v1_external_contract.py@@ -33,12 +33,19 @@ What this file pins, and why each piece was not already pinned:(``grep -r page_content tests/web tests/security`` and``grep -r content_truncated tests/`` both come back empty of api_v1).-3. **The request contract.** The server-side defaults (``temperature``,- ``iterations``, ``searches_per_section``) and the deliberate ABSENCE of- a ``search_tool`` default are part of what a caller gets when they omit+3. **The request contract.** The server-side defaults (``iterations``,+ ``searches_per_section``) and the deliberate ABSENCE of a+ ``search_tool`` default are part of what a caller gets when they omita key. ``tests/security/test_api_v1_boundary_fastapi.py`` pins theidentity params (``username`` / ``settings_snapshot``); the defaults- were unpinned.+ were unpinned. ``temperature`` is NOT defaulted, and never reaches the+ research function, on ``quick_summary``/``generate_report`` — it is a+ documented no-op on the REST path (see+ ``_ACCEPTED_BUT_INEFFECTIVE_PARAMS`` in ``api_v1.py``) — but IS+ accepted with a 200 and a ``warnings`` entry, not a 400, because it was+ a publicly documented parameter (``GET /api/v1``, release notes 1.8.1);+ ``tests/security/test_api_v1_boundary_fastapi.py`` pins that+ accept-but-strip behavior.4. **``require_api_access`` and the API kill-switch over HTTP.**``tests/web/test_rate_limit_coverage.py``::TestRequireApiAccess calls the@@ -509,16 +516,13 @@ class TestQuickSummaryResponseShape:class TestServerSideRequestDefaults:- def test_quick_summary_defaults_temperature_and_iterations(- self, authenticated_client- ):+ def test_quick_summary_defaults_iterations(self, authenticated_client):with patch(QS_TARGET, return_value={"summary": "s"}) as fn:resp = authenticated_client.post(QUICK, json={"query": "q"})assert resp.status_code == 200, resp.text[:300]args, kwargs = fn.call_argsassert args == ("q",), "query is passed positionally"- assert kwargs["temperature"] == 0.7assert kwargs["iterations"] == 1def test_quick_summary_does_not_default_search_tool(@@ -533,18 +537,38 @@ class TestServerSideRequestDefaults:assert "search_tool" not in fn.call_args.kwargs+ def test_quick_summary_accepts_but_strips_temperature(+ self, authenticated_client+ ):+ """``temperature`` is a documented no-op on the REST path (see+ ``_ACCEPTED_BUT_INEFFECTIVE_PARAMS`` in ``api_v1.py``), but unlike+ the hard-400ed no-ops it was a PUBLICLY DOCUMENTED REST parameter+ (``GET /api/v1``, release notes 1.8.1), so hard-rejecting it would+ break existing callers. It is accepted (200), stripped before the+ research call, and surfaced as a ``warnings`` entry instead.+ ``tests/security/test_api_v1_boundary_fastapi.py`` covers this in+ depth; this just pins that the request-defaults contract genuinely+ never forwards ``temperature`` to quick_summary."""+ with patch(QS_TARGET, return_value={"summary": "s"}) as fn:+ resp = authenticated_client.post(+ QUICK, json={"query": "q", "temperature": 0.1}+ )++ assert resp.status_code == 200, resp.text[:300]+ assert "temperature" not in fn.call_args.kwargs+ assert any("temperature" in w for w in resp.json().get("warnings", []))+def test_body_values_win_over_the_defaults(self, authenticated_client):with patch(QS_TARGET, return_value={"summary": "s"}) as fn:authenticated_client.post(QUICK,- json={"query": "q", "temperature": 0.1, "iterations": 5},+ json={"query": "q", "iterations": 5},)kwargs = fn.call_args.kwargs- assert kwargs["temperature"] == 0.1assert kwargs["iterations"] == 5- def test_generate_report_defaults_searches_per_section_and_temperature(+ def test_generate_report_defaults_searches_per_section(self, authenticated_client):with patch(GR_TARGET, return_value={"content": "c"}) as fn:@@ -554,7 +578,7 @@ class TestServerSideRequestDefaults:args, kwargs = fn.call_argsassert args == ("q",)assert kwargs["searches_per_section"] == 1- assert kwargs["temperature"] == 0.7+ assert "temperature" not in kwargsdef test_analyze_documents_passes_both_positionals_and_no_defaults(self, authenticated_client@@ -675,11 +699,17 @@ class TestAnalyzeDocumentsUnknownParameterBody:# so the two cannot drift; hard-coded here because THIS list is what# a client reads out of the 400 body, so any change to it is an API# change that should have to be made deliberately in two places.+ # ``programmatic_mode`` IS a declared parameter of analyze_documents but+ # is deliberately excluded from the wire allowlist: it is+ # identity/audit plumbing (see ``_IDENTITY_PLUMBING_PARAMS`` /+ # ``_ANALYZE_DOCUMENTS_PARAMS`` in api_v1.py) that+ # ``_load_user_context_into_params`` manages itself via+ # ``setdefault``, so a caller-supplied value would otherwise let a+ # request opt itself out of DB-backed metrics/rate-limit accounting.ALLOWED = ["force_reindex","max_results","output_file",- "programmatic_mode","temperature",]@@ -733,6 +763,30 @@ class TestAnalyzeDocumentsUnknownParameterBody:assert resp.status_code == 200, resp.text[:300]assert fn.call_args.kwargs[name] == 1+ def test_programmatic_mode_is_rejected_with_400(self, authenticated_client):+ """``programmatic_mode`` is a genuine declared parameter of+ ``analyze_documents`` (unlike ``bogus`` above), so it would+ otherwise survive the signature-derived allowlist untouched.+ It must be explicitly subtracted (see ``_ANALYZE_DOCUMENTS_PARAMS``+ in api_v1.py) so a caller cannot opt their own analyze_documents+ calls out of DB-backed metrics/rate-limit accounting the same way+ already closed for quick_summary/generate_report.+ """+ with patch(AD_TARGET) as fn:+ resp = authenticated_client.post(+ ANALYZE,+ json={+ "query": "q",+ "collection_name": "c",+ "programmatic_mode": True,+ },+ )++ assert resp.status_code == 400, resp.text[:300]+ assert fn.call_count == 0+ assert "programmatic_mode" in resp.json()["error"]+ assert "programmatic_mode" not in resp.json()["allowed_parameters"]+# ---------------------------------------------------------------------------# 7. Timeout and failure status codes@@ -851,20 +905,30 @@ class TestApiDocumentationPayload:"/api/v1/analyze_documents",}assert all(e["method"] == "POST" for e in by_path.values())+ # ``temperature`` IS advertised for all three endpoints, but its+ # quick_summary/generate_report entries carry a "no effect on this+ # endpoint" annotation (see api_documentation in api_v1.py): it is a+ # dead no-op there (accepted with a 200 + ``warnings`` entry, not+ # forwarded to the research function — see+ # _ACCEPTED_BUT_INEFFECTIVE_PARAMS), but omitting it entirely would+ # misrepresent the wire contract for callers following release+ # notes 1.8.1, which documents it as a valid /quick_summary+ # parameter. It stays a real, forwarded parameter for+ # analyze_documents below.assert set(by_path["/api/v1/quick_summary"]["parameters"]) == {"query","search_tool","iterations",- "temperature","allow_default_settings",+ "temperature",}assert set(by_path["/api/v1/generate_report"]["parameters"]) == {"query","output_file","searches_per_section","model_name",- "temperature","allow_default_settings",+ "temperature",}assert set(by_path["/api/v1/analyze_documents"]["parameters"]) == {"query",