Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
204c2ae
Add accountID to the GPS draft so it can be owner-checked
allgandalf Aug 4, 2026
0096067
Stamp the starting user on the GPS draft
allgandalf Aug 4, 2026
4161915
Keep the GPS trip across a forced SAML re-auth
allgandalf Aug 4, 2026
2cab489
Only keep a live trip, and stamp its owner on the way out
allgandalf Aug 4, 2026
b148569
Never offer a resumed trip to a different user
allgandalf Aug 4, 2026
226ad5f
Rename the owner flag to satisfy no-negated-variables
allgandalf Aug 4, 2026
e369d33
Cover the GPS trip surviving a forced re-auth
allgandalf Aug 4, 2026
cfdb42a
Do not let an image reauth sign the user out when it cannot refresh s…
allgandalf Aug 4, 2026
637feab
Keep a valid attachment token instead of blanking on a session-age guess
allgandalf Aug 4, 2026
08fac85
Merge branch 'Expensify:main' into gps-trip-survives-forced-reauth
allgandalf Aug 7, 2026
d9bddf3
Move canReauthenticateSilently next to the branches it predicts
allgandalf Aug 12, 2026
20485c7
Say why the GPS draft read has to be a subscription
allgandalf Aug 12, 2026
6b0d9e5
Do not suppress reauth before Onyx has loaded credentials
allgandalf Aug 12, 2026
86eb524
Never keep a GPS trip we cannot record an owner for
allgandalf Aug 12, 2026
c854287
Simplify the canReauthenticateSilently doc
allgandalf Aug 12, 2026
5a0a1ec
Merge remote-tracking branch 'upstream/main' into HEAD
allgandalf Aug 13, 2026
88ccfa3
Read the GPS draft on demand instead of subscribing to it
allgandalf Aug 13, 2026
a67e9df
Merge remote-tracking branch 'upstream/main' into HEAD
allgandalf Aug 16, 2026
6d92bb9
Preserve the trip without reading Onyx during sign out
allgandalf Aug 16, 2026
63052b7
Check trip ownership with useOnyx once the session has loaded
allgandalf Aug 16, 2026
ff2210a
Seed the trip owner the way a real trip records it
allgandalf Aug 16, 2026
95222c0
Merge remote-tracking branch 'upstream/main' into HEAD
allgandalf Aug 18, 2026
6f039fb
Use the shared accountID selector
allgandalf Aug 18, 2026
e60f191
Merge remote-tracking branch 'upstream/main' into gps-trip-survives-f…
allgandalf Aug 20, 2026
b489379
revert unintended formatting changes
allgandalf Aug 20, 2026
e972ed8
revert unintended formatting changes in AuthScreensInitHandler
allgandalf Aug 20, 2026
b9508bc
Merge remote-tracking branch 'upstream/main' into HEAD
allgandalf Aug 21, 2026
b66fdf8
move the attachment fix to a follow up
allgandalf Aug 21, 2026
1fa2818
shorten comments
allgandalf Aug 21, 2026
87e9830
keep a trip that records no accountID
allgandalf Aug 21, 2026
3693f10
add test for the trip owner check
allgandalf Aug 21, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 25 additions & 1 deletion src/components/GPSTripStateChecker/index.native.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import useLocalize from '@hooks/useLocalize';
import useNetwork from '@hooks/useNetwork';
import useOnyx from '@hooks/useOnyx';

import {resetGPSDraftDetails} from '@libs/actions/GPSDraftDetails';
import {getGpsPoints, stopGpsTrip} from '@libs/GPSDraftDetailsUtils';
import Navigation from '@libs/Navigation/Navigation';
import {generateReportID} from '@libs/ReportUtils';
Expand All @@ -16,6 +17,7 @@ import ONYXKEYS from '@src/ONYXKEYS';
import ROUTES from '@src/ROUTES';
import {useSplashScreenState} from '@src/SplashScreenStateContext';

