~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): correct #5533's claims, reject output_file on REST research endpoints (#6203)
LearningCircuit3b217b83c3e3
diff --git a/changelog.d/+api-reject-registry-params.bugfix.md b/changelog.d/+api-reject-registry-params.bugfix.mdindex 5116ccd8dd..6d26469f76 100644--- a/changelog.d/+api-reject-registry-params.bugfix.md+++ b/changelog.d/+api-reject-registry-params.bugfix.md@@ -1 +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.+The public REST endpoints `/api/v1/quick_summary` and `/api/v1/generate_report` now reject 16 request-body parameters with HTTP 400 instead of silently forwarding or ignoring them: `retrievers`, `llms`, `progress_callback`, `openai_endpoint_url`, `research_id`, `programmatic_mode`, `research_context`, `research_mode`, `settings`, `settings_override`, `api_key`, `user_password`, `metadata`, `provider`, `max_search_results`, and `output_file`. Each was either a live-object parameter a JSON body can never carry correctly (`retrievers`/`llms`/`progress_callback`), live credential/endpoint steering (`openai_endpoint_url`), a server-side filesystem path a public API body should not choose (`output_file`), identity/audit plumbing the REST path already manages itself, or a silent no-op that only invited confusion. `/api/v1/analyze_documents` additionally rejects `programmatic_mode` and, as of this update, `output_file` too — the same bare-`open()` write sink as `generate_report`, closing the same gap on that third endpoint (it previously advertised the accepted-parameter set in its own `allowed_parameters` 400 response body, so this is a visible narrowing there too). `temperature` is the one previously-documented exception: it is accepted (200) rather than rejected for backward compatibility, but is stripped before the research call — every response where it was supplied now carries a `warnings` array naming it as a no-op on these two endpoints. `model_name`, `search_strategy`, and `search_tool` additionally get lightweight string type validation at the boundary, turning a wrong-typed value from an opaque 500 into a clear 400; a `null` value is let through unchanged for `model_name`/`search_tool` (both already treat `None` as "use the stored setting"), while `null` for `search_strategy` is correctly rejected (it previously 500'd). `iterations` is NOT type-validated: its only REST-path effect is an unread attribute assignment, so no type crashes there — an earlier draft of this note claimed a bad `iterations` type crashes mid-research via `range(1, iterations + 1)`, which traced to the wrong constructor call and was false; `iterations` (like `questions_per_iteration`) is accepted, forwarded, and simply inert on the REST path today. The in-process Python API is unaffected by all of the above and still accepts every one of these as real keyword arguments.diff --git a/docs/release_notes/1.8.1.md b/docs/release_notes/1.8.1.mdindex beee0e06e1..b1bc1e4b0e 100644--- a/docs/release_notes/1.8.1.md+++ b/docs/release_notes/1.8.1.md@@ -236,7 +236,7 @@`Cache`/`SearchCache` models (migration 0016). Neither table was ever populatedby any code path, so existing databases lose no data — the empty tables areremoved automatically on the next migration. ([#drop-orphaned-cache-tables](https://github.com/LearningCircuit/local-deep-research/pull/drop-orphaned-cache-tables))-- Removed the `/api/v1/quick_summary_test` REST endpoint. It was a near-duplicate of `/quick_summary` with hardcoded test defaults; call `/quick_summary` with `search_tool`, `iterations`, and `temperature` set explicitly instead. ([#3661](https://github.com/LearningCircuit/local-deep-research/pull/3661))+- Removed the `/api/v1/quick_summary_test` REST endpoint. It was a near-duplicate of `/quick_summary` with hardcoded test defaults; call `/quick_summary` with `search_tool`, `iterations`, and `temperature` set explicitly instead. ([#3661](https://github.com/LearningCircuit/local-deep-research/pull/3661)) — **Update (see [#5533](https://github.com/LearningCircuit/local-deep-research/pull/5533)):** `temperature` is still accepted on `/quick_summary`/`/generate_report` for compatibility with this note, but has no effect on either endpoint (it is dropped before the research call; a `warnings` entry names it in the response). Use `POST /api/v1/analyze_documents`, where `temperature` is honored, for real temperature control. — **Further update (post-merge review of #5533's follow-up):** `iterations` is also still accepted for compatibility with this note, but has no observable effect on `/api/v1/quick_summary` or `/api/v1/generate_report` — on that path the value is only assigned to an attribute nothing reads back, so the run uses the account's stored `search.iterations` setting. It IS honored on `POST /api/start_research`, which passes it to the `AdvancedSearchSystem` constructor as `max_iterations` (`web/services/research_service.py`); that is the endpoint to use if you need to control iteration count over HTTP. The two endpoints require the same authentication.- Removed the benchmark result-reuse feature: new benchmark runs no longer silently import results from previous completed runs with matching search settings. The compatibility check covered only a handful of settings (ignoring evaluation config, dataset versions, and the rest of the configuration), so results produced under different conditions could contaminate a run's accuracy, and the reuse accounting could report more than 100% completion. Every run now researches its own sampled questions and reports only its own results. ([#4498](https://github.com/LearningCircuit/local-deep-research/pull/4498))- Removed the DOAJ Seal quality tier (score 8) and the Tier 4 "+1 Seal bonus": DOAJ retired the Seal in April 2025 and removed it from its metadata, so the tier could never be earned again and only ever fired on stale pre-2025 data. DOAJ-listed journals keep their score-5 floor. The `has_doaj_seal` column was dropped from the reference DB (schema version 4 — the DB rebuilds automatically on first use) and the Seal star/count no longer appear on the journal-quality dashboard.- Removed the experimental search strategies that were only reachable through the "Show All Strategies" toggle (rapid, parallel, iterative, recursive, adaptive, smart, standard, iterdrag, browsecomp, evidence, the constrained/dual-confidence family, modular, and others), along with the toggle itself. The strategy dropdown now offers source-based, focused-iteration, focused-iteration-standard, topic-organization, mcp, and langgraph-agent. The news feature's internal news-aggregation strategy is unaffected.diff --git a/src/local_deep_research/web/routers/api_v1.py b/src/local_deep_research/web/routers/api_v1.pyindex 55ce7f5b6f..24cdb908ea 100644--- a/src/local_deep_research/web/routers/api_v1.py+++ b/src/local_deep_research/web/routers/api_v1.py@@ -101,6 +101,22 @@ def _scrub_error_fields(results: Dict[str, Any]) -> None:# rather than the reject-list ``_reject_unsafe_body_params`` uses) closes# it on this third endpoint too.#+# ``output_file`` is ALSO subtracted here for the identical reason it is+# rejected on quick_summary/generate_report (see ``_SERVER_PATH_PARAMS``+# below): analyze_documents (research_functions.py) reaches the same+# ``write_file_verified`` -> bare ``open(filepath, mode)`` sink — with no+# containment, traversal, or symlink check — after its own full+# search-and-LLM run, behind the same unset-by-default+# ``api.allow_file_output`` gate, and the same opaque catch-all 500 when+# that gate is (correctly) closed. A server-side filesystem path posted in+# a public JSON body is no more REST-shaped here than it is on the other+# two endpoints; there is no substantive reason for this third endpoint to+# disagree. Found and closed in the same post-merge review pass that added+# ``_SERVER_PATH_PARAMS`` — an earlier version of this module reported the+# gap here without closing it ("separately-scoped... out of scope"); that+# scoping call was wrong, since the fix is the same one-token subtraction+# already used for ``programmatic_mode`` right above.+## ``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@@ -114,6 +130,7 @@ _ANALYZE_DOCUMENTS_PARAMS = ("research_id","programmatic_mode","research_context",+ "output_file",})@@ -229,9 +246,14 @@ _CREDENTIAL_STEERING_PARAMS = frozenset({"openai_endpoint_url"})# 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+# authenticated REST calls default to DB-backed persistence. Because+# ``setdefault`` only sets a value that is ABSENT, an explicit+# caller-supplied ``programmatic_mode`` reaching that line would be+# respected rather than overridden — which is exactly the gap this+# ``_REJECTED_BODY_PARAMS`` entry closes, by rejecting the key with a 400+# before ``_load_user_context_into_params`` ever runs, so no+# caller-supplied value can reach that ``setdefault`` at all.+# ``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@@ -290,10 +312,35 @@ _IDENTITY_PLUMBING_PARAMS = frozenset(# 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+# settings snapshot instead (the way ``search_tool`` already works).+# NOT because of a ``get_search`` default shadowing it — that was traced+# to the wrong function. ``research_functions.py`` imports ``get_search``+# from ``config/search_config.py`` (``from ..config.search_config import+# get_search`` at the top of the file), whose signature (``search_tool``,+# ``llm_instance``, ``username``, ``settings_snapshot``,+# ``programmatic_mode``) has NO ``max_results`` parameter at all, and+# which reads the effective value straight out of the snapshot+# (``get_setting_from_snapshot("search.max_results", 10, ...)``) — the+# 10-default there is a snapshot fallback, not a shadowing kwarg.+# ``_init_search_system`` calls this ``get_search`` without ever passing+# ``max_results``. (``search_engine_factory.get_search`` — a different+# function, same name, in the retriever branch of the web-search-engines+# package, imported into ``config/search_config.py`` as+# ``factory_get_search`` — also defaults ``max_results`` to 10, and IS+# one frame down this call path: ``config/search_config.get_search``+# calls it with ``**params``, where ``params["max_results"]`` is the+# value already read from the snapshot above. So its own default is+# simply always overridden by that snapshot value before it can matter;+# a reader chasing "get_search" by name alone does still land on a+# second, differently-shaped function, but that function is reachable,+# not dead — the earlier version of this comment claiming it is "never+# on this call path" was wrong.) The real reason is simpler: even a caller-supplied+# ``max_search_results`` threaded into the snapshot would need to land+# under the key ``search.max_results`` — a different name — to have any+# effect, and nothing on the REST path performs that rename; only the+# user's own stored ``search.max_results`` setting (already in the+# snapshot ``_load_user_context_into_params`` loads) ever reaches+# ``get_search``. Renaming/threading it is a real internal-API gap# 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@@ -354,11 +401,58 @@ _DEAD_OR_CONFUSING_PARAMS = frozenset(_ACCEPTED_BUT_INEFFECTIVE_PARAMS = frozenset({"temperature"})+# ``output_file`` is a declared parameter of ``generate_report`` — it was+# advertised in this module's own ``GET /api/v1`` documentation (the+# ``api_documentation`` route's ``parameters`` dict, below) prior to this+# fix; that entry has been removed since a rejected parameter should not+# also be advertised as accepted. It lets the caller name a server-side+# filesystem path to write the finished report to (``research_functions.py``+# ``generate_report`` -> ``write_file_verified`` -> ``file_write_verifier.py``).+#+# It was NOT in the audit that produced the rest of this module's classes,+# because that audit was scoped to keys reaching ``_init_search_system``+# (registry/callable/credential-steering/identity-plumbing/dead-settings —+# see each class above), and ``output_file`` never reaches+# ``_init_search_system`` at all; it is consumed directly inside+# ``generate_report`` after the report is built. Rejecting it here closes+# that gap rather than widening the earlier audit's own scope claim.+#+# Two failure modes, both real:+# - No ``defaults/`` entry sets ``api.allow_file_output``. Precisely:+# ``write_file_verified`` calls ``get_setting_from_snapshot`` with no+# ``default``, so a missing key raises ``NoSettingsContextError``+# (``config/thread_settings.py``); it is ``file_write_verifier.py``'s own+# ``except Exception: actual_value = None`` that turns this into ``None``,+# which then does not equal the required ``True``. Either way+# ``write_file_verified`` raises ``FileWriteSecurityError`` — fail-closed,+# correctly — but only AFTER the+# full research-and-report run has already completed. The endpoint's+# catch-all ``except Exception`` has no special case for+# ``FileWriteSecurityError``, so the caller pays the entire run's cost for+# an opaque 500 that never mentions the real cause.+# - If an operator has explicitly turned ``api.allow_file_output`` on,+# ``write_file_verified``'s write path (``file_write_verifier.py``) is a+# bare ``open(filepath, mode)`` with no containment: no restriction to a+# configured output directory, no traversal or symlink check. A+# caller-chosen path is written verbatim wherever the server process has+# filesystem access.+#+# A server-side filesystem path posted in a public JSON body is not a+# REST-shaped parameter — same "caller cannot legitimately express this+# safely" rationale as ``_REGISTRY_PARAMS``/``_CALLABLE_PARAMS`` above, just+# for a path instead of a live object, so it is rejected outright rather+# than merely validated early. Only the HTTP body path is affected: the+# in-process Python API is unchanged, and a programmatic caller who trusts+# their own filesystem access can still pass ``output_file=`` directly to+# ``generate_report()``.+_SERVER_PATH_PARAMS = frozenset({"output_file"})++# 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.+# _IDENTITY_PLUMBING_PARAMS, _DEAD_OR_CONFUSING_PARAMS, and+# _SERVER_PATH_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:@@ -378,33 +472,114 @@ _ACCEPTED_BUT_INEFFECTIVE_PARAMS = frozenset({"temperature"})# 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.+# ``output_file`` IS a declared parameter of ``analyze_documents`` too,+# and — like ``programmatic_mode`` above — is now explicitly subtracted+# from ``_ANALYZE_DOCUMENTS_PARAMS`` rather than admitted by the+# allowlist derivation: that endpoint's own write call reaches the+# identical ``write_file_verified`` sink as quick_summary/generate_report+# (see ``_SERVER_PATH_PARAMS`` above and the comment on+# ``_ANALYZE_DOCUMENTS_PARAMS`` itself), so there was no substantive+# reason to leave a third endpoint exposed once the other two were fixed.#-# 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:+# The scope of "traced" below is deliberately narrow: it covers every OTHER+# **kwargs-forwarded key that reaches ``_init_search_system`` from the REST+# body — NOT the full set of keys quick_summary/generate_report accept via+# **kwargs, which is what ``output_file`` above demonstrates. And "traced"+# here means privilege-safe (no host/credential steering, no cross-user+# reach, no audit-trail bypass), NOT type-safe. Three of these are+# confirmed footguns of the exact same *shape* as the now-rejected+# ``progress_callback``: a JSON body can send a value of the wrong scalar+# type, and the first consumer performs an unconditional, un-type-checked+# operation on it that AttributeErrors/TypeErrors — an opaque 500.+# ``model_name``/``search_strategy``/``search_tool`` are therefore+# additionally covered by ``_TYPE_VALIDATED_PARAMS``/+# ``_validate_param_types`` below, so the wrong-type case now gets a clean+# 400 at the boundary instead of reaching that crash. They are not+# rejected outright (unlike ``progress_callback``) because, sent with the+# right type, they are ordinary, legitimate, already-documented knobs:## - ``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.+# ``api_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`` — selects which search engine to use, same+# already-configured-account shape as the two above. It is explicitly+# documented as a public parameter of POST /api/v1/quick_summary in+# ``api_documentation`` above, and was NOT type-validated by the+# original #5533 audit despite having a confirmed footgun of the exact+# same shape: a truthy non-string value (e.g. a list) survives the+# ``search_tool or get_setting_from_snapshot(...)`` fallback in+# ``config/search_config.get_search``, then reaches+# ``retriever_registry.get(name, ...)``+# (``web_search_engines/retriever_registry.py``) — a plain dict+# ``.get()`` call, which raises ``TypeError: unhashable type`` for a+# list, or for a dict that has no ``value`` key, instead of returning+# ``None``. Be precise about the dict case: ``config/search_config.py``+# has an explicit ``isinstance(tool, dict)`` branch that unwraps+# ``tool["value"]``, so ``{"search_tool": {"value": "wikipedia"}}`` was a+# normal 200 before this change and is a 400 after it. Falsy non-strings+# (``0``, ``false``, ``[]``, ``{}``) were likewise omission-equivalent+# 200s via ``research_functions.py``'s ``if not search_tool`` and are+# 400s now. Those spellings are undocumented — the contract is+# ``"search_tool": "Search engine to use"``, a string, and the+# ``{"value": ...}`` form is a settings-snapshot debug shim, not an API+# spelling — so tightening them is intended here, but it IS a behaviour+# change and is called out rather than left for someone to discover.+# Found in post-merge review of this follow-up; added here rather than+# left as another silent gap in a set whose own comment claims+# completeness.#-# ``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.+# ``iterations``/``questions_per_iteration`` are forwarded (see+# ``_init_search_system``'s ``system.max_iterations = iterations`` /+# ``system.questions_per_iteration = questions_per_iteration``) but are+# deliberately NOT in ``_TYPE_VALIDATED_PARAMS``, for the opposite reason+# from ``search_tool`` above: tracing their actual consumer shows there is+# nothing to protect. Both assignments are bare attribute writes with no+# operation performed on the value at that call site, so no JSON type+# whatsoever raises there. And unlike ``max_iterations``/+# ``questions_per_iteration`` passed directly into ``AdvancedSearchSystem``+# (which DO feed ``range(1, self.max_iterations + 1)`` in+# ``advanced_search_system/strategies/focused_iteration_strategy.py``),+# ``_init_search_system`` never passes either kwarg into the+# ``AdvancedSearchSystem(...)`` constructor call above — only the+# post-construction attribute-assignment lines do — and nothing anywhere+# in the tree reads ``system.max_iterations``/``system.questions_per_iteration``+# back out afterward (``report_generator.py`` reads ``strategy.``, not+# ``system.``). ``AdvancedSearchSystem`` instead resolves its own+# ``self.max_iterations``/``self.questions_per_iteration`` from+# ``search.iterations``/``search.questions_per_iteration`` in the settings+# snapshot whenever the constructor argument is ``None`` — which it always+# is here, since ``_init_search_system`` never supplies one. So on the+# REST path (unlike a direct in-process ``AdvancedSearchSystem(...)`` call+# with ``max_iterations=`` set), both are pure no-ops regardless of what a+# caller posts for them — an earlier version of this comment claimed+# ``iterations`` reaches ``range(1, self.max_iterations + 1)`` and crashes+# mid-research on a bad type; that was traced to the wrong constructor+# call and is false. Given that, type-validating ``iterations`` would be+# cosmetic only — no crash exists to prevent, unlike ``model_name``/+# ``search_strategy``/``search_tool`` above — so it is left out rather+# than added for symmetry alone. Both stay forwarded rather than moved+# into ``_ACCEPTED_BUT_INEFFECTIVE_PARAMS`` alongside ``temperature``:+# unlike ``temperature``, neither has a rescue endpoint to point callers+# at (``analyze_documents`` doesn't accept an ``iterations`` parameter at+# all), and popping a kwarg that already does nothing would only change+# whether the research function *sees* an inert value, not any observable+# behavior — so this pass limits itself to correcting the record (this+# comment, the docs strings, the changelog) rather than also changing the+# accepted/forwarded shape. ``search_tool`` is unaffected by any of this —+# it IS read (``config/search_config.get_search``), which is exactly why+# it gets the type check above._REJECTED_BODY_PARAMS = (_REGISTRY_PARAMS| _CALLABLE_PARAMS| _CREDENTIAL_STEERING_PARAMS| _IDENTITY_PLUMBING_PARAMS| _DEAD_OR_CONFUSING_PARAMS+ | _SERVER_PATH_PARAMS)@@ -432,7 +607,8 @@ def _reject_unsafe_body_params(data: Dict[str, Any]) -> Optional[JSONResponse]:"(openai_endpoint_url), are identity/audit plumbing the ""REST path already manages itself ""(research_id/programmatic_mode/research_context/"- "research_mode), or "+ "research_mode), name a server-side filesystem path a "+ "public API body should not control (output_file), or ""have no effect ""when set from the REST path ""(settings/settings_override/api_key/user_password/"@@ -465,6 +641,86 @@ def _pop_ineffective_params(params: Dict[str, Any]) -> list:return warnings+# Forwarded **kwargs keys with a confirmed unconditional, un-type-checked+# operation performed on them by their first consumer (see the+# ``model_name``/``search_strategy``/``search_tool`` bullets in the+# ``_REJECTED_BODY_PARAMS`` comment above for the exact call sites and why+# ``iterations``/``questions_per_iteration`` are deliberately NOT here —+# their consumer is a bare attribute assignment, so no type ever crashes+# there). A JSON body sending the wrong scalar type for one of these three+# reaches that operation and 500s — the same opaque-500 shape+# ``_ANALYZE_DOCUMENTS_PARAMS`` exists to prevent for analyze_documents,+# applied here to the keys on this reject-list path with a confirmed+# footgun rather than every forwarded key speculatively.+_TYPE_VALIDATED_PARAMS: Dict[str, type] = {+ "model_name": str,+ "search_strategy": str,+ "search_tool": str,+}+++# ``model_name``/``search_tool`` treat an explicit JSON ``null`` as+# indistinguishable from omitting the key entirely — both resolve from the+# settings snapshot exactly as if the caller had not sent the key. The two+# reach that outcome by different routes, and the distinction matters if+# either consumer is ever changed:+# - ``model_name``: ``config/llm_config.py``'s ``get_llm`` has an+# explicit ``if model_name is None`` branch.+# - ``search_tool``: control never reaches ``config/search_config.py``'s+# ``get_search`` at all for ``None``. ``research_functions.py``'s+# ``if not search_tool`` resolves ``search.tool`` from the snapshot+# first and skips ``get_search`` entirely when it is unset. (An earlier+# revision of this comment cited ``get_search``'s+# ``search_tool or <fallback>`` as the deciding line; that is the wrong+# frame — the outcome is the same, the mechanism is not.) Both were accepted (200) before this module's type+# validation existed; excluding them here from the type check keeps that+# true instead of turning a documented no-op spelling into a new 400.+# ``search_strategy`` gets no equivalent carve-out: its consumer default+# is the non-None string ``"source_based"`` (``_init_search_system``), so+# an EXPLICIT ``null`` overrides that default with a real ``None`` and+# reaches ``strategy_name.lower()`` (search_system.py) unconditionally —+# that was a genuine pre-existing 500 (not a no-op), and this module's 400+# for it is a real fix, not an over-rejection.+#+# NOTE: this is a type-level fix only. ``model_name: ""`` still passes+# ``isinstance(value, str)``, and an empty string is NOT ``None``, so it+# skips ``get_llm``'s null-sentinel branch entirely, falls through+# ``if model_name: model_name = model_name.strip()...`` unstripped, and+# still hits ``if not model_name or not model_name.strip(): raise+# ValueError(...)`` (config/llm_config.py) — a 500, not a 400. That is a+# separate, pre-existing value-level gap this type-only pass does not+# close.+_NULL_IS_SENTINEL_PARAMS = frozenset({"model_name", "search_tool"})+++def _validate_param_types(data: Dict[str, Any]) -> Optional[JSONResponse]:+ """Reject request-body values whose JSON type cannot survive the+ unconditional operation their first consumer performs on them. See+ ``_TYPE_VALIDATED_PARAMS`` for the covered keys and rationale, and+ ``_NULL_IS_SENTINEL_PARAMS`` for the keys where ``null`` is deliberately+ let through as equivalent to omission rather than treated as a type+ error.++ Returns a 400 ``JSONResponse`` naming every offending key, or ``None``+ when every present key already has an acceptable type.+ """+ errors = []+ for key, expected_type in _TYPE_VALIDATED_PARAMS.items():+ if key not in data:+ continue+ value = data[key]+ if value is None and key in _NULL_IS_SENTINEL_PARAMS:+ continue+ if not isinstance(value, expected_type):+ errors.append(+ f"'{key}' must be a {expected_type.__name__}, got "+ f"{type(value).__name__} instead"+ )+ if errors:+ return JSONResponse({"error": "; ".join(errors)}, status_code=400)+ return None++async def require_api_access(request: Request,username: Annotated[str, Depends(require_auth)],@@ -649,7 +905,7 @@ def api_documentation("parameters": {"query": "Research query (required)","search_tool": "Search engine to use (optional)",- "iterations": "Number of search iterations (optional)",+ "iterations": "Accepted for backward compatibility, but currently has NO observable effect via the REST API: the value is only ever assigned to an attribute nothing reads back, so the research run always uses the account's stored search.iterations setting instead (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)",},@@ -660,7 +916,6 @@ def api_documentation("description": "Generate a comprehensive research report","parameters": {"query": "Research query (required)",- "output_file": "Path to save report (optional)","searches_per_section": "Searches per report section (optional)","model_name": "LLM model to use (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)",@@ -700,9 +955,19 @@ def _load_user_context_into_params(Sets ``username``, ``settings_snapshot``, and (for authenticatedrequests) ``programmatic_mode=False`` so DB-backed rate-limit- estimates persist across requests. Uses ``setdefault`` for- ``programmatic_mode`` so an explicit override in the request body- is respected.+ estimates persist across requests. Still uses ``params.setdefault(...)``+ (not a plain assignment) for ``programmatic_mode`` rather than an+ unconditional overwrite, but on every current caller that distinction+ is now moot: all three REST endpoints reject an explicit+ ``programmatic_mode`` in the request body before this function ever+ runs — quick_summary/generate_report via ``_REJECTED_BODY_PARAMS``+ (400), analyze_documents via its allowlist subtraction in+ ``_ANALYZE_DOCUMENTS_PARAMS`` (400) — so ``params`` never contains the+ key by the time ``setdefault`` runs here, and the request body can no+ longer influence this value at all. ``setdefault`` (rather than a plain+ assignment) is kept anyway so a non-REST caller of this helper that+ pre-populates ``params["programmatic_mode"]`` itself is not silently+ overridden.Returns ``None`` on success. If the settings snapshot cannot be loaded,fails CLOSED: returns a 503 ``JSONResponse`` the endpoint must return to@@ -813,15 +1078,22 @@ async def api_quick_summary(# 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.+ # max_search_results/output_file) 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+ # Cheap type check for the forwarded knobs with a confirmed+ # unconditional operation on them (see _TYPE_VALIDATED_PARAMS): turns+ # an opaque 500 into a clear 400.+ type_error = _validate_param_types(data)+ if type_error is not None:+ return type_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@@ -929,14 +1201,21 @@ async def api_generate_report(# 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.+ # max_search_results/output_file) 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+ # Cheap type check for the forwarded knobs with a confirmed+ # unconditional operation on them — see api_quick_summary and+ # _TYPE_VALIDATED_PARAMS.+ type_error = _validate_param_types(data)+ if type_error is not None:+ return type_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 Truediff --git a/tests/security/test_api_v1_boundary_fastapi.py b/tests/security/test_api_v1_boundary_fastapi.pyindex 5a05d0f332..b2a5d4c161 100644--- a/tests/security/test_api_v1_boundary_fastapi.py+++ b/tests/security/test_api_v1_boundary_fastapi.py@@ -649,9 +649,20 @@ class TestRegistryParamsRejection: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}"+ # The static message TAIL ("They either require a live Python+ # object...") lists every _REJECTED_BODY_PARAMS key, so asserting+ # against it alone would pass for ANY key in the deny-list+ # regardless of which one was actually posted. But the message's+ # dynamic PREFIX ("...REST API: {sorted, comma-joined present+ # keys}.") is built from exactly the keys _reject_unsafe_body_params+ # found in this request's body (see api_v1.py), so asserting that+ # prefix does discriminate a reverted/broken guard from a working+ # one, unlike a bare "error" in resp.json() check.+ expected_prefix = f"REST API: {', '.join(sorted(body_extra))}."+ assert expected_prefix in resp.json()["error"], (+ f"{label}: error must name exactly {sorted(body_extra)}: "+ f"{resp.json()!r}"+ )@pytest.mark.parametrize("label,path,body,target",@@ -746,6 +757,23 @@ class TestUnsafeForwardParamsRejection:(``research_context["context_limit"] = ...``), and a dict value feedscaller-controlled ``username``/``user_password``/query metadata into``TokenCounter``. See ``_IDENTITY_PLUMBING_PARAMS`` in ``api_v1.py``.++ ``output_file`` is a different shape again: a declared parameter of+ ``generate_report`` that names a server-side filesystem path to write+ the finished report to. ``api.allow_file_output`` has no default+ anywhere under ``defaults/``, so it fails closed today - but only+ AFTER the full research-and-report run completes, surfacing as an+ opaque 500 (``FileWriteSecurityError`` isn't special-cased by the+ endpoint's catch-all). And ``file_write_verifier.py``'s write path is a+ bare ``open(filepath, mode)`` with no containment, so an operator who+ has explicitly turned the setting on gets no traversal/symlink+ protection either. A server-side path posted in a public JSON body is+ not a REST-shaped parameter, so it is rejected outright rather than+ validated early. See ``_SERVER_PATH_PARAMS`` in ``api_v1.py``. This+ was NOT covered by the original ``_REJECTED_BODY_PARAMS`` audit+ (which was scoped to keys reaching ``_init_search_system``, and+ ``output_file`` never does) - found and closed in post-merge review of+ PR #5533."""@pytest.mark.parametrize(@@ -774,6 +802,15 @@ class TestUnsafeForwardParamsRejection:{"username": "attacker", "user_password": "not-a-password"},),("research_mode", "attacker-chosen-mode-label"),+ # output_file: a server-side filesystem path is not a+ # REST-shaped parameter (see _SERVER_PATH_PARAMS in api_v1.py).+ # Regression test for the completeness-claim gap found in+ # post-merge review of #5533: the reject-list's original+ # docstring claimed to be "the full class" for+ # quick_summary/generate_report but this key, forwarded+ # straight to generate_report's own write-to-disk path, was+ # never in it.+ ("output_file", "/tmp/pwned-by-api-boundary-test.md"),],)def test_rejects_unsafe_forward_params_with_400(@@ -793,9 +830,13 @@ class TestUnsafeForwardParamsRejection: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}"+ # The static message TAIL lists every _REJECTED_BODY_PARAMS key+ # (so a bare "key in error" substring check would pass regardless+ # of which key was actually posted), but the dynamic PREFIX names+ # exactly the keys _reject_unsafe_body_params found present in this+ # request — asserting it does discriminate a reverted/broken guard.+ assert f"REST API: {key}." in resp.json()["error"], (+ f"{label}/{key}: error must name {key!r}: {resp.json()!r}")@pytest.mark.parametrize(@@ -819,19 +860,27 @@ class TestUnsafeForwardParamsRejection:``TestUnsafeForwardParamsRejection``'s docstring), just no longer a400 — 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+ behavior specifically.++ ``search_tool``/``model_name``/``search_strategy`` 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-configuredprovider/model/strategy — no host or credential steering, unlike- ``openai_endpoint_url``.+ ``openai_endpoint_url``. These three are also type-validated (see+ ``TestForwardedParamTypeValidation``).++ ``iterations``/``questions_per_iteration`` are real 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's call site — but that is as far as it goes:+ both are pure no-ops one level below this mock (see+ ``TestForwardedParamTypeValidation``'s docstring for the traced+ reason), so this test intentionally does not claim they have any+ further observable effect, only that the boundary doesn't+ collaterally strip or reject them."""client, _username = _api_user(live_app)@@ -858,6 +907,193 @@ class TestUnsafeForwardParamsRejection:assert research_fn.call_args.kwargs["questions_per_iteration"] == 2+class TestForwardedParamTypeValidation:+ """Coverage area 2: wrong-scalar-type guard for confirmed footguns.++ ``model_name``/``search_strategy``/``search_tool`` are forwarded, live,+ documented knobs (see ``test_clean_request_with_documented_params_still_+ succeeds`` above) - correctly not rejected outright. But each one is+ handed, with no type check, to an unconditional operation on its first+ consumer: ``model_name.strip()`` in ``config/llm_config.py``,+ ``search_strategy.lower()`` in ``search_system.py``, and (once a+ truthy value survives the ``search_tool or get_setting_from_snapshot``+ fallback) ``retriever_registry.get(name, ...)`` -> a plain dict+ ``.get()`` in ``web_search_engines/retriever_registry.py``. A JSON body+ sending the wrong scalar type for any of these previously reached that+ operation and raised an unhandled ``AttributeError``/``TypeError`` - an+ opaque 500. ``_validate_param_types`` in ``api_v1.py`` catches the+ wrong type at the boundary instead, with a 400 naming the offending+ key(s).++ ``iterations`` is NOT covered here (found in post-merge review of PR+ #5533, then corrected in a further post-merge review pass): its only+ consumer on the REST path is ``system.max_iterations = iterations`` in+ ``research_functions.py`` - a bare attribute assignment with no+ operation performed on the value, so no JSON type ever crashes there.+ An earlier version of this module claimed ``iterations`` reaches+ ``range(1, self.max_iterations + 1)`` in+ ``focused_iteration_strategy.py`` and crashes mid-research on a bad+ type; that traced to the wrong constructor call+ (``AdvancedSearchSystem`` is built WITHOUT ``max_iterations`` in+ ``_init_search_system``, so that strategy resolves its iteration count+ from the settings snapshot instead, never from this kwarg) and is+ false - ``iterations`` is a pure no-op on the REST path regardless of+ type. See ``TestUnsafeForwardParamsRejection.+ test_clean_request_with_documented_params_still_succeeds`` for proof it+ is still accepted and forwarded unchanged (that no-op behavior is+ itself unaffected by this fix).+ """++ @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",+ [+ ("model_name", 123),+ ("search_strategy", 5),+ ("search_tool", ["searxng"]),+ ("search_tool", {"tool": "searxng"}),+ ],+ ids=[+ "model_name-int",+ "search_strategy-int",+ "search_tool-list",+ "search_tool-dict",+ ],+ )+ def test_wrong_type_is_rejected_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]}"+ )+ assert research_fn.call_count == 0, (+ f"{label}/{key}: a wrong-typed param reached the research function"+ )+ assert key in resp.json()["error"], (+ f"{label}/{key}: error must name {key!r}: {resp.json()!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_correctly_typed_values_still_succeed(+ self, live_app, label, path, target+ ):+ """Positive control: the type guard doesn't collaterally reject+ correctly-typed values for the same keys (``iterations`` included,+ even though it is not type-validated - see the class docstring)."""+ 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,+ "model_name": "gpt-4o-mini",+ "search_strategy": "source_based",+ "search_tool": "wikipedia",+ "iterations": 3,+ },+ )++ assert resp.status_code == 200, f"{label}: {resp.text[:400]}"+ 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["search_tool"] == "wikipedia"+ assert research_fn.call_args.kwargs["iterations"] == 3++ @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",+ ["model_name", "search_tool"],+ )+ def test_null_is_let_through_for_none_as_sentinel_params(+ self, live_app, label, path, target, key+ ):+ """``{"model_name": null}`` / ``{"search_tool": null}`` were 200+ before this module's type validation existed - both reach a+ ``param or <fallback>`` / ``if param is None: <fallback>`` branch+ in their consumer and resolve from the settings snapshot exactly as+ if the key had been omitted (``config/llm_config.get_llm`` for+ ``model_name``; ``config/search_config.get_search`` for+ ``search_tool``, reached via ``research_functions.py``'s own+ ``if search_tool:`` guard). A blanket ``isinstance`` check would+ have turned that documented no-op spelling into a new 400; see+ ``_NULL_IS_SENTINEL_PARAMS`` in api_v1.py.+ """+ 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: None})++ assert resp.status_code == 200, (+ f"{label}/{key}: null must be let through as the sentinel "+ f"for 'use the stored setting', got {resp.status_code} / "+ f"{resp.text[:300]}"+ )+ assert research_fn.call_args.kwargs[key] is None++ @pytest.mark.parametrize(+ "label,path,target",+ [+ ("quick_summary", QUICK_SUMMARY_PATH, QUICK_SUMMARY_TARGET),+ ("generate_report", GENERATE_REPORT_PATH, GENERATE_REPORT_TARGET),+ ],+ )+ def test_null_search_strategy_is_still_rejected(+ self, live_app, label, path, target+ ):+ """``search_strategy`` gets NO null carve-out, unlike ``model_name``/+ ``search_tool`` above: its consumer default is the non-None string+ ``"source_based"`` (``_init_search_system``), so an EXPLICIT+ ``null`` overrides that default with a real ``None`` and reaches+ ``strategy_name.lower()`` (search_system.py) unconditionally. That+ was a genuine pre-existing 500 - not a documented no-op - so this+ module's 400 for it is a real fix, not an over-rejection (the one+ case in this whole audit where the null-related behavior change is+ an improvement rather than a regression).+ """+ 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, "search_strategy": None}+ )++ assert resp.status_code == 400, (+ f"{label}: expected a 400 for null search_strategy, got "+ f"{resp.status_code} / {resp.text[:300]}"+ )+ assert research_fn.call_count == 0++class TestIneffectiveButAcceptedParams:"""Coverage area 2: ``temperature`` is a documented no-op, not a 400.@@ -1049,6 +1285,53 @@ class TestAnalyzeDocumentsParameterInjection:f"{injected} must never be advertised as caller-settable")+ def test_output_file_is_rejected_like_the_other_two_endpoints(+ self, live_app+ ):+ """``output_file`` IS a genuine declared parameter of+ ``analyze_documents`` (unlike ``username``/``settings_snapshot``+ above), so - like ``programmatic_mode`` - it would otherwise+ survive the signature-derived allowlist untouched.++ ``analyze_documents`` (research_functions.py) reaches the same+ ``write_file_verified`` -> bare ``open(filepath, mode)`` sink as+ ``generate_report`` (see ``_SERVER_PATH_PARAMS`` in api_v1.py),+ behind the same unset-by-default ``api.allow_file_output`` gate and+ the same opaque catch-all 500 when that gate is closed. A prior+ version of this module reported that gap without closing it,+ reasoning it was "separately-scoped"; that reasoning did not+ survive review - the fix is the same one-token subtraction from+ ``_ANALYZE_DOCUMENTS_PARAMS`` already used for+ ``programmatic_mode``. Regression test for that fix.+ """+ client, _username = _api_user(live_app)++ with patch(ANALYZE_DOCUMENTS_TARGET) as research_fn:+ research_fn.return_value = {"summary": "fine", "findings": []}+ resp = _post(+ client,+ ANALYZE_DOCUMENTS_PATH,+ {+ "query": QUERY,+ "collection_name": COLLECTION,+ "output_file": "/tmp/pwned-by-analyze-documents-test.md",+ },+ )++ assert resp.status_code == 400, (+ f"output_file in the body must be rejected, got "+ f"{resp.status_code} / {resp.text[:300]}"+ )+ assert research_fn.call_count == 0, (+ "output_file from the request body reached analyze_documents"+ )+ data = resp.json()+ assert "output_file" in data["error"]+ assert "output_file" not in data["allowed_parameters"], (+ "output_file must never be advertised as caller-settable on "+ "analyze_documents"+ )+class TestErrorScrubWiring:"""Coverage area 3: the endpoint invokes the CWE-209 scrub."""diff --git a/tests/web/routers/test_api_v1_external_contract.py b/tests/web/routers/test_api_v1_external_contract.pyindex cccbfa0805..a6d7b3284c 100644--- a/tests/web/routers/test_api_v1_external_contract.py+++ b/tests/web/routers/test_api_v1_external_contract.py@@ -706,10 +706,16 @@ class TestAnalyzeDocumentsUnknownParameterBody:# ``_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.+ # ``output_file`` is ALSO deliberately excluded, for the same reason it+ # is rejected on quick_summary/generate_report (see+ # ``_SERVER_PATH_PARAMS`` in api_v1.py): analyze_documents reaches the+ # identical bare-``open()`` ``write_file_verified`` sink, so a+ # server-side filesystem path is not a REST-shaped parameter here+ # either. Deliberate contract change from post-merge review of this+ # follow-up — do not add output_file back to make this pass.ALLOWED = ["force_reindex","max_results",- "output_file","temperature",]@@ -922,9 +928,14 @@ class TestApiDocumentationPayload:"allow_default_settings","temperature",}+ # ``output_file`` is deliberately NOT advertised here: this+ # follow-up rejects it with a 400 on generate_report (see+ # _SERVER_PATH_PARAMS in api_v1.py) rather than merely+ # documenting the risk, so it must not appear as an accepted+ # parameter any more. This is a deliberate contract change, not+ # an oversight — do not add output_file back to make this pass.assert set(by_path["/api/v1/generate_report"]["parameters"]) == {"query",- "output_file","searches_per_section","model_name","allow_default_settings",diff --git a/tests/web/routers/test_api_v1_real_call_path.py b/tests/web/routers/test_api_v1_real_call_path.pyindex 63d5c63f6d..c5da5fb896 100644--- a/tests/web/routers/test_api_v1_real_call_path.py+++ b/tests/web/routers/test_api_v1_real_call_path.py@@ -328,58 +328,39 @@ class TestAnalyzeDocumentsRealCallPath:f"document content missing from LLM prompt: {doc['content']!r}")- def test_output_file_branch_hands_the_users_snapshot_to_the_gate(+ def test_output_file_is_rejected_before_the_research_function_runs(self, live_app, tmp_path):- """When ``output_file`` is supplied, ``analyze_documents`` calls- ``write_file_verified`` to enforce ``api.allow_file_output``. The- USER'S snapshot must reach it, or the file-output gate silently- falls back to JSON defaults / env vars — i.e. it stops honouring the- setting the user actually chose.-- This is the file-write third of the four coordinated threadings- (signature -> get_llm -> get_search -> write_file_verified); the- other tests in this class never take this branch.+ """``output_file`` used to reach ``analyze_documents`` -> the same+ bare-``open()`` ``write_file_verified`` sink as generate_report,+ behind the same unset-by-default ``api.allow_file_output`` gate.+ Post-merge review of this follow-up found that gap and closed it+ the same way as generate_report/quick_summary: ``output_file`` is+ now subtracted from ``_ANALYZE_DOCUMENTS_PARAMS`` (api_v1.py) and+ rejected with a 400 at the REST boundary, before ``get_llm``/+ ``get_search`` — and therefore analyze_documents' own body — ever+ run. This supersedes the old version of this test, which asserted+ the (now-unreachable) 200 success path threaded the user's+ snapshot into ``write_file_verified``."""- client, username = _api_user(live_app)- _plant_tracer(username)- write_call = {}-- def _capture_write(*args, **kwargs):- write_call["args"] = args- write_call["kwargs"] = kwargs+ client, _username = _api_user(live_app)- response, _llm, _search = _post_analyze_documents(+ response, llm, search = _post_analyze_documents(client,extra_body={"output_file": str(tmp_path / "analysis.md")},- extra_patches=[- patch(- "local_deep_research.security.file_write_verifier."- "write_file_verified",- side_effect=_capture_write,- )- ],)- assert response.status_code == 200, response.text[:600]- assert write_call, (- "write_file_verified was not called — analyze_documents skipped "- "the output_file branch entirely."- )- snapshot = write_call["kwargs"].get("settings_snapshot")- assert snapshot is not None, (- "write_file_verified got settings_snapshot=None — the user's "- "api.allow_file_output setting is ignored on the file-write "- "branch."- )- assert TRACER_MARKER in snapshot, (- "the snapshot reaching write_file_verified is not the caller's "- f"own: {sorted(snapshot)[:10]}"- )- assert "api.allow_file_output" in write_call["args"], (- "write_file_verified called without the 'api.allow_file_output' "- f"setting key. args: {write_call['args']!r}"+ assert response.status_code == 400, response.text[:600]+ assert response.json()["allowed_parameters"] == sorted(+ {"force_reindex", "max_results", "temperature"}+ ), (+ "output_file must not be advertised as an accepted "+ "analyze_documents parameter any more")+ # The rejection happens before analyze_documents (and therefore the+ # stubbed get_llm/get_search) is ever reached.+ llm.invoke.assert_not_called()+ search.run.assert_not_called()def _post_generate_report(client, body=None):