Skip to content

fix(retrieval-tools): sanitize unexpected exceptions in external and app tools - #19406

Merged
undivisible merged 2 commits into
BasedHardware:mainfrom
naufalfx805-source:fix/external-tools-exception-hardening
Oct 19, 2026
Merged

undivisible merged 2 commits into
BasedHardware:mainfrom
naufalfx805-source:fix/external-tools-exception-hardening

Conversation

@naufalfx805-source

@naufalfx805-source naufalfx805-source commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Prevents sensitive internal runtime exception leakage (stack traces, internal socket errors, database connection strings) to chat users and LLM context across external and app retrieval tools:

  1. backend/utils/retrieval/tools/perplexity_tools.py:
    • Sanitize unexpected runtime exceptions during Perplexity gateway searches to return generic user-facing message instead of raw f"Error: ... {str(e)}".
    • Add exc_info=True to logger.error for full backend observability.
  2. backend/utils/retrieval/tools/web_tools.py:
    • Sanitize unhandled exceptions in fetch_url_tool to return generic user message 'Error: Failed to fetch the URL. Please verify the URL or try again later.'.
    • Add exc_info=True to logger.error.
  3. backend/utils/retrieval/tools/graph_tools.py:
    • Sanitize unhandled exceptions in traverse_knowledge_graph_tool to return "Error traversing knowledge graph. Please try again later.".
  4. backend/utils/retrieval/tools/app_tools.py:
    • Sanitize unhandled runtime exceptions in MCP tool invocation and HTTP app tool endpoint calls to return generic message instead of raw {e} and {str(e)}.
    • Add exc_info=True to logger.error.

Verification & Testing

Added hermetic test suite in backend/tests/unit/test_external_tools_sanitization.py:

  • test_perplexity_unexpected_exception_sanitized: PASS
  • test_fetch_url_unexpected_exception_sanitized: PASS
  • test_traverse_knowledge_graph_unexpected_exception_sanitized: PASS
  • test_call_tool_endpoint_unexpected_exception_sanitized: PASS
  • test_mcp_tool_unexpected_exception_sanitized: PASS

All 5 unit tests pass hermetically in 0.20s.

Failure-Class: none

cc @kodjima33 @aryanorastar
Payout address (Base / EVM):
0x496e32ff3851cdb9146223a811e3d4f9218dd954

@Git-on-my-level

Copy link
Copy Markdown
Member

Reviewed - this is a clean, well-scoped hardening change. Verified per file:

  • backend/utils/retrieval/tools/app_tools.py: both the MCP invocation path (mcp_tool_function) and _call_tool_endpoint now return generic "Error calling ... Please try again later." instead of raw {e}/{str(e)}, with exc_info=True added so the traceback stays in server logs. Webhook failure accounting (record_app_webhook_failure + disable handling) is untouched - correct.
  • backend/utils/retrieval/tools/web_tools.py: the generic except in fetch_url_tool now returns a fixed message; the ValueError blocklist branch at line 297 still passes through sanitize(str(e)), which is intentional and already sanitized.
  • backend/utils/retrieval/tools/graph_tools.py: traverse_knowledge_graph_tool returns a fixed error string; the existing logger.exception call already preserved the traceback server-side.
  • backend/utils/retrieval/tools/perplexity_tools.py: _perplexity_gateway_search generic-path error no longer embeds str(e); exc_info=True added.
  • backend/tests/unit/test_external_tools_sanitization.py: I ran the 5 hermetic tests at this PR's head - all pass in 0.13s. Each test injects a sentinel via a controllable seam (_post_gateway_chat_completion, _fetch_page, traverse_knowledge_graph, httpx.AsyncClient, call_mcp_tool) and asserts both the exact generic message and non-leakage of the sentinel. Good behavioral coverage.

I also confirmed all four leak sites are still present on main, so this is not duplicating an already-merged fix.

