~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(security): scrub exception data at API boundary + close pending CVEs (#5032)
LearningCircuita2bf7a80af84
diff --git a/.grype.yaml b/.grype.yamlindex 9560bbe6df..1034f64325 100644--- a/.grype.yaml+++ b/.grype.yaml@@ -141,24 +141,60 @@ ignore:reason: "Heap overflow in Media. Playwright 1.58 bundles pre-fix Chromium. Headless scraping only."# ==========================================================================- # NODE.JS (patchright-bundled Node 24.15.0 at patchright/driver/node)- # Fixed in Node 24.17.0 (2026-06-18 security release). patchright 1.60.0- # (latest on PyPI, 2026-06-03) predates the fix and still bundles Node- # 24.15.0. patchright is a transitive dep of crawl4ai; our Python code never- # invokes patchright's driver/node, and the production image does not install+ # NODE.JS (patchright-bundled Node 24.16.0 at patchright/driver/node)+ # All fixed in Node 24.17.0 (2026-06-18 security release). patchright 1.61.2+ # (latest on PyPI as of 2026-07-09) predates the fix and bundles Node 24.16.0.+ # patchright is a transitive dep of crawl4ai; the driver/node binary is not+ # invoked in the default configuration (web.enable_javascript_rendering+ # defaults to false), and the production image does not install# Playwright/patchright browsers (see Dockerfile note at the ldr stage), so# the bundled driver/node is dead weight. Auto-resolves when patchright ships# a rebuild with Node 24.17.0+.+ # Severities in the reasons below are the Node.js/GHSA vendor CVSS ratings.+ # GitHub's Grype alerts show NVD's context-free auto-scores for some of+ # them (CVE-2026-48930 "Critical" 9.8, CVE-2026-48615 / -48619 "High" 7.5);+ # the vendor ratings are the authoritative ones — the suppressions are not+ # downplaying the alerts.+ # Entries are scoped to the bundled binary (package: node, type: binary) —+ # matching the Chromium block above — so the same CVE ID on an unrelated+ # future node package would not be silently suppressed.# (The earlier Node 24.13.0 entries — CVE-2026-21710 / -21712..-21717 — were- # fixed in Node 24.14.1, which the bundled 24.15.0 supersedes, so they no- # longer match and were removed.)+ # fixed in Node 24.14.1, which the bundled 24.15.0/24.16.0 supersedes, so+ # they no longer match and were removed.)# ==========================================================================+ - vulnerability: CVE-2026-48933+ package: { name: node, type: binary }+ reason: "High WebCrypto AES DoS (subtle.encrypt() input multiple of 2 GiB crashes the process) in Node <24.17.0. Browser-driver node is not invoked in default config. Patchright-bundled driver/node 24.16.0; fixed in Node 24.17.0."+ - vulnerability: CVE-2026-48618+ package: { name: node, type: binary }+ reason: "High TLS wildcard-depth authentication bypass via unicode dot-separator normalisation mismatch in Node <24.17.0. Browser-driver node is not invoked in default config. Patchright-bundled driver/node 24.16.0; fixed in Node 24.17.0."+ - vulnerability: CVE-2026-48615+ package: { name: node, type: binary }+ reason: "Medium proxy-credentials leak in ERR_PROXY_TUNNEL error messages in Node <24.17.0. Browser-driver node is never launched with proxy URLs. Patchright-bundled driver/node 24.16.0; fixed in Node 24.17.0."+ - vulnerability: CVE-2026-48619+ package: { name: node, type: binary }+ reason: "Medium HTTP/2 client OOM via attacker-controlled ORIGIN frames in Node <24.17.0. Exploitable only when the node process is an HTTP/2 client against an attacker-positioned server; browser-driver node never acts as one. Patchright-bundled driver/node 24.16.0; fixed in Node 24.17.0."+ - vulnerability: CVE-2026-48928+ package: { name: node, type: binary }+ reason: "Medium mTLS authorisation bypass via case-sensitive SNI context matching in Node <24.17.0. Browser-driver node is not invoked in default config. Patchright-bundled driver/node 24.16.0; fixed in Node 24.17.0."+ - vulnerability: CVE-2026-48930+ package: { name: node, type: binary }+ reason: "Medium TLS hostname rebinding via embedded-NUL C-string truncation in resolver bindings in Node <24.17.0. Browser-driver node is not invoked in default config. Patchright-bundled driver/node 24.16.0; fixed in Node 24.17.0."+ - vulnerability: CVE-2026-48934+ package: { name: node, type: binary }+ reason: "Medium TLS host-identity verification bypass via session reuse with different servername in Node <24.17.0. Browser-driver node is not invoked in default config. Patchright-bundled driver/node 24.16.0; fixed in Node 24.17.0."+ - vulnerability: CVE-2026-48935+ package: { name: node, type: binary }+ reason: "Low Permission Model bypass via FileHandle.utimes() promises API in Node <24.17.0. Requires --permission opt-in; browser-driver node is never launched with it. Patchright-bundled driver/node 24.16.0; fixed in Node 24.17.0."- vulnerability: CVE-2026-48937- reason: "Medium HTTP/2 server DoS (server keeps accepting data after GOAWAY/RST) in Node <24.17.0. Exploitable only against a running Node.js HTTP/2 server; patchright's browser-driver node never starts one. Patchright-bundled driver/node 24.15.0; never invoked in prod."+ package: { name: node, type: binary }+ reason: "Medium HTTP/2 server DoS (server keeps accepting data after GOAWAY/RST) in Node <24.17.0. Exploitable only against a running Node.js HTTP/2 server; patchright's browser-driver node never starts one. Patchright-bundled driver/node 24.16.0; not invoked in default config."- vulnerability: CVE-2026-48617- reason: "Low Permission Model bypass via process.report.writeReport() in Node <24.17.0. Requires the process to opt into Node's experimental --permission model; the browser-driver node is never launched with it. Patchright-bundled driver/node 24.15.0; never invoked in prod."+ package: { name: node, type: binary }+ reason: "Low Permission Model bypass via process.report.writeReport() in Node <24.17.0. Requires the process to opt into Node's experimental --permission model; the browser-driver node is never launched with it. Patchright-bundled driver/node 24.16.0; not invoked in default config."- vulnerability: CVE-2026-48931- reason: "Low (CVSS 3.7) TOCTOU race in Node's http.Agent (HTTP response queue poisoning) in Node <24.17.0. Exploitable only when the node process acts as an HTTP client against an attacker-positioned server; patchright's browser-driver node is never invoked in prod. Patchright-bundled driver/node 24.15.0; fixed in Node 24.17.0."+ package: { name: node, type: binary }+ reason: "Low (CVSS 3.7) TOCTOU race in Node's http.Agent (HTTP response queue poisoning) in Node <24.17.0. Exploitable only when the node process acts as an HTTP client against an attacker-positioned server; patchright's browser-driver node is not invoked in default config. Patchright-bundled driver/node 24.16.0; fixed in Node 24.17.0."# ==========================================================================# NO FIX AVAILABLE IN DEBIAN TRIXIEdiff --git a/Dockerfile b/Dockerfileindex 25929f6909..46aa776665 100644--- a/Dockerfile+++ b/Dockerfile@@ -63,7 +63,10 @@ RUN apt-get update -o Acquire::Retries=3 && apt-get upgrade -y -o Acquire::Retri# already verified, and we re-pin to a CVE-fixed version immediately. The# three resulting Scorecard alerts (#7740, #7741, #7742) are dismissed as# won't-fix; revisit if a stable hash-locking workflow becomes available.-RUN pip3 install --no-cache-dir pip==26.1 \+# Note: the 26.1.2 bump fixes CVE-2026-8643 (path traversal via malicious+# entry point name in wheel installation); CVE-2026-1703 (fixed in 26.0) and+# GHSA-jp4c-xjxw-mgf9 (fixed in 26.1) were already covered by the prior pin.+RUN pip3 install --no-cache-dir pip==26.1.2 \&& pip install --no-cache-dir pdm==2.26.2 "hishel<1.0.0" playwright==1.58.0 "wheel>=0.46.2"# disable update checkENV PDM_CHECK_UPDATE=false@@ -261,10 +264,12 @@ SHELL ["/bin/bash", "-o", "pipefail", "-c"]ARG DEBIAN_FRONTEND=noninteractive-# Upgrade pip to fix CVE-2026-1703 (malicious wheel extraction) + GHSA-jp4c-xjxw-mgf9+# Pin pip past CVE-2026-8643 (path traversal via malicious entry point name+# in wheel install); also covers the older CVE-2026-1703 / GHSA-jp4c-xjxw-mgf9+# fixes (26.0 / 26.1).# See builder-stage rationale above for why this install is not hash-pinned# — Scorecard alert #7742 dismissed as won't-fix on the same basis.-RUN pip3 install --no-cache-dir pip==26.1+RUN pip3 install --no-cache-dir pip==26.1.2# Install runtime dependencies for SQLCipher and WeasyPrint.# `apt-get upgrade -y` is INTENTIONAL — see rationale on the builder-basediff --git a/changelog.d/+cwe-209-error-sanitization.security.md b/changelog.d/+cwe-209-error-sanitization.security.mdnew file mode 100644index 0000000000..1471fab2f8--- /dev/null+++ b/changelog.d/+cwe-209-error-sanitization.security.md@@ -0,0 +1 @@+Exception-derived strings flowing through the `/api/v1/quick_summary` and `/api/v1/analyze_documents` JSON responses are now scrubbed at the HTTP boundary (and at the strategy layer in `SourceBasedSearchStrategy`) via `sanitize_error_for_client`, closing a CWE-209 information-exposure vector flagged by CodeQL (#8019): a caught exception interpolated into a strategy's error fields could otherwise reach the API client — as `summary` (the key `quick_summary()`/`analyze_documents()` actually return), `formatted_findings`, or per-finding `content` — with credentials or stack-trace text intact. Credentials are scrubbed and length is capped; the `"Error: "` prefix is preserved so error payloads stay recognizable to clients, and the strategy-layer scrub independently covers the web-UI SSE path (`research_service.py` → `ErrorReportGenerator`), which consumes strategy output directly. `/api/v1/generate_report` gets the same boundary scrub purely as a precaution — its current payload (`content`/`metadata`) carries no error fields.diff --git a/src/local_deep_research/advanced_search_system/strategies/source_based_strategy.py b/src/local_deep_research/advanced_search_system/strategies/source_based_strategy.pyindex 11d1658597..2406b2ee02 100644--- a/src/local_deep_research/advanced_search_system/strategies/source_based_strategy.py+++ b/src/local_deep_research/advanced_search_system/strategies/source_based_strategy.py@@ -6,6 +6,7 @@ from ...citation_handler import CitationHandler# LLM and search instances should be passed via constructor, not imported# Removed get_db_setting import - using settings_snapshot instead+from ...security.log_sanitizer import sanitize_error_for_clientfrom ...utilities.thread_context import (preserve_research_context,get_search_context,@@ -517,10 +518,23 @@ class SourceBasedSearchStrategy(BaseSearchStrategy):)except Exception as e:- error_msg = f"Error in research process: {e!s}"- logger.exception(error_msg)- synthesized_content = f"Error: {e!s}"- formatted_findings = f"Error: {e!s}"+ # Log the full exception server-side; only a scrubbed summary+ # goes into the user-facing fields. sanitize_error_for_client+ # strips credentials and caps length so {e!s} cannot leak+ # secrets or long stack-trace text to the API client (CWE-209,+ # CodeQL #8019). The "Error: " prefix is preserved because+ # research_service.py:startswith("Error:") routes such strings+ # through ErrorReportGenerator for friendly rendering.+ logger.exception("Error in research process")+ # max_length=500 aligns with _TOOL_ERROR_MAX_LEN+ # (langgraph_agent_strategy.py) and _ERROR_BOUNDARY_MAX_LEN+ # (web/api.py): the 200-char default would truncate+ # categorizable tokens (e.g. "Connection refused" past char+ # 200) here, before the boundary's more generous cap could+ # preserve them for ErrorReportGenerator classification.+ safe_msg = sanitize_error_for_client(str(e), max_length=500)+ synthesized_content = f"Error: {safe_msg}"+ formatted_findings = f"Error: {safe_msg}"finding = {"phase": "Error","content": synthesized_content,diff --git a/src/local_deep_research/web/api.py b/src/local_deep_research/web/api.pyindex 45166a9e2b..2be52ca647 100644--- a/src/local_deep_research/web/api.py+++ b/src/local_deep_research/web/api.py@@ -21,6 +21,7 @@ from loguru import loggerfrom ..api.research_functions import analyze_documentsfrom ..database.session_context import get_user_db_sessionfrom ..security.decorators import require_json_body+from ..security.log_sanitizer import sanitize_error_for_clientfrom ..utilities.db_utils import get_settings_managerfrom ..security.rate_limiter import (API_RATE_LIMIT_DEFAULT,@@ -28,6 +29,44 @@ from ..security.rate_limiter import (get_current_username,)+# Match the largest strategy-layer cap (_TOOL_ERROR_MAX_LEN = 500 in+# langgraph_agent_strategy.py) at the HTTP boundary so a message already+# scrubbed at the strategy layer is never re-truncated here, and+# categorizable exception tokens (e.g. "Connection refused" sitting deep+# in a long error) survive to the API client. The 200-char default of+# sanitize_error_for_client would truncate that signal prematurely.+_ERROR_BOUNDARY_MAX_LEN = 500+++def _scrub_error_fields(results: Dict[str, Any]) -> None:+ """In-place defense-in-depth scrub for exception-derived fields about+ to leave via jsonify (CWE-209, CodeQL #8019).++ Strategy-layer `_scrub_tool_error`/`sanitize_error_for_client` already+ wraps exception text at the source; this is the final HTTP boundary.+ Only fires on fields that start with the literal ``"Error:"`` marker+ so legitimate research prose is never touched, and truncation is from+ the tail so the marker survives the scrub.++ Field names: strategies emit error text into ``current_knowledge``,+ but ``quick_summary()`` (research_functions.py) returns that value+ under the key ``summary`` — and ``analyze_documents()`` uses+ ``summary`` as well — so both spellings are scrubbed here.+ """+ for field in ("current_knowledge", "summary", "formatted_findings"):+ value = results.get(field)+ if isinstance(value, str) and value.startswith("Error:"):+ results[field] = sanitize_error_for_client(+ value, max_length=_ERROR_BOUNDARY_MAX_LEN+ )+ for finding in results.get("findings", []):+ content = finding.get("content")+ if isinstance(content, str) and content.startswith("Error:"):+ finding["content"] = sanitize_error_for_client(+ content, max_length=_ERROR_BOUNDARY_MAX_LEN+ )++# Create a blueprint for the APIapi_blueprint = Blueprint("api_v1", __name__, url_prefix="/api/v1")@@ -325,6 +364,10 @@ def _serialize_results(results: Dict[str, Any]) -> Response:"content": document.page_content,}+ # CWE-209 / CodeQL #8019: scrub exception-derived fields before+ # jsonify. See _scrub_error_fields for rationale.+ _scrub_error_fields(converted_results)+return jsonify(converted_results)@@ -496,6 +539,15 @@ def api_generate_report():result["content"] = content_previewresult["content_truncated"] = True+ # CWE-209 / CodeQL #8019: same boundary scrub as _serialize_results.+ # generate_report bypasses that helper, so apply _scrub_error_fields+ # directly. NOTE: today's payload ({content, metadata, file_path})+ # contains none of the scrubbed field names — exceptions propagate+ # to the generic handlers below instead — so this is purely+ # precautionary: it keeps the every-jsonify-sink boundary policy+ # intact if the payload shape ever grows error-carrying fields.+ _scrub_error_fields(result)+return jsonify(result)except TimeoutError:logger.exception("Request timed out")@@ -582,6 +634,11 @@ def api_analyze_documents():if error is not None:return errorresult = analyze_documents(query, collection_name, **params)+ # CWE-209 / CodeQL #8019: same boundary scrub as _serialize_results.+ # The live field here is `summary` (analyze_documents returns+ # {summary, documents, ...} and puts "Error: ..." text in summary,+ # e.g. the unknown-collection message).+ _scrub_error_fields(result)return jsonify(result)except Exception:logger.exception("Error in analyze_documents API")diff --git a/tests/strategies/test_strategy_analyze_topic.py b/tests/strategies/test_strategy_analyze_topic.pyindex 9e8a93fcc4..be23460933 100644--- a/tests/strategies/test_strategy_analyze_topic.py+++ b/tests/strategies/test_strategy_analyze_topic.py@@ -403,6 +403,78 @@ class TestErrorHandling:# Some strategies may propagate the errorlogger.warning(f"{strategy_name} propagated error: {e}")+ def test_source_based_scrubs_exception_text_from_error_fields(+ self,+ strategy_mock_llm,+ strategy_settings_snapshot,+ ):+ """CWE-209 / CodeQL #8019 regression guard: the except block in+ SourceBasedSearchStrategy must run exception text through+ sanitize_error_for_client before it lands in the client-visible+ current_knowledge / formatted_findings / finding-content fields.++ Unlike test_handles_search_exception above, a failure here fails+ the test — no try/except softening — so a regression to raw+ ``f"Error: {e!s}"`` (or a crash inside the except block) is+ caught.++ A search-level exception never reaches that except block (the+ per-question search path swallows it into a "No sources were+ found" summary), so the failure is injected at+ ``findings_repository.format_findings_to_text`` — called inside+ the guarded block right before the return.+ """+ from local_deep_research.search_system_factory import (+ create_strategy,+ )++ secret = "sk-STRATEGYLEAK123456789012"+ mock_search = Mock()+ mock_search.run = Mock(+ return_value=[+ {+ "title": "Result",+ "link": "https://example.com/1",+ "snippet": "A result snippet",+ }+ ]+ )+ mock_search.include_full_content = True++ strategy = create_strategy(+ strategy_name="source-based",+ model=strategy_mock_llm,+ search=mock_search,+ settings_snapshot=strategy_settings_snapshot,+ )+ # The categorizable token sits past char 200 of the scrubbed+ # message: it must survive the strategy-layer cap (500, aligned+ # with _ERROR_BOUNDARY_MAX_LEN / _TOOL_ERROR_MAX_LEN). With+ # sanitize_error_for_client's 200-char default it would be+ # truncated away before the API boundary ever sees it.+ padding = "x" * 230+ strategy.findings_repository.format_findings_to_text = Mock(+ side_effect=Exception(+ f"401 Unauthorized: https://api.example.com/v1?api_key={secret}"+ f" {padding} Connection refused [Errno 111]"+ )+ )++ result = strategy.analyze_topic("Test query")++ assert result["current_knowledge"].startswith("Error:")+ assert result["formatted_findings"].startswith("Error:")+ assert secret not in result["current_knowledge"]+ assert secret not in result["formatted_findings"]+ assert "Connection refused" in result["current_knowledge"]+ error_contents = [+ f["content"]+ for f in result["findings"]+ if isinstance(f, dict) and isinstance(f.get("content"), str)+ ]+ assert error_contents, "expected at least one finding with content"+ assert all(secret not in content for content in error_contents)+class TestSearchSystemIntegration:"""Test analyze_topic through AdvancedSearchSystem."""diff --git a/tests/web/test_api_coverage.py b/tests/web/test_api_coverage.pyindex 3116ad61e4..0b453ae31e 100644--- a/tests/web/test_api_coverage.py+++ b/tests/web/test_api_coverage.py@@ -545,6 +545,50 @@ class TestQuickSummary:)assert resp.status_code == 200+ def test_error_summary_scrubbed_end_to_end(self, authed_client):+ # CWE-209 / CodeQL #8019: drive the real route with the real+ # quick_summary payload shape (error text arrives under `summary`,+ # NOT `current_knowledge`) and assert the boundary scrub fires on+ # what the client actually receives.+ leaked = (+ "Error: LLM call failed: "+ "https://api.example.com/v1?api_key=sk-ENDTOEND1234567890AB"+ )+ mock_result = {+ "research_id": "abc-123",+ "summary": leaked,+ "findings": [{"phase": "Error", "content": leaked}],+ "iterations": 0,+ "questions": {},+ "formatted_findings": leaked,+ "sources": [],+ }+ with _mock_access_control():+ with patch(+ "local_deep_research.api.research_functions.quick_summary",+ return_value=mock_result,+ ):+ with patch(+ "local_deep_research.web.api.get_user_db_session"+ ) as inner_ctx:+ inner_ctx.return_value.__enter__ = MagicMock(+ return_value=None+ )+ inner_ctx.return_value.__exit__ = MagicMock(+ return_value=None+ )+ resp = authed_client.post(+ "/api/v1/quick_summary", json={"query": "test"}+ )+ assert resp.status_code == 200+ data = resp.get_json()+ for field in ("summary", "formatted_findings"):+ assert "sk-ENDTOEND1234567890AB" not in data[field]+ assert data[field].startswith("Error:")+ content = data["findings"][0]["content"]+ assert "sk-ENDTOEND1234567890AB" not in content+ assert content.startswith("Error:")+def test_timeout_returns_504(self, authed_client):with _mock_access_control():with patch(@@ -1108,6 +1152,28 @@ class TestAnalyzeDocuments:assert resp.status_code == 200assert resp.get_json() == mock_result+ def test_error_summary_scrubbed_end_to_end(self, authed_client):+ # CWE-209 / CodeQL #8019: analyze_documents puts "Error: ..." text+ # in `summary` (its real payload field) — assert the boundary+ # scrub fires on the actual route response.+ leaked = (+ "Error: collection lookup failed: "+ "https://db.example.com:5432/db?password=supersecret123"+ )+ with _mock_access_control():+ with patch(+ "local_deep_research.web.api.analyze_documents",+ return_value={"summary": leaked, "documents": []},+ ):+ resp = authed_client.post(+ "/api/v1/analyze_documents",+ json={"query": "q", "collection_name": "papers"},+ )+ assert resp.status_code == 200+ data = resp.get_json()+ assert "supersecret123" not in data["summary"]+ assert data["summary"].startswith("Error:")+def test_extra_params_forwarded(self, authed_client):with _mock_access_control():with patch(@@ -1954,6 +2020,160 @@ class TestSerializeResults:# Original list should still contain the mock objectassert original_findings[0]["documents"][0] is not None+ # -- CWE-209 / CodeQL #8019: scrub exception-derived fields at the+ # HTTP boundary so credentials and stack-trace text cannot leak via+ # the API path (which bypasses the web-UI ErrorReportGenerator).++ def test_error_prefixed_current_knowledge_is_scrubbed(self, app):+ from local_deep_research.web.api import _serialize_results++ # API key glued into an exception message (realistic: many HTTP+ # library errors echo the request URL).+ leaked = (+ "Error: LLM call failed: "+ "https://api.example.com/v1?api_key=sk-SECRETKEY1234567890AB"+ )+ results = {"current_knowledge": leaked}+ with app.app_context():+ data = _serialize_results(results).get_json()+ assert "sk-SECRETKEY1234567890AB" not in data["current_knowledge"]+ assert data["current_knowledge"].startswith("Error:")++ def test_error_prefixed_summary_is_scrubbed_real_payload_shape(self, app):+ from local_deep_research.web.api import _serialize_results++ # quick_summary() returns the strategy's current_knowledge under+ # the key `summary` (research_functions.py) — the field an API+ # client actually receives. Regression guard for the field-name+ # mismatch where only `current_knowledge` was scrubbed and the+ # real payload leaked through untouched.+ leaked = (+ "Error: LLM call failed: "+ "https://api.example.com/v1?api_key=sk-REALSHAPE12345678901"+ )+ results = {+ "research_id": "abc-123",+ "summary": leaked,+ "findings": [],+ "iterations": 1,+ "questions": {},+ "formatted_findings": "",+ "sources": [],+ }+ with app.app_context():+ data = _serialize_results(results).get_json()+ assert "sk-REALSHAPE12345678901" not in data["summary"]+ assert data["summary"].startswith("Error:")++ def test_bare_api_key_in_prose_is_scrubbed(self, app):+ from local_deep_research.web.api import _serialize_results++ # Not URL-embedded: exercises the sk-* prefix regex directly+ # (>= 20 chars after the prefix), not the ?api_key= query-param+ # pattern the other fixtures rely on.+ leaked = (+ "Error: OpenAI authentication failed for key "+ "sk-proj-AbCdEfGhIjKlMnOpQrStUvWx"+ )+ results = {"summary": leaked}+ with app.app_context():+ data = _serialize_results(results).get_json()+ assert "sk-proj-AbCdEfGhIjKlMnOpQrStUvWx" not in data["summary"]+ assert data["summary"].startswith("Error:")++ def test_error_prefixed_formatted_findings_is_scrubbed(self, app):+ from local_deep_research.web.api import _serialize_results++ leaked = (+ "Error: request to "+ "https://api.example.com/v1?api_key=sk-LEAK9876543210abcdefgh"+ )+ results = {"formatted_findings": leaked}+ with app.app_context():+ data = _serialize_results(results).get_json()+ assert "sk-LEAK9876543210abcdefgh" not in data["formatted_findings"]+ assert data["formatted_findings"].startswith("Error:")++ def test_error_prefixed_finding_content_is_scrubbed(self, app):+ from local_deep_research.web.api import _serialize_results++ leaked = (+ "Error: connection to "+ "https://db.example.com:5432/db?password=supersecret123"+ )+ results = {"findings": [{"phase": "Error", "content": leaked}]}+ with app.app_context():+ data = _serialize_results(results).get_json()+ assert "supersecret123" not in data["findings"][0]["content"]+ assert data["findings"][0]["content"].startswith("Error:")++ def test_long_non_error_current_knowledge_passes_through_unchanged(+ self, app+ ):+ from local_deep_research.web.api import _serialize_results++ # The boundary sanitizer only fires on fields starting with+ # "Error:". A long, legitimate research summary that is NOT+ # exception-derived must pass through untouched -- no truncation+ # (the 500-char cap only applies via sanitize_error_for_client,+ # which never runs for non-error content) and no credential-regex+ # false positives on prose mentions of "Authorization"/"Bearer".+ long_summary = (+ "Research summary: Authentication systems often use Bearer "+ "tokens in the Authorization header, but a well-designed API "+ "also supports API keys, OAuth, and session cookies. "+ ) * 20 # ~1800 chars, well over the boundary cap+ assert not long_summary.startswith("Error:")++ results = {"current_knowledge": long_summary}+ with app.app_context():+ data = _serialize_results(results).get_json()+ assert data["current_knowledge"] == long_summary++ def test_error_field_categorizable_token_survives_boundary_cap(self, app):+ from local_deep_research.web.api import _serialize_results++ # Regression guard for the strategy cap alignment: an error+ # message whose categorizable signal ("Connection refused") sits+ # past the 200-char HTTP-client default must survive the boundary+ # scrub. If _ERROR_BOUNDARY_MAX_LEN regresses to 200, the token+ # is truncated and ErrorReportGenerator classification breaks.+ leading = "x" * 230+ leaked = f"Error: {leading} Connection refused [Errno 111]"+ results = {"current_knowledge": leaked}+ with app.app_context():+ data = _serialize_results(results).get_json()+ assert "Connection refused" in data["current_knowledge"]+ assert data["current_knowledge"].startswith("Error:")++ def test_scrub_error_fields_helper_covers_all_field_spellings(self, app):+ # _scrub_error_fields is the helper called by all three jsonify+ # sinks (_serialize_results, generate_report, analyze_documents).+ # Verify every scrubbed spelling as a unit: `current_knowledge`+ # (raw strategy dicts), `summary` (quick_summary /+ # analyze_documents payloads), `formatted_findings`, and+ # per-finding `content`. Endpoint-level coverage lives in+ # TestQuickSummary / TestAnalyzeDocuments.+ from local_deep_research.web.api import _scrub_error_fields++ leaked = (+ "Error: connect to "+ "https://api.example.com/v1?api_key=sk-LEAK1234567890abcd"+ )+ results = {+ "current_knowledge": leaked,+ "summary": leaked,+ "formatted_findings": leaked,+ "findings": [{"phase": "Error", "content": leaked}],+ }+ _scrub_error_fields(results)+ assert "sk-LEAK1234567890abcd" not in results["current_knowledge"]+ assert "sk-LEAK1234567890abcd" not in results["summary"]+ assert "sk-LEAK1234567890abcd" not in results["formatted_findings"]+ assert "sk-LEAK1234567890abcd" not in results["findings"][0]["content"]+ assert results["current_knowledge"].startswith("Error:")+ assert results["summary"].startswith("Error:")+# ===================================================================# HTTP method enforcement