[Due for payment on 2026-11-25] [$175] Prevent unnecessary SAML sign-outs during mobile session hydration
Problem
On mobile startup, makeXHR enhances request parameters before waiting for stored session data. A request can therefore retain authToken: null and clientUpdateID: -1 even after hydration completes. The resulting 407 response can trigger unnecessary SAML sign-in despite a valid saved session.
Proposed fix
Move enhanceParameters() inside the hasReadRequiredDataFromStorage().then(...) callback, before sending the request.
Verification
Add a regression test that loads the request module and immediately initiates a request while hydration is pending. Verify it waits and sends the saved authentication token and client update ID.
Cover iOS and Android startup, background push handling, and persisted-request replay.
Upwork Automation - Do Not Edit
- Upwork Job URL: https://www.upwork.com/jobs/~022120958197360704418
- Upwork Job ID: 2120958197360704418
- Last Price Increase: 2026-11-12
Issue Owner
Current Issue Owner: @allgandalf
Triggered auto assignment to Contributor-plus team member for initial proposal review - @dmkt9 (External)
Job added to Upwork: https://www.upwork.com/jobs/~022120958197360704418
🤖 Web test steps verification results: ⚠️ partial
This issue cannot be safely reproduced in the ready web session. Mobile cold-start timing, pending hydration, and a SAML fixture were unavailable; the reported 407/SAML regression remains unverified.
| Step | Status |
|---|---|
Assess session and reproduction prerequisitesAuthenticated web Home was confirmed. The already-initialized session cannot establish mobile startup hydration timing. No sign-out, sign-in, source changes, or fabricated hydration state were attempted.![]() |
✅ |
Proposal
What is the root cause of that problem?
The parameter-ordering defect is confirmed; its role in the reported mobile sign-outs is not.
makeXHR captures authentication parameters before awaiting stored session data. If called before hydration, it can retain missing authentication even after the saved token becomes available. A subsequent 407 can trigger SAML sign-in without first retrying with that saved token.
Code evidence and important limitations
- Request.ts:25–33 captures parameters before the readiness barrier and sends the same object afterward.
- enhanceParameters.ts:80–106 converts uninitialized authentication to
null. Payload serialization omits that value rather than sending a literal null. - Reauthentication.ts:215–242 redirects SAML-required accounts after hydration without validating the saved token first.
Counterevidence: The pinned Onyx implementation hydrates storage before initializing subscriptions, and persisted replay has additional subscription barriers. No concrete startup caller was demonstrated to reach the problematic window.
Also, NetworkStore.ts:34–77 waits for session and credentials—not explicitly for clientUpdateID. Moving enhancement alone does not establish watermark readiness.
What changes do you think we should make in order to solve the problem?
For the confirmed ordering defect, move parameter enhancement inside the readiness callback, immediately before transmission.
Before treating this as the solution to the reported sign-outs:
- Add a fresh-module regression test: initiate an authenticated request while hydration callbacks are withheld, confirm no transmission, deliver saved state, then assert the transmitted token and update ID.
- Test delayed update-ID hydration separately; extend readiness only if that test demonstrates a gap.
- Reproduce an actual mobile startup, background-push, or persisted-replay sequence that reaches the early-capture window.
The existing Request tests passed 6/6, but do not cover this race.
What alternative solutions did you explore? (Optional)
Genuine server-side token expiry can produce the same SAML redirect. No production logs were queried because the issue supplies neither an affected request/account nor a bounded incident window. Those details are needed to distinguish expiry from missing-token transmission.
Related issue: Keep unsent receipts and comments when SAML signs someone out addresses consequences of SAML sign-out, not this proposed trigger.
Next Steps for Contributor+ team:
To accept: @MelvinBot implement [this](https://github.com/Expensify/App/issues/106764) to create a draft PR for the ordering hardening and regression coverage—not as a verified resolution of the mobile sign-outs.
To refine: @MelvinBot <your feedback>
To reject: Explain why you are rejecting Melvin's proposal.
view run · no recording available
Proposal
What is the root cause of that problem?
makeXHR calls enhanceParameters (src/libs/Request.ts:25) before it awaits hasReadRequiredDataFromStorage() (Request.ts:26). The result is frozen in finalParameters and sent unchanged after the barrier (Request.ts:27-28). A request issued during hydration therefore keeps whatever enhanceParameters read at that instant: authToken: null (enhanceParameters.ts:~96, from getAuthToken() still undefined) and clientUpdateID: -1 (enhanceParameters.ts:17, the initial value of lastUpdateIDAppliedToClient). The server answers 407, and reauthenticate then sees account?.isSAMLRequired and calls redirectToSignIn(SAML_REQUIRED) (Reauthentication.ts SAML branch), although the saved session was valid.
What changes do you think we should make in order to solve the problem?
- In
Request.ts, move theenhanceParameters(...)call inside the.then()callback, directly beforeHttpUtils.xhr. - Add a unit test in the existing Request tests:
jest.isolateModules, mockNetworkStore.hasReadRequiredDataFromStoragewith a deferred promise, callmakeXHR(viaprocessWithMiddleware), and assertHttpUtils.xhrhas not been called. Then set a saved token and update ID in Onyx, resolve the deferred promise, and assertxhrreceives thatauthTokenandclientUpdateID, and that the[enhanceParameters] Sending request without authTokenlog never fires. - Note:
checkRequiredData(NetworkStore.ts:34-40) gates only onauthTokenandcredentials.clientUpdateIDcomes from a separate Onyx connection, so after step 1 add a second assertion with that key delivered late, and widen the barrier only if it fails.
What alternative solutions did you explore? (Optional)
- MelvinBot's proposal (the only one so far) agrees on the ordering defect but stops short of a fix, because it could not show a startup caller that reaches the window. Mine is the same one-line move plus a test that creates the window deterministically, so the fix is proven without a device.
- Making
enhanceParameterslazy insideHttpUtils.xhrwas rejected: it is a larger change and affectsAuthenticate, which passes its own parameters. - Skipping the SAML redirect on a first 407 and retrying the saved token was rejected: it hides the cause and delays genuine expiry handling.
Proposal
What is the root cause of that problem?
In src/libs/Request.ts:25-30:
function makeXHR<TKey extends OnyxKey>(request: Request<TKey>): Promise<Response<TKey> | void> {
const finalParameters = enhanceParameters(request.command, request?.data ?? {});
return hasReadRequiredDataFromStorage().then((): Promise<Response<TKey> | void> => {
return HttpUtils.xhr(request.command, finalParameters, request.type, request.shouldUseSecure, request.initiatedOffline);
});
}
enhanceParameters() is executed synchronously on line 26 before awaiting hasReadRequiredDataFromStorage().
During mobile app cold startup (or background push handling / persisted request replay), if a network request is initiated before Onyx finishes reading SESSION and CREDENTIALS from local storage:
authTokeninNetworkStore.tsis stillundefined.enhanceParameterscallsgetAuthToken(), which returnsundefined. Line 95 ofenhanceParameters.tsfalls back tonull(finalParameters.authToken = authToken ?? null;) and capturesclientUpdateID: -1.- Later, storage hydration completes,
NetworkStorepopulates the valid sessionauthToken, andhasReadRequiredDataFromStorage()resolves. - However,
HttpUtils.xhris invoked with the pre-capturedfinalParametersobject containingauthToken: nullandclientUpdateID: -1. - The backend receives the request without an authentication token and returns a
407 Not Authenticatedresponse. For accounts configured with SAML, this unexpected 407 triggers reauthentication / SAML redirect, unnecessarily signing out the user despite having a valid saved session in storage.
What changes do you think we should make in order to solve the problem?
- In
src/libs/Request.ts, move the call toenhanceParametersinside thehasReadRequiredDataFromStorage().then(...)callback immediately before callingHttpUtils.xhr:
function makeXHR<TKey extends OnyxKey>(request: Request<TKey>): Promise<Response<TKey> | void> {
return hasReadRequiredDataFromStorage().then((): Promise<Response<TKey> | void> => {
const finalParameters = enhanceParameters(request.command, request?.data ?? {});
return HttpUtils.xhr(request.command, finalParameters, request.type, request.shouldUseSecure, request.initiatedOffline);
});
}
This guarantees that parameter enhancement always reads the latest hydrated authToken, accountID, clientUpdateID, and credentials from NetworkStore.
- In
tests/unit/RequestTest.ts: Add a unit test simulating a request dispatched whilehasReadRequiredDataFromStorageis pending. Verify thatenhanceParameters(and the resulting XHR call) is evaluated with the hydrated session data once the storage promise resolves.
What alternative solutions did you explore? (Optional)
- Mutating or re-evaluating
finalParameters.authTokeninside.then(): mutating properties post-enhancement is error-prone, violates clean parameter construction, and fails to update other dependent fields likeclientUpdateIDordelegate. Moving the entireenhanceParameterscall inside the resolved storage callback is cleaner and guarantees all parameters are constructed atomically with fully hydrated state.
Contributor details
Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~0131dae36abcf59374
📣 @FueledByRedBull! 📣 Hey, it seems we don’t have your contributor details yet! You'll only have to do this once, and this is how we'll hire you on Upwork. Please follow these steps:
- Make sure you've read and understood the contributing guidelines.
- Get the email address used to login to your Expensify account. If you don't already have an Expensify account, create one here. If you have multiple accounts (e.g. one for testing), please use your main account email.
- Get the link to your Upwork profile. It's necessary because we only pay via Upwork. You can access it by logging in, and then clicking on your name. It'll look like this. If you don't already have an account, sign up for one here.
- Copy the format below and paste it in a comment on this issue. Replace the placeholder text with your actual details.
Format:
Contributor details
Your Expensify account email: <REPLACE EMAIL HERE>
Upwork Profile Link: <REPLACE LINK HERE>
Proposal
What is the root cause of that problem?
In src/libs/Request.ts:25-30:
function makeXHR<TKey extends OnyxKey>(request: Request<TKey>): Promise<Response<TKey> | void> {
const finalParameters = enhanceParameters(request.command, request?.data ?? {});
return hasReadRequiredDataFromStorage().then((): Promise<Response<TKey> | void> => {
return HttpUtils.xhr(request.command, finalParameters, request.type, request.shouldUseSecure, request.initiatedOffline);
});
}
enhanceParameters() is invoked synchronously before waiting for hasReadRequiredDataFromStorage(). On mobile startup, background push handling, or persisted request replay:
authTokeninNetworkStore.tsis stillundefined(Onyx has not finished readingONYXKEYS.SESSION).enhanceParametersruns, readsgetAuthToken() === undefined, logs[enhanceParameters] Sending request without authToken, setsfinalParameters.authToken = null, and captures default values for session-dependent fields.- Once storage hydration resolves,
makeXHRexecutesHttpUtils.xhr, but sends the pre-capturedfinalParameterswithauthToken: null. - The server responds with
407 Not Authenticated. InReauthentication.ts, an unexpected 407 on an account whereisSAMLRequiredis true triggers a redirect to SAML sign-in, wiping the active session despite valid credentials being saved in local storage.
What changes do you think we should make in order to solve the problem?
- In
src/libs/Request.ts, moveenhanceParametersinside thehasReadRequiredDataFromStorage().then(...)callback immediately before callingHttpUtils.xhr:
function makeXHR<TKey extends OnyxKey>(request: Request<TKey>): Promise<Response<TKey> | void> {
return hasReadRequiredDataFromStorage().then((): Promise<Response<TKey> | void> => {
const finalParameters = enhanceParameters(request.command, request?.data ?? {});
return HttpUtils.xhr(request.command, finalParameters, request.type, request.shouldUseSecure, request.initiatedOffline);
});
}
This guarantees enhanceParameters reads authToken, email, and other session metadata just-in-time once storage hydration has completed.
- In
tests/unit/RequestTest.ts, add a unit test that verifies just-in-time parameter enhancement across the hydration barrier:- Reset
NetworkStoreviaresetHasReadRequiredDataFromStorage(). - Initiate a network request through
Request.processWithMiddleware(request). - Assert
HttpUtils.xhrhas not yet been called. - Populate
ONYXKEYS.SESSION(providingauthToken), allowinghasReadRequiredDataFromStorage()to resolve. - Assert
HttpUtils.xhris invoked with the hydratedauthTokenrather thannull.
- Reset
What alternative solutions did you explore? (Optional)
- Widening
NetworkStore.checkRequiredData()to wait forONYX_UPDATES_LAST_UPDATE_ID_APPLIED_TO_CLIENTorACCOUNT: Rejected because non-auth keys can be empty/undefined on fresh installs or cleared sessions, which would unnecessarily block the readiness promise or require extra fallback state machines. Gating on auth data while deferring parameter construction to dispatch time is the minimal, clean fix. - Mutating
finalParameters.authTokeninside.then(): Rejected because piecemeal mutation of frozen request objects is error-prone and violates clean parameter construction.
Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~019004dd062e120600?mp_source=share
⚠️ Invalid email. Please make sure to create an Expensify account with this email first here.
Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~019004dd062e120600?mp_source=share
✅ Contributor details stored successfully. Thank you for contributing to Expensify!
Proposal
Please re-state the problem that we are trying to solve in this issue.
On mobile cold start, background push notification handling, or persisted request replay, makeXHR enhances request parameters before waiting for Onyx session/storage hydration (hasReadRequiredDataFromStorage()). As a result, any request initiated while hydration is still pending freezes authToken: null and clientUpdateID: -1 into finalParameters even after hydration resolves—causing an unnecessary 407 Not Authenticated response and triggering SAML sign-out despite a valid saved session.
What is the root cause of that problem?
There are two coupled issues in src/libs/Request.ts and src/libs/Network/NetworkStore.ts:
-
enhanceParametersruns beforehasReadRequiredDataFromStorage()insrc/libs/Request.ts:25-30:function makeXHR<TKey extends OnyxKey>(request: Request<TKey>): Promise<Response<TKey> | void> { const finalParameters = enhanceParameters(request.command, request?.data ?? {}); return hasReadRequiredDataFromStorage().then((): Promise<Response<TKey> | void> => { return HttpUtils.xhr(request.command, finalParameters, request.type, request.shouldUseSecure, request.initiatedOffline); }); }Because
enhanceParameters(...)is called synchronously beforehasReadRequiredDataFromStorage()resolves,getAuthToken()returnsundefined(turning intofinalParameters.authToken = nullatsrc/libs/Network/enhanceParameters.ts:95) andlastUpdateIDAppliedToClientis still-1(enhanceParameters.ts:16, 98). WhenhasReadRequiredDataFromStorage()subsequently resolves,HttpUtils.xhrsends that stalefinalParameterssnapshot. -
NetworkStore.checkRequiredData()(src/libs/Network/NetworkStore.ts:38-44) only waits forONYXKEYS.SESSIONandONYXKEYS.CREDENTIALS, NOTONYXKEYS.ONYX_UPDATES_LAST_UPDATE_ID_APPLIED_TO_CLIENT:- In
NetworkStore.ts:38-44:function checkRequiredData() { if (authToken === undefined || credentials === undefined) { return; } resolveIsReadyPromise(); } - And in
enhanceParameters.ts:16-28:let lastUpdateIDAppliedToClient = -1; Onyx.connectWithoutView({ key: ONYXKEYS.ONYX_UPDATES_LAST_UPDATE_ID_APPLIED_TO_CLIENT, callback: (value) => { if (value) { lastUpdateIDAppliedToClient = value; } else { lastUpdateIDAppliedToClient = -1; } }, }); - Each
Onyx.connectWithoutViewreads its storage key independently via async native storage (SQLite/MMKV). BecauseONYXKEYS.SESSIONandONYXKEYS.CREDENTIALSare registered inNetworkStore.ts,isReadyPromiseresolves as soon as those two callbacks fire—even ifONYXKEYS.ONYX_UPDATES_LAST_UPDATE_ID_APPLIED_TO_CLIENThas not finished hydrating from storage yet! - Furthermore,
resetHasReadRequiredDataFromStorage()(NetworkStore.ts:46-51) creates a newisReadyPromisewithout resetting the module-level hydration flags, so ifSESSIONorCREDENTIALSwas already populated earlier, callingresetHasReadRequiredDataFromStorage()leavesauthTokenandcredentialsnon-undefineduntil the next Onyx write.
- In
What changes do you think we should make in order to solve the problem?
-
Move
enhanceParametersinsidehasReadRequiredDataFromStorage().then(...)insrc/libs/Request.ts:25-30:function makeXHR<TKey extends OnyxKey>(request: Request<TKey>): Promise<Response<TKey> | void> { return hasReadRequiredDataFromStorage().then((): Promise<Response<TKey> | void> => { const finalParameters = enhanceParameters(request.command, request?.data ?? {}); return HttpUtils.xhr(request.command, finalParameters, request.type, request.shouldUseSecure, request.initiatedOffline); }); } -
Include
ONYX_UPDATES_LAST_UPDATE_ID_APPLIED_TO_CLIENThydration inNetworkStore.ts(and sharegetLastUpdateIDAppliedToClient()withenhanceParameters.ts):- Track whether
ONYXKEYS.ONYX_UPDATES_LAST_UPDATE_ID_APPLIED_TO_CLIENThas received its initial storage callback (hasReadLastUpdateID = false->trueon callback, where an empty/unset storage key still fires the callback withundefined/nulland setslastUpdateIDAppliedToClient = -1). - Gate
checkRequiredData()onauthToken === undefined || credentials === undefined || !hasReadLastUpdateIDsohasReadRequiredDataFromStorage()truly guarantees bothauthTokenandclientUpdateIDhave hydrated from storage beforeenhanceParametersruns. - In
resetHasReadRequiredDataFromStorage(), resetauthToken = undefined,credentials = undefined, andhasReadLastUpdateID = falseso tests and session resets cleanly re-arm the hydration barrier.
- Track whether
-
Add the regression test in
tests/unit/RequestTest.ts:- Load the request module / reset the storage readiness barrier while hydration is pending (
resetHasReadRequiredDataFromStorage()). - Immediately initiate a request via
Request.processWithMiddleware({command: WRITE_COMMANDS.OPEN_APP, data: {}}). - Verify
HttpUtils.xhr(orglobal.fetch) is not called while hydration is pending. - Hydrate
ONYXKEYS.SESSION(authToken: 'saved-session-token'),ONYXKEYS.CREDENTIALS, andONYXKEYS.ONYX_UPDATES_LAST_UPDATE_ID_APPLIED_TO_CLIENT(12345). - Verify the pending request waits for hydration and sends
authToken: 'saved-session-token'andclientUpdateID: 12345(neverauthToken: nullorclientUpdateID: -1).
- Load the request module / reset the storage readiness barrier while hydration is pending (
What alternative solutions did you explore? (Optional)
- Only moving
enhanceParametersinside.then()without gatingcheckRequiredData()onONYX_UPDATES_LAST_UPDATE_ID_APPLIED_TO_CLIENT's initial callback: ifSESSIONandCREDENTIALShydrate beforeONYX_UPDATES_LAST_UPDATE_ID_APPLIED_TO_CLIENT,hasReadRequiredDataFromStorage()resolves whilelastUpdateIDAppliedToClientis still-1, violating the requirement that startup requests wait and send both the saved authentication token and the savedclientUpdateID.
Contributor+ Checklist:
-
[x] [Contributor] The offending PR and associated issue have been commented on, pointing out the bug it caused and why, so the author and reviewers can learn from the mistake.
Link to the comment on the PR: N/A - Result of the original design.
makeXHRhas built the request parameters before waiting for the stored session sinceRequest.js, and the case of a request made before hydration was never handled. Link to the comment on the Issue: N/A -
[x] [Contributor] If the regression was CRITICAL (e.g. interrupts a core flow) A discussion in #expensify-open-source has been started about whether any other steps should be taken (e.g. updating the PR review checklist) in order to catch this type of bug sooner.
Link to discussion: N/A
-
[x] [Contributor] If it was decided to create a regression test for the bug, please propose the regression test steps using the template below to ensure the same bug will not reach production again.
Regression Test Proposal
- On iOS or Android, sign in with an account on a SAML required domain.
- Close the app fully.
- Open the app again.
- Send a message in any chat.
- Create an expense.
- Verify that you stay signed in, that you are not sent to the company sign-in page after reopening the app, and that both the message and the expense go through.
Do we agree 👍 or 👎.
This ticket is due for payment on 2026-11-25.
This ticket is due for payment on 2026-11-25.
@MelvinBot Please help update the ticket title by adding [Due for payment on 2026-11-25] at the beginning of the title.
Not overdue
Updated the title to begin with [Due for payment on 2026-11-25], preserving the rest of the title.
go away melv
Triggered auto assignment to @mallenexpensify (Awaiting Payment)