Skip to content

fix(auth): fall back to session-based auth in _load_user - #14569

Merged
KevinHuSh merged 4 commits into
infiniflow:mainfrom
mhtkarakose:fix/oauth-session-fallback
May 11, 2026
Merged

KevinHuSh merged 4 commits into
infiniflow:mainfrom
mhtkarakose:fix/oauth-session-fallback

Conversation

@mhtkarakose

Copy link
Copy Markdown
Contributor

Summary

Closes #13663.

OAuth / OIDC callbacks call login_user(user) which writes _user_id into the session cookie, but _load_user() in api/apps/__init__.py only ever looked at the Authorization header. The SPA's response interceptor wipes the Authorization value from localStorage on the first 401 it sees — meaning that during the post-redirect window after an OAuth login, a single transient 401 sends every subsequent request back to the login page even though login_user() had already established a perfectly good server-side session.

The reporter's analysis traces this all the way through the redirect → navigate('/') → first request → empty header → 401 → removeAll() → infinite-redirect-to-login chain.

What changed

  • New _load_user_from_session() helper that reads session["_user_id"], looks up the user in UserService (with the same StatusEnum.VALID and access_token checks already used elsewhere), and assigns g.user.
  • Every return None path in _load_user() now routes through that helper before giving up:
    • missing Authorization header
    • malformed bearer prefix
    • empty / too-short JWT payload
    • JWT signature failure
    • JWT-resolved user not found / has no access_token
    • APIToken.query() fallback exhausted

The JWT and API-token paths still take precedence — the session is only consulted when those can't authenticate the request. So existing local-login and SDK callers see no behaviour change; only OAuth / OIDC users that hit the original race now stay logged in.

The Bearer-prefix issue called out in #13663 (lines 103-110) is already handled in the current code, so this PR only addresses the second half of the report.

Test plan

  • Configure OIDC under oauth in service_conf.yaml
  • Click the OIDC login button, complete auth at the IdP
  • Confirm that navigating between pages no longer bounces back to /login
  • Confirm local email/password login still issues + accepts JWTs
  • Confirm SDK/API key callers still authenticate via Authorization: Bearer <api-token>

…13663)

OAuth / OIDC callbacks call login_user() which writes _user_id into the
session cookie, but _load_user() only looked at the Authorization header.
The SPA's response interceptor wipes the Authorization value from local
storage on the first 401 it sees, and during the post-redirect window
that empty header bounced every subsequent request straight back to the
login page.

Add a _load_user_from_session() helper and route every "no usable token"
exit through it: missing header, malformed bearer, empty/short JWT
payload, JWT signature failure, missing user record, and the
APIToken.query() fallback all now consult the session before giving up.
This restores the behaviour login_user() was always meant to provide
without breaking the existing JWT / API-token paths, which still take
precedence whenever they actually validate.
Copilot AI review requested due to automatic review settings May 4, 2026 09:17
@dosubot dosubot Bot added the size:M This PR changes 30-99 lines, ignoring generated files. label May 4, 2026
@coderabbitai

coderabbitai Bot commented May 4, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack
No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 56e4b012-a98f-4d40-8ffd-05f3429e91e4

📥 Commits

Reviewing files that changed from the base of the PR and between f927c9c and 22107df.

📒 Files selected for processing (2)
  • api/apps/__init__.py
  • test/testcases/test_web_api/test_system_app/test_apps_init_unit.py
🚧 Files skipped from review as they are similar to previous changes (2)
  • test/testcases/test_web_api/test_system_app/test_apps_init_unit.py
  • api/apps/init.py

📝 Walkthrough

Walkthrough

Authentication now falls back to a session-cookie lookup via a new _load_user_from_session() helper. _load_user() strips a leading "Bearer " from Authorization, enforces access-token format/length checks, and uses the session fallback on multiple failure paths. Page discovery/registration formatting was refactored; behavior preserved.

Changes

OAuth/OIDC Session Fallback & Bearer Handling

