openhuman icon indicating copy to clipboard operation
openhuman copied to clipboard

fix(auth): narrow SessionExpired to confirmed OpenHuman backend 401s

Open M3gA-Mind opened this issue 6 months ago • 1 comments

Summary

  • Narrows is_session_expired_error in src/core/jsonrpc.rs so DomainEvent::SessionExpired only fires for confirmed OpenHuman session expiry, not for downstream provider 401s.
  • Adds is_downstream_provider_auth_error helper for diagnostic logging only (no session side-effects).
  • Adds 'provider_auth' error kind to CoreRpcErrorKind in coreRpcClient.ts; tightens classifyRpcError with the same HTTP-method-prefix logic.
  • Fixes Discord card-click logout (issue #2285) as a direct consequence.

Root Cause

is_session_expired_error used a loose "401 + unauthorized" string match. Discord bot-token failures arrive as "Discord API error: Discord list guilds failed (401): Unauthorized" — which contains both "401" and "unauthorized" — causing the full user session to be cleared on every Discord card interaction.

Fix

OpenHuman backend errors (from authed_json in src/api/rest.rs) always use the format "{HTTP_METHOD} /path failed (401 Unauthorized): {body}". Provider errors start with the provider name. The fix keeps the "401 + unauthorized" branch only when the message starts with an HTTP method verb, which matches backend paths while excluding Discord, OpenAI, Anthropic, Composio, etc.

Test plan

  • [x] src/core/jsonrpc_tests.rs — 10 is_session_expired_error tests covering: HTTP-method-prefix matches, Discord exclusion, BYO-key exclusion, Composio exclusion, explicit markers still match
  • [x] app/src/services/__tests__/coreRpcClient.test.ts — 3 new test.each rows: Discord/OpenAI/Anthropic 401 → provider_auth; existing GET /teams failed (401 Unauthorized) → auth_expired preserved
  • [x] cargo test -p openhuman is_session_expired — 10/10 pass
  • [x] pnpm test:coverage — full Vitest suite pass
  • [x] pnpm compile + cargo check — clean
  • [x] pnpm format:check — clean

Submission Checklist

  • [x] Tests added or updated (happy path + at least one failure / edge case)
  • [x] Diff coverage ≥ 80% — all new/changed lines in jsonrpc.rs and coreRpcClient.ts covered by unit tests
  • [x] No new external network dependencies introduced
  • [x] N/A: Coverage matrix — no new production feature rows
  • [x] N/A: Manual smoke checklist — no release surfaces touched

Related

Closes #2286 Related: #2285 (Discord card-click logout — fixed as a consequence of this change)


AI Authored PR Metadata (required for Codex/Linear PRs)

Linear Issue

  • Key: N/A
  • URL: N/A

Commit & Branch

  • Branch: fix/session-expired-cascade-2286
  • Commit SHA: a0da2423

Validation Run

  • [x] pnpm --filter openhuman-app compile
  • [x] pnpm --filter openhuman-app format:check
  • [x] pnpm --filter openhuman-app lint
  • [x] cargo check --manifest-path Cargo.toml
  • [x] pnpm test:coverage (Vitest full suite)
  • [x] cargo test -p openhuman is_session_expired (10/10 pass)

Validation Blocked

  • command: N/A
  • error: N/A
  • impact: N/A

Behavior Changes

  • Intended behavior change: provider-auth 401s (Discord, OpenAI BYO-key, Composio direct-mode) no longer clear the user session
  • User-visible effect: clicking the Discord channel card no longer logs the user out; BYO-key misconfiguration no longer forces re-auth

Parity Contract

  • Legacy behavior preserved: OpenHuman backend 401s (GET /teams failed (401 Unauthorized)) still trigger session expiry
  • Guard/fallback/dispatch parity checks: api_error in inference/provider/ops.rs still publishes SessionExpired directly for backend auth failures (independent of this fix)

Duplicate / Superseded PR Handling

  • Duplicate PR(s): none
  • Canonical PR: this PR

Summary by CodeRabbit

  • Bug Fixes

    • Improved error classification to distinguish user session expiry from external provider authentication failures, reducing mistaken session terminations and improving recovery and logging behavior.
  • Tests

    • Expanded and tightened test coverage to ensure confirmed session-expiry signals are detected while external API 401/unauthorized responses do not trigger session-expiry handling.

Review Change Stack

M3gA-Mind avatar May 20 '26 14:05 M3gA-Mind

[!CAUTION]

Review failed

Failed to post review comments

📝 Walkthrough

Walkthrough

This PR narrows SessionExpired publication to confirmed OpenHuman user-session expiry by introducing a provider_auth error kind, tightening session-expiry detection to require explicit markers or HTTP-method-prefixed backend 401s, and logging downstream provider authorization failures instead of clearing the session.

Changes

Session Expiry vs. Provider Auth Distinction

Layer / File(s) Summary
Error kind and RPC classification contract
app/src/services/coreRpcClient.ts
CoreRpcErrorKind exports a new provider_auth variant to distinguish downstream provider/integration 401 failures from user-session expiry.
TypeScript RPC error classifier and tests
app/src/services/coreRpcClient.ts, app/src/services/__tests__/coreRpcClient.test.ts
classifyRpcError expands regex/marker checks to separate explicit backend/session-expiry signals from downstream provider 401s and invalid-token patterns, returning provider_auth for provider errors; tests assert Discord, OpenAI, and Anthropic 401s classify as provider_auth.
Rust session-expiry predicate
src/core/jsonrpc.rs
is_session_expired_error rewritten to match only explicit OpenHuman session markers via observability helper or HTTP-method-prefixed backend 401s; diagnostic-only predicate remains for logging.
invoke_method integration and logging
src/core/jsonrpc.rs
invoke_method publishes SessionExpired only when is_session_expired_error confirms expiry and now logs non-expiry provider 401s at info level without triggering session teardown.
Test coverage for session-expiry and provider-auth separation
src/core/jsonrpc_tests.rs
Tests now require HTTP-method-prefixed backend 401 matching for session expiry, add positive OpenHuman backend 401 cases, and add regression negatives for Discord and BYO-key provider 401s; "invalid token" no longer matches session-expiry.

Sequence Diagram(s)

sequenceDiagram
  participant invoke_method
  participant is_session_expired_error
  participant is_downstream_provider_auth_error
  participant SessionExpiredEvent

  invoke_method->>is_session_expired_error: check error text
  is_session_expired_error-->>invoke_method: true (explicit session expiry)
  invoke_method->>SessionExpiredEvent: publish SessionExpired (sanitized reason)
  invoke_method->>is_downstream_provider_auth_error: else check provider 401 patterns
  is_downstream_provider_auth_error-->>invoke_method: true (provider 401)
  invoke_method-->>invoke_method: log info (provider auth, no teardown)

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Possibly related issues

  • #2285 — Similar objective to prevent downstream 401s (e.g., Discord card) from triggering SessionExpired and logging out users.

Suggested reviewers

  • senamakel
  • graycyrus

Poem

🐰 I nibble logs and chase the clue,
A 401 from Discord stays true—
Provider slips, the session stays,
I hop and patch the graceful way. 🥕

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and accurately summarizes the main objective: narrowing SessionExpired classification to only confirmed OpenHuman backend 401s, which is the primary focus of this PR.
Linked Issues check ✅ Passed The PR fully addresses all coding objectives from issue #2286: narrows SessionExpired to confirmed OpenHuman backend 401s, adds provider_auth classification, tightens HTTP-method-prefix detection, excludes downstream provider 401s, and includes comprehensive test coverage meeting diff coverage ≥80%.
Out of Scope Changes check ✅ Passed All changes are scoped to the stated objectives: error classification narrowing in Rust and TypeScript, test additions, and helper function additions directly supporting the SessionExpired fix.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Comment @coderabbitai help to get the list of available commands and usage tips.

coderabbitai[bot] avatar May 20 '26 14:05 coderabbitai[bot]

huge thanks @m3ga-mind 🙌 love how surgical this fix is, scoping sessionexpired to only confirmed openhuman 401s (and keeping provider auth stuff as diagnostic-only) is exactly the kind of nuance that saves so much debugging pain later. always a treat seeing your prs land 🚀

senamakel avatar May 21 '26 02:05 senamakel

Summary

  • Narrows is_session_expired_error in src/core/jsonrpc.rs so DomainEvent::SessionExpired only fires for confirmed OpenHuman session expiry, not for downstream provider 401s.
  • Adds is_downstream_provider_auth_error helper for diagnostic logging only (no session side-effects).
  • Adds 'provider_auth' error kind to CoreRpcErrorKind in coreRpcClient.ts; tightens classifyRpcError with the same HTTP-method-prefix logic.
  • Fixes Discord card-click logout (issue #2285) as a direct consequence.

Root Cause

is_session_expired_error used a loose "401 + unauthorized" string match. Discord bot-token failures arrive as "Discord API error: Discord list guilds failed (401): Unauthorized" — which contains both "401" and "unauthorized" — causing the full user session to be cleared on every Discord card interaction.

Fix

OpenHuman backend errors (from authed_json in src/api/rest.rs) always use the format "{HTTP_METHOD} /path failed (401 Unauthorized): {body}". Provider errors start with the provider name. The fix keeps the "401 + unauthorized" branch only when the message starts with an HTTP method verb, which matches backend paths while excluding Discord, OpenAI, Anthropic, Composio, etc.

Test plan

  • [x] src/core/jsonrpc_tests.rs — 10 is_session_expired_error tests covering: HTTP-method-prefix matches, Discord exclusion, BYO-key exclusion, Composio exclusion, explicit markers still match
  • [x] app/src/services/__tests__/coreRpcClient.test.ts — 3 new test.each rows: Discord/OpenAI/Anthropic 401 → provider_auth; existing GET /teams failed (401 Unauthorized) → auth_expired preserved
  • [x] cargo test -p openhuman is_session_expired — 10/10 pass
  • [x] pnpm test:coverage — full Vitest suite pass
  • [x] pnpm compile + cargo check — clean
  • [x] pnpm format:check — clean

Submission Checklist

  • [x] Tests added or updated (happy path + at least one failure / edge case)
  • [x] Diff coverage ≥ 80% — all new/changed lines in jsonrpc.rs and coreRpcClient.ts covered by unit tests
  • [x] No new external network dependencies introduced
  • [x] N/A: Coverage matrix — no new production feature rows
  • [x] N/A: Manual smoke checklist — no release surfaces touched

Related

Closes #2286 Related: #2285 (Discord card-click logout — fixed as a consequence of this change)


AI Authored PR Metadata (required for Codex/Linear PRs)

Linear Issue

  • Key: N/A
  • URL: N/A

Commit & Branch

  • Branch: fix/session-expired-cascade-2286
  • Commit SHA: a0da2423

Validation Run

  • [x] pnpm --filter openhuman-app compile
  • [x] pnpm --filter openhuman-app format:check
  • [x] pnpm --filter openhuman-app lint
  • [x] cargo check --manifest-path Cargo.toml
  • [x] pnpm test:coverage (Vitest full suite)
  • [x] cargo test -p openhuman is_session_expired (10/10 pass)

Validation Blocked

  • command: N/A
  • error: N/A
  • impact: N/A

Behavior Changes

  • Intended behavior change: provider-auth 401s (Discord, OpenAI BYO-key, Composio direct-mode) no longer clear the user session
  • User-visible effect: clicking the Discord channel card no longer logs the user out; BYO-key misconfiguration no longer forces re-auth

Parity Contract

  • Legacy behavior preserved: OpenHuman backend 401s (GET /teams failed (401 Unauthorized)) still trigger session expiry
  • Guard/fallback/dispatch parity checks: api_error in inference/provider/ops.rs still publishes SessionExpired directly for backend auth failures (independent of this fix)

Duplicate / Superseded PR Handling

  • Duplicate PR(s): none
  • Canonical PR: this PR

Summary by CodeRabbit

  • Bug Fixes

    • Improved error classification to distinguish user session expiry from external provider authentication failures, reducing mistaken session terminations and improving recovery and logging behavior.
  • Tests

    • Expanded and tightened test coverage to ensure confirmed session-expiry signals are detected while external API 401/unauthorized responses do not trigger session-expiry handling.

Review Change Stack

Auto runn

fzamel3333-ai avatar May 22 '26 11:05 fzamel3333-ai

Json

fzamel3333-ai avatar May 25 '26 23:05 fzamel3333-ai