Skip to content

fix(retrieval-tools): sanitize internal exception disclosure across core chat tools - #17827

Closed
naufalfx805-source wants to merge 4 commits into
BasedHardware:mainfrom
naufalfx805-source:fix/retrieval-tools-exception-hardening
Closed

naufalfx805-source wants to merge 4 commits into
BasedHardware:mainfrom
naufalfx805-source:fix/retrieval-tools-exception-hardening

Conversation

@naufalfx805-source

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

Copy link
Copy Markdown
Contributor

Description

This PR hardens error handling and prevents internal exception disclosure across the core chat retrieval tools:

  • backend/utils/retrieval/tools/conversation_tools.py
  • backend/utils/retrieval/tools/memory_tools.py
  • backend/utils/retrieval/tools/calendar_tools.py
  • backend/utils/retrieval/tools/file_tools.py
  • backend/utils/retrieval/tools/gmail_tools.py

Summary of Changes

  1. Sanitize Exception Details: Eliminated raw exception formatting (str(e), f"{e}"), date parsing ValueError leaks, and traceback.print_exc() calls in returned tool strings so internal database queries, credentials, and stack traces are never disclosed to the agent context or end users.
  2. Preserve Observability: Server-side observability is preserved and enhanced by passing exc_info=True to logger.error(...).
  3. Hermetic Test Suite: Added backend/tests/unit/test_retrieval_tools_sanitization.py containing 18 unit tests validating error sanitization and hermetic module isolation across all 5 tools.

Test Verification

Ran full hermetic pytest suite:

tests/unit/test_retrieval_tools_sanitization.py::TestConversationToolsSanitization::test_get_conversations_invalid_start_date PASSED
tests/unit/test_retrieval_tools_sanitization.py::TestConversationToolsSanitization::test_get_conversations_invalid_end_date PASSED
tests/unit/test_retrieval_tools_sanitization.py::TestConversationToolsSanitization::test_get_conversations_formatting_exception_sanitized PASSED
tests/unit/test_retrieval_tools_sanitization.py::TestConversationToolsSanitization::test_search_conversations_invalid_dates PASSED
tests/unit/test_retrieval_tools_sanitization.py::TestMemoryToolsSanitization::test_get_memories_invalid_dates PASSED
tests/unit/test_retrieval_tools_sanitization.py::TestMemoryToolsSanitization::test_get_memories_invalid_temporal_read_arguments PASSED
tests/unit/test_retrieval_tools_sanitization.py::TestMemoryToolsSanitization::test_search_memories_invalid_temporal_arguments PASSED
tests/unit/test_retrieval_tools_sanitization.py::TestMemoryToolsSanitization::test_search_memories_exception_sanitized PASSED
tests/unit/test_retrieval_tools_sanitization.py::TestCalendarToolsSanitization::test_create_calendar_event_invalid_start_time PASSED
tests/unit/test_retrieval_tools_sanitization.py::TestCalendarToolsSanitization::test_create_calendar_event_unexpected_exception_sanitized PASSED
tests/unit/test_retrieval_tools_sanitization.py::TestCalendarToolsSanitization::test_get_calendar_events_unexpected_exception_sanitized PASSED
tests/unit/test_retrieval_tools_sanitization.py::TestCalendarToolsSanitization::test_delete_calendar_event_by_id_unexpected_exception_sanitized PASSED
tests/unit/test_retrieval_tools_sanitization.py::TestCalendarToolsSanitization::test_delete_calendar_event_search_batch_mutation_sanitized PASSED
tests/unit/test_retrieval_tools_sanitization.py::TestCalendarToolsSanitization::test_update_calendar_event_unexpected_exception_sanitized PASSED
tests/unit/test_retrieval_tools_sanitization.py::TestFileToolsSanitization::test_search_files_config_error_sanitized PASSED
tests/unit/test_retrieval_tools_sanitization.py::TestFileToolsSanitization::test_search_files_session_error_sanitized PASSED
tests/unit/test_retrieval_tools_sanitization.py::TestFileToolsSanitization::test_search_files_unexpected_error_sanitized PASSED
tests/unit/test_retrieval_tools_sanitization.py::TestGmailToolsSanitization::test_get_gmail_messages_unexpected_exception_sanitized PASSED

70 passed in 6.95s (including related retrieval semantics and date validation suites)

Failure-Class: none
Line-Count-Exception: backend/utils/retrieval/tools/calendar_tools.py | 1517 -> 1522 | sanitize internal exception disclosure

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

…ore chat tools

Sanitize raw exception strings, tracebacks, and internal details across conversation, memory, calendar, file, and gmail retrieval tools. Add comprehensive unit tests verifying hermetic error sanitization.
@Git-on-my-level

Copy link
Copy Markdown
Member

Thanks for this clean security-hardening pass — exactly the right instinct: raw exception strings from the DB/API layers shouldn't reach the agent context, and the fix keeps full detail in server logs via exc_info=True while giving the agent a stable, actionable message.