Layer / File(s) Summary
Session Fallback Helper
api/apps/__init__.py
_load_user_from_session() reads session["_user_id"], queries UserService for a VALID user, validates user.access_token (non-empty, len>=32, not INVALID_-prefixed), and sets g.user when valid.
Authorization Preprocessing
api/apps/__init__.py
_load_user() now strips a leading "Bearer " from the Authorization header before JWT decoding.
Token Validation & Lookup
api/apps/__init__.py
Enforces access-token length/format checks; routes JWT decode failures, invalid/empty/too-short decoded tokens, missing DB access tokens, and API-token lookup failures into the session fallback path.
Integration: Session Fallback Usage
api/apps/__init__.py
_load_user() calls _load_user_from_session() for missing/malformed Authorization, JWT/API token failures, and exceptions, returning the session-resolved user when applicable.
Page Discovery & Registration Refactor
api/apps/__init__.py
Condensed list-comprehension formatting in search_pages_path(), simplified register_page() expressions, and moved the register_backward_compat_routes import earlier; functional behavior unchanged.
Tests
test/testcases/test_web_api/test_system_app/test_apps_init_unit.py
Adds test_load_user_session_fallback and test_load_user_session_fallback_after_token_paths_fail covering session-based resolution, rejection of invalid/too-short tokens, none-when-no-session/header, and logged/swallowed session lookup exceptions.

Sequence Diagram(s)

sequenceDiagram
    participant Client as Client
    participant Server as Server (api/apps)
    participant DB as UserService / DB
    participant Session as Session Store

    Client->>Server: HTTP request (Authorization header + session cookie)
    alt Authorization header present
        Server->>Server: Strip "Bearer " if present
        Server->>Server: Attempt JWT.decode or API-token lookup
        alt token valid and user found
            Server->>DB: query by access_token
            DB-->>Server: user
            Server->>Server: validate token format/length
            Server-->>Client: proceed (g.user set)
        else token invalid or lookup failed
            Server->>Session: read session["_user_id"]
            alt session user id present
                Server->>DB: query by id
                DB-->>Server: user or None
                Server->>Server: validate session user's token
                Server-->>Client: proceed if valid, else 401
            else no session
                Server-->>Client: 401 / no user
            end
        end
    else no Authorization header
        Server->>Session: read session["_user_id"]
        alt session user id present
            Server->>DB: query by id
            DB-->>Server: user
            Server->>Server: validate token format/length
            Server-->>Client: proceed if valid, else 401
        else no session
            Server-->>Client: 401 / no user
        end
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 I hopped through headers, sniffed a Bearer trace,
Searched cookie burrows for a warm, safe place.
When tokens were brittle or hiding their face,
I nudged the session and found the right case —
Now logins stay cozy, no more frantic race.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 11.11% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately and concisely describes the main change: adding session-based authentication fallback in the _load_user function to fix OAuth/OIDC login issues.
Description check ✅ Passed The PR description comprehensively covers the problem being solved, what changed, and the test plan, following the template structure with clear context about the OAuth race condition.
Linked Issues check ✅ Passed The PR addresses both main objectives from #13663: it implements session-based fallback in _load_user() when JWT/API-token checks fail, and handles the Bearer prefix stripping before JWT decoding.
Out of Scope Changes check ✅ Passed Changes are limited to authentication fallback and page discovery refactoring in api/apps/init.py, with corresponding test coverage; all changes directly support the OAuth/OIDC session fallback objective.

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


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@dosubot dosubot Bot added the 🐞 bug Something isn't working, pull request that fix bug. label May 4, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

This PR fixes an OAuth/OIDC post-redirect logout loop by making server-side authentication fall back to the existing session cookie (session["_user_id"]) when header-based authentication can’t resolve a user in api/apps/__init__.py.

Changes:

  • Added _load_user_from_session() to resolve g.user via the session cookie created by login_user().
  • Updated _load_user() to consult the session fallback on missing/invalid Authorization, JWT decode failures, user lookup failures, and API-token fallback exhaustion.
  • Minor formatting/whitespace cleanups in the app init/module registration helpers.