Two minor, non-blocking notes:

  1. The log lines in app_tools.py interpolate raw exception text ({e}) without utils.log_sanitizer; that matches the pre-existing pattern in these files (graph_tools already logs raw exc), but if you touch them again, routing through sanitize() would match the backend logging guidance.
  2. For maintainers: there is overlap with still-open PRs on the same sites (fix(perplexity-tools): sanitize unexpected search exception handling #15632, fix(retrieval): sanitize raw exception leakage in traverse_knowledge_graph_tool #15647 by another contributor; this author's fix(retrieval-tools): sanitize internal exception disclosure across core chat tools #17827 covers adjacent chat tools) - worth deduping at merge time so whichever lands first gets a clean rebase.

Thanks for the tight scope and the sentinel-based tests. Leaving the merge call to the maintainers given the overlapping open PRs.

(Automated review on behalf of the maintainer team.)


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@aryanorastar aryanorastar left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1b4e54665c0a origin/main ad94069 still returns str(e) in perplexity_tools.py:143 and app_tools.py:440, and sanitize(str(e)) from fetch_url at web_tools.py:300. This head replaces unexpected paths with fixed messages; test_external_tools_sanitization.py pins them. Later #19616/#19601 are same-file copies. CI green. Head 1b4e54665c0a63208067074f91416d20041843a0. Required checks on this head are green.

…tools

Prevent internal exception leakage in perplexity_tools, web_tools, graph_tools, and app_tools by returning sanitized error messages and enabling exc_info=True for backend logging. Add comprehensive hermetic unit tests.
@naufalfx805-source
naufalfx805-source force-pushed the fix/external-tools-exception-hardening branch from 1b4e546 to 7746030 Compare October 3, 2026 03:24
@undivisible
undivisible merged commit 4e93799 into BasedHardware:main Oct 19, 2026
45 checks passed
Git-on-my-level added a commit that referenced this pull request Oct 19, 2026
Five unit files fail on current main. Each one passed on its own PR's base
and broke when main moved underneath it; none is a product regression.

- test_request_context.py (#19738): tested the JIT budget surface that
  #22209 removed from llm_gateway/gateway/request_context.py. Keep the
  request-id tests; drop the tests for removed code.
- test_users_joan_followup_tombstone_guard.py (#19867): called
  delete_person_endpoint, but the joan followup route is
  delete_followup_question_endpoint.
- test_developer_from_segments_idempotency.py (#21265): process fakes
  rejected the trigger=CLIENT_FINALIZE kwarg the router passes since #19788.
- test_external_tools_sanitization.py (#19406): the stubbed utils package
  lacked utils.generated_compute (#21488) and utils.model_text. Stub the
  default-off gate as disabled and load the stdlib-only model_text for real.
- test_batch_upload_storage.py: the database.vector_db stub lacked
  delete_action_item_vectors_batch, which merge_conversations imports since
  #15953.

Failure-Class: none

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Git-on-my-level added a commit that referenced this pull request Oct 19, 2026
)

* fix(backend): restore pyright-clean main after #22207 and #22326

Main's backend unit shards fail the enforced pyright lane:

- database/desktop_previews.py (#22207): 16 reportUnnecessaryIsInstance
  errors. The runtime guards stay; they move into validators that take
  `object` (_payload, _string, _expected_generation, _datetime), so the
  checks are meaningful to pyright. Public signatures, error messages and
  check order are unchanged.
- utils/sync/pipeline.py:process_segment (#22326 on top of #22452):
  "code is too complex to analyze". Behaviour-neutral split: the two
  identical cap-hold defer blocks become one hold_for_cap closure, and the
  final-pass / speaker-identification block moves to
  _assign_segment_speakers with the same exception handling.

Failure-Class: none

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(backend): repair unit tests that drifted from main across merges

Five unit files fail on current main. Each one passed on its own PR's base
and broke when main moved underneath it; none is a product regression.

- test_request_context.py (#19738): tested the JIT budget surface that
  #22209 removed from llm_gateway/gateway/request_context.py. Keep the
  request-id tests; drop the tests for removed code.
- test_users_joan_followup_tombstone_guard.py (#19867): called
  delete_person_endpoint, but the joan followup route is
  delete_followup_question_endpoint.
- test_developer_from_segments_idempotency.py (#21265): process fakes
  rejected the trigger=CLIENT_FINALIZE kwarg the router passes since #19788.
- test_external_tools_sanitization.py (#19406): the stubbed utils package
  lacked utils.generated_compute (#21488) and utils.model_text. Stub the
  default-off gate as disabled and load the stdlib-only model_text for real.
- test_batch_upload_storage.py: the database.vector_db stub lacked
  delete_action_item_vectors_batch, which merge_conversations imports since
  #15953.

Failure-Class: none

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backend Backend Task (python) positive-signal Automation verified a genuine fix/quality contribution

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants