Skip to content

fix(oauth): harden notion services with timeouts, defensive null guards, and safe database validation (#14257) - #14258

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

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

Conversation

@TheRWX

@TheRWX TheRWX commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #14257

Harden Notion CRM OAuth plugin (plugins/oauth) against network hangs, unhandled JSON decode errors on HTTP 502/504 responses, null/malformed conversation fields, and fragile database schema handling:

  1. plugins/oauth/client.py:
    • Added DEFAULT_TIMEOUT = 10.0 across NotionClient.get_database, get_access_token, and get_databases_edited_time_desc, preventing worker threads from blocking indefinitely on unresponsive endpoints.
    • Wrapped network requests in try ... except requests.RequestException to return structured 500 error envelopes rather than uncaught server crashes.
    • Added _safe_json helper to guard against JSONDecodeError when Notion or intermediary proxies return HTML error pages (e.g. 502 Bad Gateway).
    • Hardened from_dict and multi_from_dict in NotionDatabasePropertyModel, NotionDatabaseModel, and NotionOAuthModel against None, empty dicts, missing keys, and non-list structures.
    • Corrected return type annotation in NotionOAuthModel.from_dict.

  2. plugins/oauth/conversation_created.py:
    • Added _build_notion_conversation_properties helper with complete null guards for structured, title, emoji, speakers, category, and overview.
    • Guarded emoji decoding against both UnicodeEncodeError and UnicodeDecodeError, safely falling back to raw emoji or default 🧠.
    • Handled None segments and missing/None speaker attributes during speaker set deduplication.
    • Clamped conversation duration to non-negative values (max(0, int(delta))) and guarded against missing started_at or finished_at.
    • Added DEFAULT_TIMEOUT and request exception handling to create_notion_row.
    • Hardened validate_database against non-dict responses and missing schema properties.

  3. Hermetic Test Suite:
    • Authored plugins/oauth/test_oauth_hardening.py with 23 unit tests running under pure standard library Python (python3 -S) in 0.008s with zero third-party dependencies.

Product invariants affected

none

How it was verified

• Ran hermetic test suite under stdlib:
python3 -S plugins/oauth/test_oauth_hardening.py

23 tests passed in 0.008s

• Ran standard test suite:
python3 plugins/oauth/test_oauth_hardening.py

23 tests passed in 0.009s

• Ran existing log safety suite:
python3 plugins/oauth/test_client_log_safety.py

5 tests passed in 1.25s

• Ran repo preflight:
bash scripts/pr-preflight --lane ci --pr-body-file /tmp/pr_body_oauth.md

All checks passed

Tests

• plugins/oauth/test_oauth_hardening.py:
• NotionClientHardeningTests (get_database default & custom timeouts, request exceptions, 502 HTML non-json error; get_access_token default timeout, request exception; get_databases_edited_time_desc timeout, missing results key)
• NotionModelsHardeningTests (property model defensive & valid, database model defensive & malformed properties, multi_from_dict non-list & invalid items, oauth model defensive)
• ConversationPayloadHardeningTests (null structured properties fallback, emoji unicode decoding safety, speaker dedup & null segments, duration clamping & null timestamps, create_notion_row success & timeout, validate_database missing fields & invalid schema)

Failure class (fixes)

Failure-Class: none

Claim: PayPal [email protected]

Review in cubic

…ds, and safe database validation (BasedHardware#14257)

Harden Notion CRM OAuth integration against network hangs, unhandled JSON decode errors on HTTP 502/504 responses, null/malformed conversation fields, and fragile database schema handling.

Fixes BasedHardware#14257

Failure-Class: none

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

Thanks @TheRWX — this is a genuinely useful hardening pass. I verified the claims locally at head: all 23 tests in the new suite pass under both python3 -S plugins/oauth/test_oauth_hardening.py and plain python3, and the existing plugins/oauth/test_client_log_safety.py (5 tests) still passes from repo root, so the log-safety invariant from #13778 holds.

Per-file notes:

plugins/oauth/client.py

  • DEFAULT_TIMEOUT = 10.0 correctly reaches all three request calls (get_database, get_access_token, get_databases_edited_time_desc), each now catching requests.RequestException into the structured {"error": ...} envelope callers already understand. Real fix for the unbounded hangs in #14257.
  • _safe_json fixes the actual 502/504 HTML-page crash, and the from_dict/multi_from_dict hardening preserves behavior for well-formed payloads (empty-string defaults only replace what were previously hard KeyError/TypeErrors). The corrected NotionOAuthModel.from_dict return annotation is a good catch.
  • Nit: Optional in from typing import Any, List, Optional is unused — please drop it.

plugins/oauth/conversation_created.py

  • _build_notion_conversation_properties keeps the exact property shape on the happy path while adding the null guards from the issue; max(0, int(delta)) clamping and the None-speaker dedup are the right calls.
  • Two wire-visible behavior changes worth naming in the PR body (both look intentional and reasonable): POST /notion-crm previously let validate_database's HTTPException propagate as a 400 to the caller, while create_notion_row now returns False so the endpoint returns {} — better for a webhook, but it is a visible change; and the OAuth callback previously bare-returned None on validation failure, it now renders the error page (code 400005) — clear improvement.
  • The try: from .client ... except (ImportError, ValueError): from oauth.client ... dual import only serves importing the module with plugins/ directly on sys.path (as the new test does); production (plugins/main.py uses from oauth import conversation_created) takes the relative path. Not blocking — test_client_log_safety.py solves the same need via importlib.util.spec_from_file_location without touching production imports, which would also work here.

plugins/oauth/test_oauth_hardening.py

  • Good coverage mapping to the issue claims: timeout kwarg assertions, exception envelopes, non-JSON 502, model hardening, payload nulls, and both validate_database failure paths.
  • Blocking gap: the file is wired into no CI lane. .github/checks-manifest.yaml runs plugin-oauth-client-log-safety-tests for plugins/**/*.py changes, but nothing executes this new 481-line suite, so it will silently rot after merge. Please add an entry mirroring the log-safety one (under the existing checks: list — entries appended at EOF after exempt: do not register), e.g.:
  - id: plugin-oauth-hardening-tests
    command: ["python3", "plugins/oauth/test_oauth_hardening.py"]
    triggers: ["plugins/oauth/**", ".github/checks-manifest.yaml"]
    lanes: ["local", "ci"]
    reason: "regression suite for oauth plugin timeouts, exception envelopes, non-JSON error pages, and null-guarded payload building"

That is the repo's contract for hermetic tests (they must run in CI), and a standalone-process manifest command is also the safest way to run this suite given it installs sys.modules stubs at import time.

Once the manifest entry (and the Optional nit) land, I have no further technical concerns. Leaving the merge call for human maintainer review: this is the Notion OAuth integration surface, and bounty eligibility for #14257 is a maintainer decision (claims are handled via [email protected] per the contribution docs rather than the PR body).


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 python needs-tests PR introduces logic that should be covered by tests needs-maintainer-review Needs a human maintainer to sign off before merge labels Sep 17, 2026
…n up imports (BasedHardware#14257)

- Register plugin-oauth-hardening-tests in .github/checks-manifest.yaml directly below plugin-oauth-client-log-safety-tests.
- Drop unused Optional import in plugins/oauth/client.py.

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

TheRWX commented Sep 17, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @Git-on-my-level for the thorough review. Addressed both requested items in commit c3daf2a320:

  1. Manifest Registration: Registered plugin-oauth-hardening-tests in .github/checks-manifest.yaml directly below plugin-oauth-client-log-safety-tests under the active checks: list (triggers on plugins/oauth/** and .github/checks-manifest.yaml, lanes ["local", "ci"]).
  2. Import Cleanup: Dropped the unused Optional import from typing in plugins/oauth/client.py:3.

Both local and CI preflight gates pass with zero warnings or errors (15/15 checks pass, 23/23 hermetic tests pass under python3 -S).

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.

Re-review at head c3daf2a — both requested changes are in; verdict: approve.

  • plugin-oauth-hardening-tests is now registered in .github/checks-manifest.yaml (command python3 plugins/oauth/test_oauth_hardening.py, triggers plugins/oauth/** + the manifest, lanes local+ci, with reason) — appended under the existing checks list, so it registers, per my earlier note.
  • Unused Optional import dropped from plugins/oauth/client.py.
  • Re-verified locally at head: python3 -S plugins/oauth/test_oauth_hardening.py → 23/23 OK, and python3 plugins/oauth/test_client_log_safety.py → 5/5 OK (#13778 invariant holds). No other files changed since my prior file-by-file review (delta was exactly the manifest entry + the import line).

Merge authorization is covered: David has explicitly signed off on landing the remaining plugin-hardening PRs in this batch. CI green on this head, merge-tree clean, no open threads.

@Git-on-my-level
Git-on-my-level merged commit ce8ef46 into BasedHardware:main Sep 17, 2026
28 checks passed
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 needs-tests PR introduces logic that should be covered by tests python

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Plugin] Harden error handling, timeouts, null guards, and safe database validation in oauth notion plugin

2 participants