Comment thread api/apps/__init__.py Outdated
Comment on lines +108 to +109
except Exception as e:
logging.warning(f"load_user from session got exception {e}")
Comment thread api/apps/__init__.py
Comment on lines 120 to 126
def _load_user():
jwt = Serializer(secret_key=settings.SECRET_KEY)
authorization = request.headers.get("Authorization")
g.user = None
if not authorization:
return None
return _load_user_from_session()

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
api/apps/__init__.py (1)

94-117: ⚡ Quick win

Add logs for the new session-auth fallback decisions.

This introduces a new authentication path, but normal fallback attempts/successes/failures are silent unless the DB query throws. A couple of non-PII logs here would make it much easier to debug the redirect-loop scenario this PR is fixing.

As per coding guidelines, "Add logging for new flows".

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/apps/__init__.py` around lines 94 - 117, The _load_user_from_session
function lacks informational logs for the new session-auth fallback; add non-PII
logging at key decision points: log when there is no _user_id in session, when
UserService.query returns no users (include the queried user_id but not
sensitive data), when a user is found but has no access_token or it is blank,
and when the fallback successfully resolves a user (log user.id or a masked
identifier). Use the existing logging module and reference the function name
_load_user_from_session and the call to UserService.query to place these
messages; keep logs concise and non-sensitive (do not log tokens).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@api/apps/__init__.py`:
- Around line 114-115: The session-fallback path currently only rejects empty
user.access_token; update that guard so it enforces the same validity rules used
by UserService.query(access_token=...), i.e. reject tokens that are too short
(len below the system MIN token length) or that start with the revocation prefix
"INVALID_" in addition to empty/whitespace checks; implement this by extending
the if condition around user.access_token to include a length check and prefix
check (or call the shared token-validation helper if one exists) so
stale/invalid tokens are not accepted.

---

Nitpick comments:
In `@api/apps/__init__.py`:
- Around line 94-117: The _load_user_from_session function lacks informational
logs for the new session-auth fallback; add non-PII logging at key decision
points: log when there is no _user_id in session, when UserService.query returns
no users (include the queried user_id but not sensitive data), when a user is
found but has no access_token or it is blank, and when the fallback successfully
resolves a user (log user.id or a masked identifier). Use the existing logging
module and reference the function name _load_user_from_session and the call to
UserService.query to place these messages; keep logs concise and non-sensitive
(do not log tokens).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: d0b13dc2-726c-4135-9d97-d0a6607501e4

📥 Commits

Reviewing files that changed from the base of the PR and between 24af087 and a0c4a61.

📒 Files selected for processing (1)
  • api/apps/__init__.py

Comment thread api/apps/__init__.py Resolved
Address the review notes on infiniflow#14569:

- Apply the same access-token rules in _load_user_from_session() that the
  JWT path uses: reject tokens shorter than 32 chars and tokens prefixed
  with "INVALID_" (the marker logout writes when revoking). Without
  these guards the new session fallback could otherwise keep a stale
  session authenticated after logout or after a corrupted token row.
- Switch the helper's exception logger to logging.exception(...) so the
  stack trace survives into production logs.
- Extend test_apps_init_unit.py with a test_load_user_session_fallback
  case covering: no-header + valid session, malformed bearer + valid
  session, INVALID_-prefixed token rejected, short-token rejected,
  no-session, and a database error during the session lookup.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (3)
api/apps/__init__.py (2)

108-123: ⚡ Quick win

Log when session fallback actually authenticates the request.

The new flow only logs failures. A small debug/info log on the success path would make it much easier to confirm in production that the request was recovered by _load_user_from_session() rather than by header auth.

🪵 Suggested change
     if not access_token or len(access_token) < 32 or access_token.startswith("INVALID_"):
         return None
+    logging.debug("Authenticated request via session fallback for user_id=%s", user_id)
     g.user = user
     return user

