Skip to content

fix(ms365): harden services with defensive null guards, recipient extraction, and safe retry-after parsing (#14247) - #14250

Merged
Git-on-my-level merged 2 commits into
BasedHardware:mainfrom
TheRWX:fix/ms365-services-hardening
Sep 17, 2026
Merged

Git-on-my-level merged 2 commits into
BasedHardware:mainfrom
TheRWX:fix/ms365-services-hardening

Conversation

@TheRWX

@TheRWX TheRWX commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #14247

Harden Microsoft 365 (plugins/omi-ms365-app) service layers against null API payloads, malformed collections, missing dictionary keys, and rate-limit header formats across Outlook mail, Teams, SharePoint, and Calendar operations:

  1. services/mail.py:

    • read(): Defensively extracts toRecipients and ccRecipients via _extract_recipients(), preventing TypeError: 'NoneType' object is not iterable when Microsoft Graph returns "toRecipients": null or "ccRecipients": null.
    • Safely parses recipient entries if formatted as dicts or raw strings, avoiding KeyError: 'emailAddress'.
    • list_recent() and search(): Coerces and clamps limit between 1 and 50; guards against null value collections and filters non-dict items.
    • _slim_message(): Guards against non-dict inputs, returning {}.
    • Quotes in search queries are safely escaped.
  2. services/teams.py:

    • list_recent_chats() and list_my_teams(): Guards against null value collections ((data.get("value") or [])), preventing TypeError: 'NoneType' object is not iterable.
    • Filters out non-dict chat/team items and bounds limit to [1, 50].
    • create_online_meeting(): Defensively accesses response dictionary.
  3. services/sharepoint.py:

    • _slim_item(): Guards non-dict inputs, preventing TypeError: argument of type 'NoneType' is not iterable on "folder" in it.
    • list_recent_files() and search_files(): Guards against null value responses and filters non-dict items.
    • Bounds limit to [1, 50] and safely escapes single quotes in OData queries.
  4. services/calendar.py:

    • find_free_slots(): Guards against null meetingTimeSuggestions from Graph ({"meetingTimeSuggestions": null}), preventing TypeError: 'NoneType' object is not iterable.
    • Shields nested keys (meetingTimeSlot -> start/end -> dateTime) from KeyError and TypeError when slots or dates are omitted.
    • _slim_event(): Guards non-dict inputs and null nested organizer/location objects.
  5. services/graph_client.py:

    • _parse_retry_after(): Safely parses Retry-After headers supporting both integer seconds and RFC 7231 / RFC 9110 HTTP-date strings (e.g. Wed, 21 Oct 2026 07:28:00 GMT), preventing ValueError crashes during rate-limiting or 503 backoffs.
  6. Hermetic Regression Test Suite:

    • Added plugins/omi-ms365-app/test_services_hardening.py containing 21 tests covering defensive null guards, recipient extraction, and RFC 7231 header parsing, runnable under pure standard library Python (python3 -S) with zero third-party dependencies.

Product invariants affected

none

How it was verified

  • Ran hermetic tests under stdlib Python:
    python3 -S plugins/omi-ms365-app/test_services_hardening.py
    # 21 tests passed in 0.012s
  • Ran all MS365 tests:
    python3 -m unittest plugins/omi-ms365-app/test_services_hardening.py plugins/omi-ms365-app/test_calendar_pagination.py plugins/omi-ms365-app/test_tool_dispatch.py
    # 36 tests passed in 0.026s
  • Ran repo preflight:
    bash scripts/pr-preflight --lane ci --pr-body-file /tmp/pr_body.md
    # All checks passed

Tests

  • plugins/omi-ms365-app/test_services_hardening.py:
    • MailHardeningTests (slim message non-dict, extract recipients null/malformed, read null recipients, list recent null value, search quote escaping)
    • TeamsHardeningTests (chats null value, chats non-dict items, joined teams null value, online meeting non-dict)
    • SharePointHardeningTests (slim item non-dict, recent files null value, search quotes, binary content fallback)
    • CalendarHardeningTests (slim event non-dict, free slots null suggestions, free slots guarded nested keys)
    • GraphClientRetryAfterTests (integer seconds, null/empty default, RFC 7231 HTTP-date parsing, invalid string fallback)

Failure class (fixes)

Failure-Class: none

Claim: PayPal [email protected]

Review in cubic

…raction, and safe retry-after parsing (BasedHardware#14247)

Fixes BasedHardware#14247

Harden Microsoft 365 plugin services against null API payloads,
missing collection values, unhandled type exceptions, and rate limit parsing:

1. mail.py:
   - read: guard against null toRecipients and ccRecipients from Graph API
     preventing TypeError: 'NoneType' object is not iterable.
   - extract recipient emailAddress safely from dict or string items.
   - list_recent / search: guard against null value payload and filter non-dict items.
   - _slim_message: guard non-dict input.
   - clamp limit to [1, 50].

2. teams.py:
   - list_recent_chats / list_my_teams: guard against null value collections
     preventing TypeError: 'NoneType' object is not iterable.
   - filter non-dict items and clamp limit to [1, 50].
   - create_online_meeting: defensive extraction on unexpected response types.

3. sharepoint.py:
   - _slim_item: guard against non-dict items preventing TypeError on "folder" in it.
   - list_recent_files / search_files: guard against null value collections and filter non-dict items.
   - clamp limit to [1, 50] and escape query string quotes.

4. calendar.py:
   - find_free_slots: guard against null meetingTimeSuggestions and shield nested keys
     (meetingTimeSlot -> start/end -> dateTime) from KeyError/TypeError.
   - _slim_event: guard against non-dict inputs and null nested objects.

5. graph_client.py:
   - _parse_retry_after: safely parse Retry-After header supporting integer seconds
     and RFC 7231 / RFC 9110 HTTP-date strings without crashing on ValueError.

6. test_services_hardening.py:
   - Authored 21 hermetic unit tests runnable under pure stdlib Python (python3 -S).

Product invariants affected: none
Failure-Class: none
@Git-on-my-level

Copy link
Copy Markdown
Member

Thanks @TheRWX — solid hardening pass. I verified the diff and ran the new suite plus both existing ms365 suites (test_calendar_pagination.py, test_tool_dispatch.py) against your branch in a network-isolated container: all 36 tests pass.

Per-file notes:

  • services/graph_client.py — _parse_retry_after is the real fix here: int(resp.headers.get("Retry-After", "2")) raised ValueError on RFC 7231 HTTP-date values; the new parser handles integer seconds, HTTP-dates, and invalid fallbacks, and both retry loops (_request and get_bytes) now share it.
  • services/mail.py — _extract_recipients replaces the r["emailAddress"] indexing that raised TypeError/KeyError on "toRecipients": null (the [Plugin] Harden error handling, null guards, and type validation in omi-ms365-app #14247 crash); read() also returns {} on a non-dict message and guards body/contentType.
  • services/calendar.py — find_free_slots no longer indexes s["meetingTimeSlot"]["start"]["dateTime"] directly; _slim_event guards the nested start/end/location/organizer/onlineMeeting objects.
  • services/teams.py — null value collections and non-dict items handled in list_recent_chats/list_my_teams; create_online_meeting now echoes the requested subject/start/end when Graph omits them (previously null — reads as an improvement, flagging the behavior change for visibility).
  • services/sharepoint.py — "folder" in it on a non-dict no longer raises TypeError; OData single-quote doubling preserved plus str(query or "") coercion.
  • test_services_hardening.py — hermetic, stdlib-only, follows the plugin's existing stub pattern; 21/21 green.

One actionable gap: the new suite is not registered in .github/checks-manifest.yaml, so CI will never run it. Both existing ms365 suites have entries (ms365-calendar-pagination-tests at line 66). Please add one alongside them, e.g.:

Placement caution: add it next to the other ms365 entries, not at the end of the file — entries appended at EOF land under exempt: and the manifest check goes red.

Two minor non-blocking notes:

  • mail.search escapes " as " inside the KQL phrase; Graph/KQL phrase queries don't document backslash escapes, so a query containing a literal double quote may return fewer or no results rather than error. Worth a quick live check against a tenant if you have one.
  • max(1, min(int(limit), 50)) still raises ValueError on non-numeric strings (the dispatcher maps TypeError to 400, not ValueError), e.g. limit="ten" would surface as a 500. A try/except fallback to the default limit would close it.

Also noting for maintainers: #14252 by @Evos09 addresses the same issue #14247 and is also open, so one of the two will need to be picked or reconciled before merge — code quality here looks good either way.


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 needs-maintainer-review Needs a human maintainer to sign off before merge python labels Sep 16, 2026
…mits (BasedHardware#14247)

- Register ms365-services-hardening-tests in .github/checks-manifest.yaml adjacent to ms365-calendar-pagination-tests.
- Safely coerce string limit inputs across calendar, mail, sharepoint, and teams falling back to defaults on ValueError/TypeError.
- Strip double quotes from mail search query phrases to avoid corrupting KQL syntax.
- Expand hermetic test suite with 2 new unit tests (23/23 tests pass).

Product invariants affected: none
Failure-Class: none
@TheRWX

TheRWX commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks @Git-on-my-level for the thorough review. I've addressed the feedback in commit 5cef1171bb:

  1. Manifest Registration: Registered ms365-services-hardening-tests in .github/checks-manifest.yaml directly adjacent to ms365-calendar-pagination-tests with triggers on plugins/omi-ms365-app/** and .github/checks-manifest.yaml.
  2. Safe Limit Coercion: Wrapped limit parsing with try / except (ValueError, TypeError) fallbacks across calendar.py, mail.py, sharepoint.py, and teams.py so non-numeric strings (e.g. limit="ten") fall back safely to service defaults instead of propagating a 500.
  3. KQL Quote Handling: Updated mail.search to strip embedded double quotes from queries (replace('"', '')) rather than backslash-escaping, preserving valid KQL phrase wrapping.
  4. Hermetic Test Coverage: Added 2 new tests in plugins/omi-ms365-app/test_services_hardening.py covering non-numeric limit fallbacks across all 4 services and quote stripping in mail search. The suite now runs 23/23 tests green in 0.02s, and all 3 MS365 test suites pass (38/38 tests).
  5. Upstream Preflight: Ran scripts/pr-preflight --lane ci — all 17 manifest checks passed cleanly.

PayPal: [email protected]

@Git-on-my-level Git-on-my-level left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

MS365 plugin hardening: null guards, recipient extraction, retry-after parsing. CI green.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

needs-maintainer-review Needs a human maintainer to sign off before merge python

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Plugin] Harden error handling, null guards, and type validation in omi-ms365-app

2 participants