Per-file notes:

  • backend/utils/retrieval/tools/calendar_tools.py — most-touched file. All {e}/{retry_error}/{delete_error} interpolations in returned strings are replaced with fixed messages across get_calendar_events_tool, create_calendar_event_tool, delete_calendar_event_tool, and update_calendar_event_tool, and every logger.error gains exc_info=True. The batch-delete change is load-bearing rather than cosmetic: mutation_result.failed tuples are rendered verbatim by format_deleted_calendar_events (backend/models/calendar_mutation.py), so swapping str(e) for the constant "Failed to delete event" closes an actual disclosure path.
  • backend/utils/retrieval/tools/conversation_tools.py — date-parse ValueError text dropped from both get_conversations_tool and search_conversations_tool messages while keeping the echoed user input and the expected format (good — the agent can still self-correct). The formatting-failure path keeps the useful "Found N conversations…" context minus str(e), and the stray traceback.print_exc() (unstructured stderr) is gone, with the log correctly upgraded from logger.info to logger.error.
  • backend/utils/retrieval/tools/file_tools.py — config-access and session-ValueError paths now return constants; the ValueError path sensibly logs at warning since a malformed session id is a client-side condition, not a server fault.
  • backend/utils/retrieval/tools/gmail_tools.py — final handler sanitized and the now-unused import traceback removed; the symbols the tests patch (retry_on_auth_async, google_integration_has_scope) all exist at head, so the tests exercise real call sites.
  • backend/utils/retrieval/tools/memory_tools.py — temporal-read argument errors sanitized in both get_memories_tool and search_memories_tool, including the chat_scope date parse; the final search handler is sanitized with exc_info=True.
  • backend/tests/unit/test_retrieval_tools_sanitization.py — solid hermetic suite built on the repo's testing.import_isolation harness. The tests assert both the exact sanitized strings and the absence of planted secrets (postgres:// URIs, Bearer ya29 tokens, internal keys), which is the right shape for regression protection, and the ENCRYPTION_SECRET env default matches the repo's public dev-template placeholder already used across the existing unit suite.

Verified on head 7c1f469: no return f"...{e}"-style interpolation remains in any of the five tool modules — the remaining {e} uses are all in logger.* calls (server-side only). Backend unit suite, all four shards, the hermetic merge gate, formatting, and hygiene checks are green.

One non-blocking observation for a possible follow-up: the same unsanitized pattern still exists in sibling retrieval tool modules — e.g. action_item_tools.py still has ~9 return f"...{e}" sites. A follow-up applying this same treatment there (and to any other chat-exposed tools) would finish the sweep.

Since this changes what agent-facing tool errors disclose, it deserves a quick maintainer pass before merge even though everything checks out.


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

@Git-on-my-level Git-on-my-level added positive-signal Automation verified a genuine fix/quality contribution backend Backend Task (python) labels Sep 24, 2026
@aryanorastar

Copy link
Copy Markdown
Collaborator

Keeping this open. Not approving 7c1f469772bd. origin/main ca828a8c617d still interpolates {str(e)} in gmail_tools.py, and this SHA also rewrites calendar_tools.py, conversation_tools.py, file_tools.py, and memory_tools.py (extra production, so not a gmail-only close). Hygiene SKIPPED. Do not approve this sha.

— Astar, on behalf of @aryanorastar

@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.

7c1f469772bd2efbf4b7bf5523d9e1b92e77f9c5 backend/utils/retrieval/tools/calendar_tools.py still returns GoogleAPIError e.message.

@naufalfx805-source

Copy link
Copy Markdown
Contributor Author

@aryanorastar Good catch! Fixed in commit 356f8f7. Sanitized all 6 GoogleAPIError e.message occurrences across calendar_tools.py to return clean generic error messages while preserving server-side logging, and added a matching unit test in test_retrieval_tools_sanitization.py (19/19 passing).

@Git-on-my-level

Copy link
Copy Markdown
Member

Verified at 356f8f7: all six GoogleAPIError handlers in calendar_tools.py (get events, create, delete-by-id, delete-by-search, get-for-update, update) now keep status and message in logger.error only — every return in those paths is a fixed string (e.g. "Error fetching calendar events. Please try again."). I also scanned every return statement across the five changed tool files: none interpolate exception objects or messages; returned error strings echo only user-supplied input (dates, titles, query text). Server-side detail is preserved via exc_info=True on the unexpected-error handlers.

The new test_get_calendar_events_google_api_error_message_sanitized plants a secret in the raised GoogleAPIError message and asserts it never reaches the tool output — a direct regression guard for the concern raised on the previous commit. Thanks for the quick turnaround.

One non-blocking nit: the contact-search error loggers (calendar_tools.py lines ~133/135/212/214) and the non-retry GoogleAPIError logger lines lack exc_info=True while their sibling handlers have it; happy to see that aligned in a follow-up but it does not block.

The earlier automated review on the prior head stands; this comment covers only the delta. Since a maintainer changes-requested review is on record for the previous commit and no CI summary is available for this head, leaving formal sign-off to the human maintainer.

