Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
1 change: 1 addition & 0 deletions src/CONST/runtimeConfigured.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ const CONST_RUNTIME: ConstRuntime = {
EXCLUDE_FROM_LAST_VISITED_PATH: [
SCREENS.NOT_FOUND,
SCREENS.SAML_SIGN_IN,
SCREENS.TRANSITION_BETWEEN_APPS,
SCREENS.VALIDATE_LOGIN,
SCREENS.MIGRATED_USER_WELCOME_MODAL.DYNAMIC_ROOT,
SCREENS.SUBMIT_PLAN_WELCOME_MODAL.DYNAMIC_ROOT,
Expand Down
1 change: 1 addition & 0 deletions src/CONST/runtimeDefaults.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ const CONST_RUNTIME_DEFAULTS: ConstRuntime = {
EXCLUDE_FROM_LAST_VISITED_PATH: [
'not-found',
'SAMLSignIn',
'TransitionBetweenApps',
'ValidateLogin',
'Dynamic_MigratedUserWelcomeModal_Root',
'Dynamic_SubmitPlanWelcomeModal_Root',
Expand Down
7 changes: 4 additions & 3 deletions src/libs/Navigation/NavigationRoot.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ function trackFullstoryPageView(state: NavigationState) {
/**
* Intercept navigation state changes and log it
*/
function parseAndLogRoute(state: NavigationState) {
function parseAndLogRoute(state: NavigationState, authenticated: boolean) {
if (!state) {
return;
}
Expand All @@ -88,7 +88,8 @@ function parseAndLogRoute(state: NavigationState) {

const focusedRoute = findFocusedRoute(state);

if (focusedRoute && !CONST.EXCLUDE_FROM_LAST_VISITED_PATH.includes(focusedRoute?.name)) {
// Signed-out screens are never restored, and saving one would overwrite the page a forced re-auth returns to.
if (authenticated && focusedRoute && !CONST.EXCLUDE_FROM_LAST_VISITED_PATH.includes(focusedRoute?.name)) {
updateLastVisitedPath(currentPath);
if (currentPath.startsWith(`/${ROUTES.ONBOARDING_ROOT.route}`)) {
updateOnboardingLastVisitedPath(currentPath);
Expand Down Expand Up @@ -280,7 +281,7 @@ function NavigationRoot({authenticated, lastVisitedPath, initialUrl, onReady}: N
Sentry.addBreadcrumb({message: `[NAVIGATION] screen: ${currentRoute?.name}, params: ${JSON.stringify(currentRoute?.params ?? {})}`, category: 'navigation'});

updateCurrentReportID(state);
parseAndLogRoute(state);
parseAndLogRoute(state, authenticated);

// We want to clean saved scroll offsets for screens that aren't anymore in the state.
cleanStaleScrollOffsets(state);
Expand Down
8 changes: 6 additions & 2 deletions src/libs/actions/App.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,16 +48,18 @@ type PolicyParamsForOpenOrReconnect = {

// `currentSessionData` is only used in actions, not during render. So `Onyx.connectWithoutView` is appropriate.
// If React components need this value in the future, use `useOnyx` instead.
let currentSessionData: {accountID?: number; email: string} = {
let currentSessionData: {accountID?: number; email: string; authToken?: string} = {
accountID: undefined,
email: '',
authToken: undefined,
};
Onyx.connectWithoutView({
key: ONYXKEYS.SESSION,
callback: (val) => {
currentSessionData = {
accountID: val?.accountID,
email: val?.email ?? '',
authToken: val?.authToken,
};
},
});
Expand Down Expand Up @@ -240,7 +242,8 @@ function setAppLoading(isLoading: boolean) {
*/
function saveCurrentPathBeforeBackground() {
try {
if (!navigationRef.isReady()) {
// Signed out there is only the sign-in page to save, and on Android the SAML browser backgrounds the app.
if (!navigationRef.isReady() || !currentSessionData.authToken) {
return;
}

Expand Down Expand Up @@ -996,6 +999,7 @@ function showSupportalPermissionDenied(payload: OnyxTypes.SupportalPermissionDen
export {
setLocale,
setSidebarLoaded,
saveCurrentPathBeforeBackground,
setUpPoliciesAndNavigate,
openApp,
setAppLoading,
Expand Down
23 changes: 22 additions & 1 deletion src/libs/actions/Session/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import getPlatform from '@libs/getPlatform';
import HttpUtils from '@libs/HttpUtils';
import Log from '@libs/Log';
import {findMatchingDynamicSuffix} from '@libs/Navigation/helpers/dynamicRoutesUtils/findAllMatchingDynamicSuffixes';
import getAdaptedStateFromPath from '@libs/Navigation/helpers/getAdaptedStateFromPath';
import Navigation from '@libs/Navigation/Navigation';
import navigationRef from '@libs/Navigation/navigationRef';
import * as MainQueue from '@libs/Network/MainQueue';
Expand Down Expand Up @@ -870,7 +871,7 @@ function beginGoogleSignIn(token: string | null, preferredLocale: Locale | undef
* Will create a temporary login for the user in the passed authenticate response which is used when
* re-authenticating after an authToken expires.
*/
function signInWithShortLivedAuthToken(authToken: string, isSAML = false) {
function signInWithShortLivedAuthToken(authToken: string, isSAML = false, exitTo?: string) {
const {optimisticData, failureData, finallyData} = getShortLivedLoginParams(false, isSAML);
const authMethod = isSAML ? CONST.AUTH_METHOD.SAML : CONST.AUTH_METHOD.SHORT_LIVED_AUTH_TOKEN;
// Set the in-flight guard synchronously, before awaiting device info. optimisticData below (which also sets this key)
Expand All @@ -883,6 +884,26 @@ function signInWithShortLivedAuthToken(authToken: string, isSAML = false) {
API.read(READ_COMMANDS.SIGN_IN_WITH_SHORT_LIVED_AUTH_TOKEN, {authToken, skipReauthentication: true, authMethod, deviceInfo}, {optimisticData, failureData, finallyData});
});
NetworkStore.setLastShortAuthToken(authToken);
if (!exitTo) {
return;
}

const login = credentials.login;
// waitForUserSignIn keeps a single resolver that openReportFromDeepLink may already hold, so wait on the routes instead.
Navigation.waitForProtectedRoutes().then(() => {
// A failed sign-in leaves this waiting, so a later sign-in by another account must not land on this page.
if (!login || deprecatedSession.email?.toLowerCase() !== login.toLowerCase()) {
return;
}
try {
// Rebuilt like a cold start restore of this path.
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
navigationRef.resetRoot({...getAdaptedStateFromPath(exitTo as Route), stale: true});
} catch (error) {
// A path saved by an older build may no longer exist, and the sign-in already landed on Home.
Log.warn('Unable to return to the last visited path after SAML sign in', {error});
}
});
}

/**
Expand Down
3 changes: 2 additions & 1 deletion src/libs/actions/SignInRedirect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,9 @@ function clearStorageAndRedirect(errorMessage?: string, isSAMLReauthentication?:
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.
// A forced re-auth is involuntary, so an in-progress trip and the current page survive it.
keysToPreserve.push(ONYXKEYS.GPS_DRAFT_DETAILS);
keysToPreserve.push(ONYXKEYS.LAST_VISITED_PATH);
}

return Onyx.clear(keysToPreserve).then(async () => {
Expand Down
21 changes: 15 additions & 6 deletions src/pages/LogInWithShortLivedAuthTokenPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import ONYXKEYS from '@src/ONYXKEYS';
import type {Route} from '@src/ROUTES';
import ROUTES from '@src/ROUTES';
import type SCREENS from '@src/SCREENS';
import isLoadingOnyxValue from '@src/types/utils/isLoadingOnyxValue';

import React, {useEffect} from 'react';

Expand All @@ -25,8 +26,15 @@ type LogInWithShortLivedAuthTokenPageProps = PlatformStackScreenProps<PublicScre
function LogInWithShortLivedAuthTokenPage({route}: LogInWithShortLivedAuthTokenPageProps) {
const {shortLivedAuthToken = '', shortLivedToken = '', authTokenType, exitTo, error, isSAML = false} = route?.params ?? {};
const [account] = useOnyx(ONYXKEYS.ACCOUNT);
const [lastVisitedPath, lastVisitedPathMetadata] = useOnyx(ONYXKEYS.LAST_VISITED_PATH);
const isLoadingLastVisitedPath = isLoadingOnyxValue(lastVisitedPathMetadata);

useEffect(() => {
// Only a forced SAML re-auth keeps a last visited path, so it has to be read before the sign-in starts.
if (isLoadingLastVisitedPath) {
return;
}

// We have to check for both shortLivedAuthToken and shortLivedToken, as the old mobile app uses shortLivedToken, and is not being actively updated.
const token = shortLivedAuthToken || shortLivedToken;

Expand All @@ -45,10 +53,11 @@ function LogInWithShortLivedAuthTokenPage({route}: LogInWithShortLivedAuthTokenP
return;
}

// Try to authenticate using the shortLivedToken if we're not already trying to load the accounts
if (token && !account?.isLoading) {
// Try to authenticate using the shortLivedToken if we're not already trying to load the accounts.
// A forced SAML re-auth leaves account.isLoading true until this sign-in, so it must not block a SAML token.
if (token && (isSAML || !account?.isLoading)) {
Log.info('LogInWithShortLivedAuthTokenPage - Successfully received shortLivedAuthToken. Signing in...');
signInWithShortLivedAuthToken(token, isSAML);
signInWithShortLivedAuthToken(token, isSAML, isSAML ? lastVisitedPath : undefined);
// For SAML sign-ins, navigate to HOME explicitly since the SAML flow
// doesn't use exitTo deep link routing. For non-SAML flows, let the
// navigation system handle exitTo routing naturally via setUpPoliciesAndNavigate.
Expand All @@ -73,11 +82,11 @@ function LogInWithShortLivedAuthTokenPage({route}: LogInWithShortLivedAuthTokenP
Navigation.navigate(exitTo as Route);
});
}
// The only dependencies of the effect are based on props.route
// Runs once the route and the last visited path are known, later Onyx changes must not restart the sign-in.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [route]);
}, [route, isLoadingLastVisitedPath]);

if (account?.isLoading) {
if (account?.isLoading || isLoadingLastVisitedPath) {
return <FullScreenLoadingIndicator />;
}

Expand Down
9 changes: 5 additions & 4 deletions src/pages/signin/SAMLSignInPage/index.native.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ import {openAuthSessionAsync} from 'expo-web-browser';
import React, {useCallback, useEffect, useRef, useState} from 'react';

function SAMLSignInPage() {
const [account] = useOnyx(ONYXKEYS.ACCOUNT);
const [credentials] = useOnyx(ONYXKEYS.CREDENTIALS);
const [lastVisitedPath] = useOnyx(ONYXKEYS.LAST_VISITED_PATH);
const [showNavigation, shouldShowNavigation] = useState(true);
const [SAMLUrl, setSAMLUrl] = useState('');
const {translate} = useLocalize();
Expand Down Expand Up @@ -68,9 +68,10 @@ function SAMLSignInPage() {
Log.hmmm('SAMLSignInPage - No JSON parameter found in callback URL');
}

if (!account?.isLoading && credentials?.login && shortLivedAuthToken) {
// A forced re-auth leaves account.isLoading true until sign-in, so the token alone decides here.
if (credentials?.login && shortLivedAuthToken) {
Log.info('SAMLSignInPage - Successfully received shortLivedAuthToken. Signing in...');
signInWithShortLivedAuthToken(shortLivedAuthToken, true);
signInWithShortLivedAuthToken(shortLivedAuthToken, true, lastVisitedPath);
return;
}

Expand All @@ -87,7 +88,7 @@ function SAMLSignInPage() {
Navigation.navigate(ROUTES.HOME);
});
},
[credentials?.login, account?.isLoading, translate],
[credentials?.login, lastVisitedPath, translate],
);

useEffect(() => {
Expand Down
73 changes: 73 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.

NAB: Tests should follow the Given, When, Then comments

Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {SIDE_EFFECT_REQUEST_COMMANDS, WRITE_COMMANDS} from '@libs/API/types';
import asyncOpenURL from '@libs/asyncOpenURL';
import getPlatform from '@libs/getPlatform';
import HttpUtils from '@libs/HttpUtils';
import Navigation, {navigationRef} from '@libs/Navigation/Navigation';
import * as NetworkStore from '@libs/Network/NetworkStore';
import {setHasRadio} from '@libs/NetworkState';
import PushNotification from '@libs/Notification/PushNotification';
Expand Down Expand Up @@ -900,6 +901,50 @@ describe('Session', () => {

expect(session?.signedInWithSAML).toBe(false);
});

test('signInWithShortLivedAuthToken rebuilds navigation from exitTo once the same login is signed in', async () => {
await Onyx.merge(ONYXKEYS.CREDENTIALS, {login: 'user@saml.example.com'});
await Onyx.merge(ONYXKEYS.SESSION, {authToken: 'testAuthToken', email: 'User@saml.example.com'});
await waitForBatchedUpdates();
jest.spyOn(Navigation, 'waitForProtectedRoutes').mockResolvedValue(undefined);
const resetRootSpy = jest.spyOn(navigationRef, 'resetRoot').mockImplementation(() => {});

SessionUtil.signInWithShortLivedAuthToken('testAuthToken', true, '/search?q=status:outstanding');
await waitForBatchedUpdates();

expect(resetRootSpy).toHaveBeenCalledTimes(1);
const [state] = resetRootSpy.mock.calls.at(0) ?? [];
expect(state?.stale).toBe(true);
expect(state?.routes.length).toBeGreaterThan(0);
jest.restoreAllMocks();
});

test('signInWithShortLivedAuthToken does not navigate to exitTo without a login to compare', async () => {
await Onyx.merge(ONYXKEYS.SESSION, {authToken: 'testAuthToken', email: 'user@saml.example.com'});
await waitForBatchedUpdates();
jest.spyOn(Navigation, 'waitForProtectedRoutes').mockResolvedValue(undefined);
const resetRootSpy = jest.spyOn(navigationRef, 'resetRoot').mockImplementation(() => {});

SessionUtil.signInWithShortLivedAuthToken('testAuthToken', true, '/search?q=status:outstanding');
await waitForBatchedUpdates();

expect(resetRootSpy).not.toHaveBeenCalled();
jest.restoreAllMocks();
});

test('signInWithShortLivedAuthToken does not navigate to exitTo when another login signs in', async () => {
await Onyx.merge(ONYXKEYS.CREDENTIALS, {login: 'user@saml.example.com'});
await Onyx.merge(ONYXKEYS.SESSION, {authToken: 'testAuthToken', email: 'other@example.com'});
await waitForBatchedUpdates();
jest.spyOn(Navigation, 'waitForProtectedRoutes').mockResolvedValue(undefined);
const resetRootSpy = jest.spyOn(navigationRef, 'resetRoot').mockImplementation(() => {});

SessionUtil.signInWithShortLivedAuthToken('testAuthToken', true, '/search?q=status:outstanding');
await waitForBatchedUpdates();

expect(resetRootSpy).not.toHaveBeenCalled();
jest.restoreAllMocks();
});
});

describe('resendValidateCode', () => {
Expand Down Expand Up @@ -1172,6 +1217,34 @@ describe('Session', () => {
});
});

describe('last visited path on the sign in redirect', () => {
beforeEach(() => {
jest.restoreAllMocks();
});

test('keeps the last visited path when a SAML re-auth forces the redirect', async () => {
await TestHelper.signInWithTestUser();
await Onyx.merge(ONYXKEYS.LAST_VISITED_PATH, '/search?q=status:outstanding');
await waitForBatchedUpdates();

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

expect(await getOnyxValue(ONYXKEYS.LAST_VISITED_PATH)).toBe('/search?q=status:outstanding');
});

test('discards the last visited path on a sign out redirect', async () => {
await TestHelper.signInWithTestUser();
await Onyx.merge(ONYXKEYS.LAST_VISITED_PATH, '/search?q=status:outstanding');
await waitForBatchedUpdates();

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

expect(await getOnyxValue(ONYXKEYS.LAST_VISITED_PATH)).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
Loading
Loading