As per coding guidelines, "Add logging for new flows".

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/apps/__init__.py` around lines 108 - 123, Add an info-level log on the
success path of the session fallback so we record when _load_user_from_session
recovers authentication; after you set g.user = user (and before returning user)
call the app logger (or logging.info) to emit a clear message including the
user.id (or user.id/username) and that authentication was restored from session,
and optionally include truncated access_token metadata (e.g., masked or length)
for traceability; use the same context as UserService.query and the access_token
validation branch so it's easy to locate and won't leak secrets.

126-131: ⚡ Quick win

Reuse g.user instead of reloading auth on every current_user access.

current_user is a LocalProxy, so _load_user() runs every time the proxy is touched. Resetting g.user on Line 129 discards the request-scoped user you set later, which means the new session-fallback path can hit UserService.query(...) multiple times in a single request (@login_required first, then current_user.id in the handler).

♻️ Suggested change
 def _load_user():
+    if hasattr(g, "user"):
+        return g.user
+
+    g.user = None
     jwt = Serializer(secret_key=settings.SECRET_KEY)
     authorization = request.headers.get("Authorization")
-    g.user = None
     if not authorization:
         return _load_user_from_session()
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/apps/__init__.py` around lines 126 - 131, The _load_user function is
overwriting request-scoped g.user (causing repeated UserService.query calls) by
unconditionally setting g.user = None; instead, check and reuse an existing
g.user (e.g., if getattr(g, "user", None): return g.user) and remove the
unconditional reset, and ensure the session fallback path
(_load_user_from_session) assigns g.user before returning; update references in
current_user/_load_user and ensure only unset g.user triggers auth reload.
test/testcases/test_web_api/test_system_app/test_apps_init_unit.py (1)

177-237: ⚡ Quick win

Cover the JWT/API-token failure branches with a valid session too.

This test pins the missing-header and malformed-bearer cases, but the new return _load_user_from_session() edges after JWT decode failure and API-token exhaustion still are not covered by a positive “valid session wins” assertion. Those are part of the same regression surface and can drift independently.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/testcases/test_web_api/test_system_app/test_apps_init_unit.py` around
lines 177 - 237, The test misses asserting that after JWT decode failures and
API-token exhaustion the code still falls back to a valid session; update
test_load_user_session_fallback to add cases that set a
session["_user_id"]="user-1", monkeypatch apps_module.UserService.query to
return valid_user, and call apps_module._load_user() while providing
Authorization headers that trigger the JWT-decode-failure path and the
API-token-exhaustion path (e.g. a malformed/invalid JWT header and a header
representing an exhausted API token), asserting the result is valid_user for
both; use the same async-with quart_app.test_request_context blocks used
elsewhere in the test so these new checks integrate with the existing flow.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@api/apps/__init__.py`:
- Around line 108-123: Add an info-level log on the success path of the session
fallback so we record when _load_user_from_session recovers authentication;
after you set g.user = user (and before returning user) call the app logger (or
logging.info) to emit a clear message including the user.id (or
user.id/username) and that authentication was restored from session, and
optionally include truncated access_token metadata (e.g., masked or length) for
traceability; use the same context as UserService.query and the access_token
validation branch so it's easy to locate and won't leak secrets.
- Around line 126-131: The _load_user function is overwriting request-scoped
g.user (causing repeated UserService.query calls) by unconditionally setting
g.user = None; instead, check and reuse an existing g.user (e.g., if getattr(g,
"user", None): return g.user) and remove the unconditional reset, and ensure the
session fallback path (_load_user_from_session) assigns g.user before returning;
update references in current_user/_load_user and ensure only unset g.user
triggers auth reload.

In `@test/testcases/test_web_api/test_system_app/test_apps_init_unit.py`:
- Around line 177-237: The test misses asserting that after JWT decode failures
and API-token exhaustion the code still falls back to a valid session; update
test_load_user_session_fallback to add cases that set a
session["_user_id"]="user-1", monkeypatch apps_module.UserService.query to
return valid_user, and call apps_module._load_user() while providing
Authorization headers that trigger the JWT-decode-failure path and the
API-token-exhaustion path (e.g. a malformed/invalid JWT header and a header
representing an exhausted API token), asserting the result is valid_user for
both; use the same async-with quart_app.test_request_context blocks used
elsewhere in the test so these new checks integrate with the existing flow.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 91c2033c-c0a5-4da4-811e-d664ee1c5278