— AI-generated maintainer feedback on behalf of the Omi maintainers


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 added a commit that referenced this pull request Oct 2, 2026
…n_item_tools (#18486)

## Description
Follow-up to PR #17827 addressing the observation by @Git-on-my-level:
> *"the same unsanitized pattern still exists in sibling retrieval tool
modules — e.g. action_item_tools.py still has ~9 return f"...{e}" sites.
A follow-up applying this same treatment there (and to any other
chat-exposed tools) would finish the sweep."*

This PR hardens error handling and closes all internal exception
disclosure sites in
`backend/utils/retrieval/tools/action_item_tools.py`.

### Summary of Changes
1. **Sanitize Exception Details**: Eliminated raw exception formatting
(`str(e)`, `f"{e}"`), date parsing `ValueError` leaks, and
`traceback.print_exc()` calls in returned tool strings so internal
database queries, credentials, and stack traces are never disclosed to
the agent context or end users.
2. **Preserve Observability**: Server-side observability is preserved
and enhanced by passing `exc_info=True` to `logger.error(...)`.
3. **Hermetic Test Suite**: Added
`backend/tests/unit/test_action_item_tools_sanitization.py` containing
12 unit tests validating error sanitization and hermetic module
isolation across all 3 action item tools.
4. **Module Stub Hygiene**: Fully compliant with
`backend/scripts/check_module_stub_pollution.py` (0 violations).

### Test Verification
Ran full hermetic pytest suite:
```
backend/tests/unit/test_action_item_tools_sanitization.py::TestGetActionItemsSanitization::test_invalid_start_date_sanitized PASSED
backend/tests/unit/test_action_item_tools_sanitization.py::TestGetActionItemsSanitization::test_invalid_end_date_sanitized PASSED
backend/tests/unit/test_action_item_tools_sanitization.py::TestGetActionItemsSanitization::test_invalid_due_start_date_sanitized PASSED
backend/tests/unit/test_action_item_tools_sanitization.py::TestGetActionItemsSanitization::test_invalid_due_end_date_sanitized PASSED
backend/tests/unit/test_action_item_tools_sanitization.py::TestGetActionItemsSanitization::test_config_error_sanitized PASSED
backend/tests/unit/test_action_item_tools_sanitization.py::TestGetActionItemsSanitization::test_db_exception_sanitized PASSED
backend/tests/unit/test_action_item_tools_sanitization.py::TestCreateActionItemSanitization::test_invalid_due_at_sanitized PASSED
backend/tests/unit/test_action_item_tools_sanitization.py::TestCreateActionItemSanitization::test_db_exception_sanitized PASSED
backend/tests/unit/test_action_item_tools_sanitization.py::TestCreateActionItemSanitization::test_config_error_sanitized PASSED
backend/tests/unit/test_action_item_tools_sanitization.py::TestUpdateActionItemSanitization::test_invalid_due_at_sanitized PASSED
backend/tests/unit/test_action_item_tools_sanitization.py::TestUpdateActionItemSanitization::test_db_exception_sanitized PASSED
backend/tests/unit/test_action_item_tools_sanitization.py::TestUpdateActionItemSanitization::test_config_error_sanitized PASSED

============================= 12 passed in 0.86s ==============================
```

Regression test suites:
```
backend/tests/unit/test_action_items_timezone.py (11 passed)
backend/tests/unit/test_action_item_date_validation.py (26 passed)

============================= 37 passed in 3.09s ==============================
```

Hygiene check:
```
python backend/scripts/check_module_stub_pollution.py
Checked 1296 backend test file(s); 0 violation(s).
```

Failure-Class: none

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


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/18486?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="Review in cubic"
src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
@naufalfx805-source

Copy link
Copy Markdown
Contributor Author

Closing this pull request as the branch has fallen significantly behind \main\ (with multiple merge conflicts across core retrieval tools), and the exception sanitization protections proposed here are now comprehensively addressed in recent PRs such as #19406.

@github-actions

github-actions Bot commented Oct 3, 2026

Copy link
Copy Markdown
Contributor

Hey @naufalfx805-source 👋

Thank you so much for taking the time to contribute to Omi! We truly appreciate you putting in the effort to submit this pull request.

After careful review, we've decided not to merge this particular PR. Please don't take this personally — we genuinely try to merge as many contributions as possible, but sometimes we have to make tough calls based on:

  • Project standards — Ensuring consistency across the codebase
  • User needs — Making sure changes align with what our users need
  • Code best practices — Maintaining code quality and maintainability
  • Project direction — Keeping aligned with our product principles and locked invariants

Before your next PR, please skim:

  • PRODUCT.md — product north star
  • Product invariants — locked rules (shared chat, memory tiers, agent control plane, integrations, brand)

If this was declined for direction or taste, maintainers should cite an invariant ID or open a proposed one — ask if that citation is missing.

Your contribution is still valuable to us, and we'd love to see you contribute again in the future! If you'd like feedback on how to improve this PR or want to discuss alternative approaches, please don't hesitate to reach out.

Thank you for being part of the Omi community!

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.

3 participants