import {accountIDSelector} from '@selectors/Session';
import {hasStartedLocationUpdatesAsync, startLocationUpdatesAsync, stopLocationUpdatesAsync} from 'expo-location';
import React, {useEffect, useRef, useState} from 'react';

Expand All @@ -26,6 +28,8 @@ function GPSTripStateChecker() {
const {translate} = useLocalize();
const [showContinueTripModal, setShowContinueTripModal] = useState(false);
const [gpsDraftDetails, gpsDraftDetailsMetadata] = useOnyx(ONYXKEYS.GPS_DRAFT_DETAILS);
const [currentAccountID, currentAccountIDResult] = useOnyx(ONYXKEYS.SESSION, {selector: accountIDSelector});
const isSessionLoaded = currentAccountIDResult.status === 'loaded';
const hasHandledAppRestart = useRef(false);
const {isOffline} = useNetwork();

Expand All @@ -36,6 +40,26 @@ function GPSTripStateChecker() {
useUpdateGpsTripOnReconnect({gpsPoints: getGpsPoints(gpsDraftDetails)});
useUpdateGpsNotification();

// A trip started before this shipped records no accountID, so only a different one means another user.
const isTripFromDifferentUser = isSessionLoaded && !!gpsDraftDetails?.accountID && gpsDraftDetails.accountID !== currentAccountID;

useEffect(() => {
if (!isTripFromDifferentUser) {
return;
}

resetGPSDraftDetails();
hasStartedLocationUpdatesAsync(BACKGROUND_LOCATION_TRACKING_TASK_NAME).then((isRunning) => {
if (!isRunning) {
return;
}

stopLocationUpdatesAsync(BACKGROUND_LOCATION_TRACKING_TASK_NAME).catch((error) =>
console.error('[GPS distance request] Failed to stop tracking for a trip from another user', error),
);
});
}, [isTripFromDifferentUser]);

useEffect(() => {
// Wait for the GPS_DRAFT_DETAILS subscription to hydrate before running the restart check once, so we don't
// misread the not-yet-loaded state as "no trip" and wrongly stop an in-progress trip's background task.
Expand Down Expand Up @@ -119,7 +143,7 @@ function GPSTripStateChecker() {

return (
<ConfirmModal
isVisible={showContinueTripModal && splashScreenState === CONST.BOOT_SPLASH_STATE.HIDDEN}
isVisible={showContinueTripModal && !!gpsDraftDetails?.isTracking && !isTripFromDifferentUser && splashScreenState === CONST.BOOT_SPLASH_STATE.HIDDEN}
title={translate('gps.continueGpsTripModal.title')}
prompt={translate('gps.continueGpsTripModal.prompt')}
shouldReverseStackedButtons
Expand Down
3 changes: 2 additions & 1 deletion src/libs/actions/GPSDraftDetails.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,13 +80,14 @@ function removeLastSegment(gpsPoints: GPSPoint[][]) {
});
}

function initGpsDraft(reportID: string, unit: Unit) {
function initGpsDraft(reportID: string, unit: Unit, accountID?: number) {
Onyx.merge(ONYXKEYS.GPS_DRAFT_DETAILS, {
gpsPoints: [[]],
isTracking: true,
distanceInMeters: 0,
reportID,
unit,
accountID,
});
}

Expand Down
3 changes: 3 additions & 0 deletions src/libs/actions/SignInRedirect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,9 @@ function clearStorageAndRedirect(errorMessage?: string, isSAMLReauthentication?:
keysToPreserve.push(ONYXKEYS.ACCOUNT);
Onyx.merge(ONYXKEYS.CREDENTIALS, {login: currentSessionEmail, autoGeneratedLogin: null, autoGeneratedPassword: null});
Onyx.merge(ONYXKEYS.ACCOUNT, {isLoading: true});

// A forced re-auth is involuntary, so an in-progress trip survives it.
keysToPreserve.push(ONYXKEYS.GPS_DRAFT_DETAILS);
}

return Onyx.clear(keysToPreserve).then(async () => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import Button from '@components/ButtonComposed';
import ConfirmModal from '@components/ConfirmModal';
import {loadIllustration} from '@components/Icon/IllustrationLoader';
import {useSession} from '@components/OnyxListItemProvider';

import {useMemoizedLazyAsset} from '@hooks/useLazyAsset';
import useLocalize from '@hooks/useLocalize';
Expand Down Expand Up @@ -53,6 +54,7 @@ function GPSButtons({navigateToNextStep, setShouldShowStartError, setShouldShowP
const [showZeroDistanceModal, setShowZeroDistanceModal] = useState(false);
const [showDisabledServicesModal, setShowDisabledServicesModal] = useState(false);
const {isOffline} = useNetwork();
const session = useSession();

const {asset: ReceiptLocationMarker} = useMemoizedLazyAsset(() => loadIllustration('ReceiptLocationMarker'));
const [gpsDraftDetails] = useOnyx(ONYXKEYS.GPS_DRAFT_DETAILS);
Expand Down Expand Up @@ -93,7 +95,7 @@ function GPSButtons({navigateToNextStep, setShouldShowStartError, setShouldShowP
return;
}

initGpsDraft(reportID, unit);
initGpsDraft(reportID, unit, session?.accountID);
startGpsTripNotification(translate, reportID, unit);
};

Expand Down
3 changes: 3 additions & 0 deletions src/types/onyx/GpsDraftDetails.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,9 @@ type GpsDraftDetails = {
/** Distance unit of the ongoing GPS trip */
unit: Unit;

/** accountID that started the trip, so a draft kept across a re-auth is never resumed by a different user */
accountID?: number;

/**
* Distance the user trimmed to in the Edit Stop screen.
* When set, this is the distance shown to the user and used when creating the expense.
Expand Down
40 changes: 40 additions & 0 deletions tests/actions/SessionTest.ts

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.

Can you also please follow the Given, when, then comments for tests?

Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ import {openAuthSessionAsync} from 'expo-web-browser';
import {clearTokenRefresh, removeAllFromAutoprefetch} from 'react-native-nitro-fetch';
import Onyx from 'react-native-onyx';

import getOnyxValue from '../utils/getOnyxValue';
import * as TestHelper from '../utils/TestHelper';
import waitForBatchedUpdates from '../utils/waitForBatchedUpdates';

Expand Down Expand Up @@ -1105,6 +1106,45 @@ describe('Session', () => {
});
});

describe('GPS trip on the sign in redirect', () => {
const gpsTrip = {
gpsPoints: [[{lat: 1, long: 2}]],
distanceInMeters: 100,
isTracking: true,
reportID: '1',
unit: CONST.CUSTOM_UNITS.DISTANCE_UNIT_MILES,
};

beforeEach(() => {
jest.restoreAllMocks();
});

test('keeps the in-progress trip when a SAML re-auth forces the redirect', async () => {
await TestHelper.signInWithTestUser();
const accountID = (await getOnyxValue(ONYXKEYS.SESSION))?.accountID;
await Onyx.merge(ONYXKEYS.GPS_DRAFT_DETAILS, {...gpsTrip, accountID});
await waitForBatchedUpdates();

await SignInRedirect.default(undefined, true);
await waitForBatchedUpdates();

const draft = await getOnyxValue(ONYXKEYS.GPS_DRAFT_DETAILS);
expect(draft?.isTracking).toBe(true);
expect(draft?.accountID).toBe(accountID);
});

test('discards the in-progress trip on a sign out redirect', async () => {
await TestHelper.signInWithTestUser();
await Onyx.merge(ONYXKEYS.GPS_DRAFT_DETAILS, gpsTrip);
await waitForBatchedUpdates();

await SignInRedirect.default();
await waitForBatchedUpdates();

expect(await getOnyxValue(ONYXKEYS.GPS_DRAFT_DETAILS)).toBeUndefined();
});
});

describe('signIn', () => {
test('sends the login and validate code arguments to the API, independent of the CREDENTIALS Onyx cache', async () => {
const writeSpy = jest.spyOn(API, 'write').mockResolvedValue(undefined);
Expand Down
93 changes: 93 additions & 0 deletions tests/unit/components/GPSTripStateCheckerTest.tsx

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.

Same here

Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import {render} from '@testing-library/react-native';

import ComposeProviders from '@components/ComposeProviders';
import GPSTripStateChecker from '@components/GPSTripStateChecker/index.native';
import {LocaleContextProvider} from '@components/LocaleContextProvider';
import OnyxListItemProvider from '@components/OnyxListItemProvider';

import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import {SplashScreenStateContextProvider} from '@src/SplashScreenStateContext';
import type {GpsDraftDetails} from '@src/types/onyx';

import React from 'react';
import Onyx from 'react-native-onyx';

import getOnyxValue from '../../utils/getOnyxValue';
import waitForBatchedUpdatesWithAct from '../../utils/waitForBatchedUpdatesWithAct';

jest.mock('@libs/Navigation/Navigation', () => ({
__esModule: true,
default: {navigate: jest.fn()},
}));

jest.mock('@pages/iou/request/step/IOURequestStepDistanceGPS/GPSNotifications', () => ({
startGpsTripNotification: jest.fn(),
stopGpsTripNotification: jest.fn(),
updateGpsTripNotificationDistance: jest.fn(),
updateGpsTripNotificationUnit: jest.fn(),
updateGpsTripNotificationLanguage: jest.fn(),
checkAndCleanGpsNotification: jest.fn(() => Promise.resolve()),
shouldUpdateGpsNotificationUnit: jest.fn(() => false),
}));

const CURRENT_ACCOUNT_ID = 1;
const OTHER_ACCOUNT_ID = 2;

const trip: GpsDraftDetails = {
gpsPoints: [[{lat: 1, long: 2}]],
distanceInMeters: 100,
isTracking: true,
reportID: '1',
unit: CONST.CUSTOM_UNITS.DISTANCE_UNIT_MILES,
};

function renderChecker() {
return render(
<ComposeProviders components={[OnyxListItemProvider, LocaleContextProvider, SplashScreenStateContextProvider]}>
<GPSTripStateChecker />
</ComposeProviders>,
);
}

describe('GPSTripStateChecker', () => {
beforeAll(() => {
Onyx.init({keys: ONYXKEYS});
});

beforeEach(async () => {
await Onyx.clear();
await Onyx.merge(ONYXKEYS.SESSION, {accountID: CURRENT_ACCOUNT_ID});
await waitForBatchedUpdatesWithAct();
});

it('keeps a trip that records no accountID, because it predates the trip owner being stored', async () => {
await Onyx.merge(ONYXKEYS.GPS_DRAFT_DETAILS, trip);
await waitForBatchedUpdatesWithAct();

renderChecker();
await waitForBatchedUpdatesWithAct();

expect((await getOnyxValue(ONYXKEYS.GPS_DRAFT_DETAILS))?.isTracking).toBe(true);
});

it('keeps a trip started by the signed in user', async () => {
await Onyx.merge(ONYXKEYS.GPS_DRAFT_DETAILS, {...trip, accountID: CURRENT_ACCOUNT_ID});
await waitForBatchedUpdatesWithAct();

renderChecker();
await waitForBatchedUpdatesWithAct();

expect((await getOnyxValue(ONYXKEYS.GPS_DRAFT_DETAILS))?.isTracking).toBe(true);
});

it('discards a trip started by a different user', async () => {
await Onyx.merge(ONYXKEYS.GPS_DRAFT_DETAILS, {...trip, accountID: OTHER_ACCOUNT_ID});
await waitForBatchedUpdatesWithAct();

renderChecker();
await waitForBatchedUpdatesWithAct();

expect(await getOnyxValue(ONYXKEYS.GPS_DRAFT_DETAILS)).toBeUndefined();
});
});
Loading