📥 Commits

Reviewing files that changed from the base of the PR and between a0c4a61 and 0a328cf.

📒 Files selected for processing (2)
  • api/apps/__init__.py
  • test/testcases/test_web_api/test_system_app/test_apps_init_unit.py

- Emit a debug-level log when _load_user_from_session() recovers a
  request so operators can confirm in production that auth came in via
  the session cookie rather than a header.
- Add a test that combines a malformed Authorization header (JWT
  decode raises, APIToken.query returns []) with a valid session to
  confirm the new fallback path also kicks in after the JWT and
  API-token branches give up — the regression surface CodeRabbit
  flagged.

(Skipping the unrelated suggestion to cache `g.user` across LocalProxy
accesses; that touches the existing per-request reset behaviour and is
out of scope for this fix.)
@KevinHuSh KevinHuSh added the ci Continue Integration label May 9, 2026
@codecov

codecov Bot commented May 9, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.16%. Comparing base (ee0de58) to head (22107df).
⚠️ Report is 14 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #14569   +/-   ##
=======================================
  Coverage   94.16%   94.16%           
=======================================
  Files          10       10           
  Lines         703      703           
  Branches      112      112           
=======================================
  Hits          662      662           
  Misses         25       25           
  Partials       16       16           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@KevinHuSh
KevinHuSh merged commit 7ec87f7 into infiniflow:main May 11, 2026
1 check passed
@dosubot dosubot Bot mentioned this pull request May 19, 2026
4 tasks done
Ricardo-M-L pushed a commit to Ricardo-M-L/ragflow that referenced this pull request Aug 17, 2026
…14569)

## Summary

Closes infiniflow#13663.

OAuth / OIDC callbacks call `login_user(user)` which writes `_user_id`
into the session cookie, but `_load_user()` in `api/apps/__init__.py`
only ever looked at the `Authorization` header. The SPA's response
interceptor wipes the Authorization value from `localStorage` on the
first 401 it sees — meaning that during the post-redirect window after
an OAuth login, a single transient 401 sends every subsequent request
back to the login page even though `login_user()` had already
established a perfectly good server-side session.

The reporter's analysis traces this all the way through the redirect →
`navigate('/')` → first request → empty header → 401 → `removeAll()` →
infinite-redirect-to-login chain.

## What changed

- New `_load_user_from_session()` helper that reads
`session["_user_id"]`, looks up the user in `UserService` (with the same
`StatusEnum.VALID` and `access_token` checks already used elsewhere),
and assigns `g.user`.
- Every `return None` path in `_load_user()` now routes through that
helper before giving up:
  - missing `Authorization` header
  - malformed `bearer ` prefix
  - empty / too-short JWT payload
  - JWT signature failure
  - JWT-resolved user not found / has no `access_token`
  - `APIToken.query()` fallback exhausted

The JWT and API-token paths still take precedence — the session is only
consulted when those can't authenticate the request. So existing
local-login and SDK callers see no behaviour change; only OAuth / OIDC
users that hit the original race now stay logged in.

The Bearer-prefix issue called out in infiniflow#13663 (lines 103-110) is already
handled in the current code, so this PR only addresses the second half
of the report.

## Test plan

- [ ] Configure OIDC under `oauth` in `service_conf.yaml`
- [ ] Click the OIDC login button, complete auth at the IdP
- [ ] Confirm that navigating between pages no longer bounces back to
`/login`
- [ ] Confirm local email/password login still issues + accepts JWTs
- [ ] Confirm SDK/API key callers still authenticate via `Authorization:
Bearer <api-token>`

---------

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

Labels

🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration size:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

OAuth/OIDC login fails: _load_user doesn't handle Bearer prefix or session fallback

3 participants