App icon indicating copy to clipboard operation
App copied to clipboard

[Due for payment on 2026-11-25] [$175] Prevent unnecessary SAML sign-outs during mobile session hydration

Open melvin-bot[bot] opened this issue 2 weeks ago • 18 comments

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
Issue OwnerCurrent Issue Owner: @allgandalf

melvin-bot[bot] avatar Nov 12 '26 19:11 melvin-bot[bot]

Triggered auto assignment to Contributor-plus team member for initial proposal review - @dmkt9 (External)

melvin-bot[bot] avatar Nov 12 '26 19:11 melvin-bot[bot]

Job added to Upwork: https://www.upwork.com/jobs/~022120958197360704418

melvin-bot[bot] avatar Nov 12 '26 19:11 melvin-bot[bot]

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

Authenticated web Home; not a mobile cold-start fixture
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.
Authenticated web Home; not a mobile cold-start fixture
✅

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

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:

  1. 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.
  2. Test delayed update-ID hydration separately; extend readiness only if that test demonstrates a gap.
  3. 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

MelvinBot avatar Nov 12 '26 19:11 MelvinBot

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?

  1. In Request.ts, move the enhanceParameters(...) call inside the .then() callback, directly before HttpUtils.xhr.
  2. Add a unit test in the existing Request tests: jest.isolateModules, mock NetworkStore.hasReadRequiredDataFromStorage with a deferred promise, call makeXHR (via processWithMiddleware), and assert HttpUtils.xhr has not been called. Then set a saved token and update ID in Onyx, resolve the deferred promise, and assert xhr receives that authToken and clientUpdateID, and that the [enhanceParameters] Sending request without authToken log never fires.
  3. Note: checkRequiredData (NetworkStore.ts:34-40) gates only on authToken and credentials. clientUpdateID comes 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 enhanceParameters lazy inside HttpUtils.xhr was rejected: it is a larger change and affects Authenticate, 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.

Stephen3453 avatar Nov 12 '26 19:11 Stephen3453

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:

  1. authToken in NetworkStore.ts is still undefined.
  2. enhanceParameters calls getAuthToken(), which returns undefined. Line 95 of enhanceParameters.ts falls back to null (finalParameters.authToken = authToken ?? null;) and captures clientUpdateID: -1.
  3. Later, storage hydration completes, NetworkStore populates the valid session authToken, and hasReadRequiredDataFromStorage() resolves.
  4. However, HttpUtils.xhr is invoked with the pre-captured finalParameters object containing authToken: null and clientUpdateID: -1.
  5. The backend receives the request without an authentication token and returns a 407 Not Authenticated response. 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?

  1. In src/libs/Request.ts, move the call to enhanceParameters inside the hasReadRequiredDataFromStorage().then(...) callback immediately before calling HttpUtils.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.

  1. In tests/unit/RequestTest.ts: Add a unit test simulating a request dispatched while hasReadRequiredDataFromStorage is pending. Verify that enhanceParameters (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.authToken inside .then(): mutating properties post-enhancement is error-prone, violates clean parameter construction, and fails to update other dependent fields like clientUpdateID or delegate. Moving the entire enhanceParameters call 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

kevinjosh10 avatar Nov 12 '26 19:11 kevinjosh10

📣 @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:

  1. Make sure you've read and understood the contributing guidelines.
  2. 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.
  3. 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.
  4. Copy the format below and paste it in a comment on this issue. Replace the placeholder text with your actual details. Screen Shot 2022-11-16 at 4 42 54 PM Format:
Contributor details
Your Expensify account email: <REPLACE EMAIL HERE>
Upwork Profile Link: <REPLACE LINK HERE>

melvin-bot[bot] avatar Nov 12 '26 19:11 melvin-bot[bot]

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:

  1. authToken in NetworkStore.ts is still undefined (Onyx has not finished reading ONYXKEYS.SESSION).
  2. enhanceParameters runs, reads getAuthToken() === undefined, logs [enhanceParameters] Sending request without authToken, sets finalParameters.authToken = null, and captures default values for session-dependent fields.
  3. Once storage hydration resolves, makeXHR executes HttpUtils.xhr, but sends the pre-captured finalParameters with authToken: null.
  4. The server responds with 407 Not Authenticated. In Reauthentication.ts, an unexpected 407 on an account where isSAMLRequired is 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?

  1. In src/libs/Request.ts, move enhanceParameters inside the hasReadRequiredDataFromStorage().then(...) callback immediately before calling HttpUtils.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.

  1. In tests/unit/RequestTest.ts, add a unit test that verifies just-in-time parameter enhancement across the hydration barrier:
    • Reset NetworkStore via resetHasReadRequiredDataFromStorage().
    • Initiate a network request through Request.processWithMiddleware(request).
    • Assert HttpUtils.xhr has not yet been called.
    • Populate ONYXKEYS.SESSION (providing authToken), allowing hasReadRequiredDataFromStorage() to resolve.
    • Assert HttpUtils.xhr is invoked with the hydrated authToken rather than null.

What alternative solutions did you explore? (Optional)

  • Widening NetworkStore.checkRequiredData() to wait for ONYX_UPDATES_LAST_UPDATE_ID_APPLIED_TO_CLIENT or ACCOUNT: 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.authToken inside .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

dhruvil-codes avatar Nov 12 '26 19:11 dhruvil-codes

⚠️ Invalid email. Please make sure to create an Expensify account with this email first here.

melvin-bot[bot] avatar Nov 12 '26 19:11 melvin-bot[bot]

Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~019004dd062e120600?mp_source=share

dhruvil-codes avatar Nov 12 '26 19:11 dhruvil-codes

✅ Contributor details stored successfully. Thank you for contributing to Expensify!

melvin-bot[bot] avatar Nov 12 '26 19:11 melvin-bot[bot]

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:

  1. enhanceParameters runs before hasReadRequiredDataFromStorage() 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);
        });
    }
    

    Because enhanceParameters(...) is called synchronously before hasReadRequiredDataFromStorage() resolves, getAuthToken() returns undefined (turning into finalParameters.authToken = null at src/libs/Network/enhanceParameters.ts:95) and lastUpdateIDAppliedToClient is still -1 (enhanceParameters.ts:16, 98). When hasReadRequiredDataFromStorage() subsequently resolves, HttpUtils.xhr sends that stale finalParameters snapshot.

  2. NetworkStore.checkRequiredData() (src/libs/Network/NetworkStore.ts:38-44) only waits for ONYXKEYS.SESSION and ONYXKEYS.CREDENTIALS, NOT ONYXKEYS.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.connectWithoutView reads its storage key independently via async native storage (SQLite / MMKV). Because ONYXKEYS.SESSION and ONYXKEYS.CREDENTIALS are registered in NetworkStore.ts, isReadyPromise resolves as soon as those two callbacks fire—even if ONYXKEYS.ONYX_UPDATES_LAST_UPDATE_ID_APPLIED_TO_CLIENT has not finished hydrating from storage yet!
    • Furthermore, resetHasReadRequiredDataFromStorage() (NetworkStore.ts:46-51) creates a new isReadyPromise without resetting the module-level hydration flags, so if SESSION or CREDENTIALS was already populated earlier, calling resetHasReadRequiredDataFromStorage() leaves authToken and credentials non-undefined until the next Onyx write.

