Repository navigation
fix(auth): fall back to session-based auth in _load_user - #14569
Conversation
…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.
|
ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (2)
📝 WalkthroughWalkthroughAuthentication now falls back to a session-cookie lookup via a new ChangesOAuth/OIDC Session Fallback & Bearer Handling
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
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ 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. Comment |
There was a problem hiding this comment.
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 resolveg.uservia the session cookie created bylogin_user(). - Updated
_load_user()to consult the session fallback on missing/invalidAuthorization, JWT decode failures, user lookup failures, and API-token fallback exhaustion. - Minor formatting/whitespace cleanups in the app init/module registration helpers.
| except Exception as e: | ||
| logging.warning(f"load_user from session got exception {e}") |
| 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() | ||
|
|
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
api/apps/__init__.py (1)
94-117: ⚡ Quick winAdd 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
📒 Files selected for processing (1)
api/apps/__init__.py
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.
There was a problem hiding this comment.
🧹 Nitpick comments (3)
api/apps/__init__.py (2)
108-123: ⚡ Quick winLog 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 userAs 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 winReuse
g.userinstead of reloading auth on everycurrent_useraccess.
current_useris aLocalProxy, so_load_user()runs every time the proxy is touched. Resettingg.useron Line 129 discards the request-scoped user you set later, which means the new session-fallback path can hitUserService.query(...)multiple times in a single request (@login_requiredfirst, thencurrent_user.idin 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 winCover 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
📒 Files selected for processing (2)
api/apps/__init__.pytest/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.)
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
…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]>
Summary
Closes #13663.
OAuth / OIDC callbacks call
login_user(user)which writes_user_idinto the session cookie, but_load_user()inapi/apps/__init__.pyonly ever looked at theAuthorizationheader. The SPA's response interceptor wipes the Authorization value fromlocalStorageon 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 thoughlogin_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
_load_user_from_session()helper that readssession["_user_id"], looks up the user inUserService(with the sameStatusEnum.VALIDandaccess_tokenchecks already used elsewhere), and assignsg.user.return Nonepath in_load_user()now routes through that helper before giving up:Authorizationheaderbearerprefixaccess_tokenAPIToken.query()fallback exhaustedThe 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
oauthinservice_conf.yaml/loginAuthorization: Bearer <api-token>