What changes do you think we should make in order to solve the problem?

  1. Move enhanceParameters inside hasReadRequiredDataFromStorage().then(...) in src/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);
        });
    }
    
  2. Include ONYX_UPDATES_LAST_UPDATE_ID_APPLIED_TO_CLIENT hydration in NetworkStore.ts (and share getLastUpdateIDAppliedToClient() with enhanceParameters.ts):

    • Track whether ONYXKEYS.ONYX_UPDATES_LAST_UPDATE_ID_APPLIED_TO_CLIENT has received its initial storage callback (hasReadLastUpdateID = false -> true on callback, where an empty/unset storage key still fires the callback with undefined/null and sets lastUpdateIDAppliedToClient = -1).
    • Gate checkRequiredData() on authToken === undefined || credentials === undefined || !hasReadLastUpdateID so hasReadRequiredDataFromStorage() truly guarantees both authToken and clientUpdateID have hydrated from storage before enhanceParameters runs.
    • In resetHasReadRequiredDataFromStorage(), reset authToken = undefined, credentials = undefined, and hasReadLastUpdateID = false so tests and session resets cleanly re-arm the hydration barrier.
  3. 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 (or global.fetch) is not called while hydration is pending.
    • Hydrate ONYXKEYS.SESSION (authToken: 'saved-session-token'), ONYXKEYS.CREDENTIALS, and ONYXKEYS.ONYX_UPDATES_LAST_UPDATE_ID_APPLIED_TO_CLIENT (12345).
    • Verify the pending request waits for hydration and sends authToken: 'saved-session-token' and clientUpdateID: 12345 (never authToken: null or clientUpdateID: -1).

What alternative solutions did you explore? (Optional)

  • Only moving enhanceParameters inside .then() without gating checkRequiredData() on ONYX_UPDATES_LAST_UPDATE_ID_APPLIED_TO_CLIENT's initial callback: if SESSION and CREDENTIALS hydrate before ONYX_UPDATES_LAST_UPDATE_ID_APPLIED_TO_CLIENT, hasReadRequiredDataFromStorage() resolves while lastUpdateIDAppliedToClient is still -1, violating the requirement that startup requests wait and send both the saved authentication token and the saved clientUpdateID.

cocvn157 avatar Nov 13 '26 04:11 cocvn157

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. makeXHR has built the request parameters before waiting for the stored session since Request.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

  1. On iOS or Android, sign in with an account on a SAML required domain.
  2. Close the app fully.
  3. Open the app again.
  4. Send a message in any chat.
  5. Create an expense.
  6. 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 👎.

huult avatar Nov 18 '26 02:11 huult

This ticket is due for payment on 2026-11-25.

huult avatar Nov 18 '26 06:11 huult

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.

huult avatar Nov 23 '26 01:11 huult

Not overdue

huult avatar Nov 23 '26 01:11 huult

Updated the title to begin with [Due for payment on 2026-11-25], preserving the rest of the title.


view run

MelvinBot avatar Nov 23 '26 01:11 MelvinBot

go away melv

allgandalf avatar Nov 23 '26 07:11 allgandalf

Triggered auto assignment to @mallenexpensify (Awaiting Payment)