Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

task(settings): Disable 2FA and Recovery Code actions when account has no password #12819

Merged
merged 2 commits into from
May 10, 2022
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
70 changes: 61 additions & 9 deletions packages/fxa-settings/src/components/App/index.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,15 @@

import React, { ReactNode } from 'react';
import { render, act } from '@testing-library/react';
import { History } from '@reach/router';
import App from '.';
import * as Metrics from '../../lib/metrics';
import { Account, AppContext, useInitialState } from '../../models';
import { mockAppContext, renderWithRouter } from '../../models/mocks';
import {
mockAppContext,
MOCK_ACCOUNT,
renderWithRouter,
} from '../../models/mocks';
import { Config } from '../../lib/config';
import * as NavTiming from 'fxa-shared/metrics/navigation-timing';
import { HomePath } from '../../constants';
Expand Down Expand Up @@ -51,7 +56,7 @@ describe('metrics', () => {
});

it('Initializes metrics flow data when present', async () => {
(useInitialState as jest.Mock).mockReturnValueOnce({loading: true});
(useInitialState as jest.Mock).mockReturnValueOnce({ loading: true });
const DEVICE_ID = 'yoyo';
const BEGIN_TIME = 123456;
const FLOW_ID = 'abc123';
Expand Down Expand Up @@ -93,9 +98,10 @@ describe('performance metrics', () => {
});

it('observeNavigationTiming is called when metrics collection is enabled', () => {
(useInitialState as jest.Mock).mockReturnValueOnce({loading: true});
(useInitialState as jest.Mock).mockReturnValueOnce({ loading: true });
const account = {
metricsEnabled: true,
hasPassword: true,
} as unknown as Account;
render(
<AppContext.Provider value={mockAppContext({ account, config })}>
Expand All @@ -106,9 +112,10 @@ describe('performance metrics', () => {
});

it('observeNavigationTiming is not called when metrics collection is disabled', () => {
(useInitialState as jest.Mock).mockReturnValueOnce({loading: true});
(useInitialState as jest.Mock).mockReturnValueOnce({ loading: true });
const account = {
metricsEnabled: false,
hasPassword: true,
} as unknown as Account;
render(
<AppContext.Provider value={mockAppContext({ account, config })}>
Expand All @@ -132,18 +139,24 @@ describe('App component', () => {
expect(getByLabelText('Loading...')).toBeInTheDocument();
});

it('renders `LoadingSpinner` component when the error message includes "Invalid token"',() => {
(useInitialState as jest.Mock).mockReturnValueOnce({ error: { message: "Invalid token" }});
it('renders `LoadingSpinner` component when the error message includes "Invalid token"', () => {
(useInitialState as jest.Mock).mockReturnValueOnce({
error: { message: 'Invalid token' },
});
const { getByLabelText } = renderWithRouter(<App {...appProps} />);

expect(getByLabelText('Loading...')).toBeInTheDocument();
});

it('renders `AppErrorDialog` component when there is an error other than "Invalid token"', () => {
(useInitialState as jest.Mock).mockReturnValueOnce({ error: { message: "Error" }});
(useInitialState as jest.Mock).mockReturnValueOnce({
error: { message: 'Error' },
});
const { getByRole } = renderWithRouter(<App {...appProps} />);

expect(getByRole('heading', { level: 2 })).toHaveTextContent('General application error');
expect(getByRole('heading', { level: 2 })).toHaveTextContent(
'General application error'
);
});

(useInitialState as jest.Mock).mockReturnValue({ loading: false });
Expand Down Expand Up @@ -242,7 +255,7 @@ describe('App component', () => {
history: { navigate },
} = renderWithRouter(<App {...appProps} />, { route: HomePath });

await navigate(HomePath + '/two_step_authentication/replace_codes' );
await navigate(HomePath + '/two_step_authentication/replace_codes');

expect(getByTestId('2fa-recovery-codes')).toBeInTheDocument();
});
Expand Down Expand Up @@ -279,4 +292,43 @@ describe('App component', () => {

expect(history.location.pathname).toBe('/settings/avatar');
});

describe('prevents access to certain routes when account has no password', () => {
let history: History;

beforeEach(async () => {
const account = {
...MOCK_ACCOUNT,
hasPassword: false,
} as unknown as Account;

const config = {
metrics: { navTiming: { enabled: true, endpoint: '/foobar' } },
} as Config;

({ history } = await renderWithRouter(
<AppContext.Provider value={mockAppContext({ account, config })}>
<App {...appProps} />
</AppContext.Provider>,
{ route: HomePath }
));
});

it('redirects PageRecoveryKeyAdd', async () => {
await history.navigate(HomePath + '/account_recovery');
expect(history.location.pathname).toBe('/settings');
});

it('redirects PageTwoStepAuthentication', async () => {
await history.navigate(HomePath + '/two_step_authentication');
expect(history.location.pathname).toBe('/settings');
});

it('redirects Page2faReplaceRecoveryCodes', async () => {
await history.navigate(
HomePath + '/two_step_authentication/replace_codes'
);
expect(history.location.pathname).toBe('/settings');
});
});
});
28 changes: 24 additions & 4 deletions packages/fxa-settings/src/components/App/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ type AppProps = {

export const App = ({ flowQueryParams, navigatorLanguages }: AppProps) => {
const config = useConfig();
const { metricsEnabled } = useAccount();
const { metricsEnabled, hasPassword } = useAccount();

useEffect(() => {
if (config.metrics.navTiming.enabled && metricsEnabled) {
Expand Down Expand Up @@ -76,11 +76,31 @@ export const App = ({ flowQueryParams, navigatorLanguages }: AppProps) => {
<PageDisplayName path="/display_name" />
<PageAvatar path="/avatar" />
<PageChangePassword path="/change_password" />
<PageRecoveryKeyAdd path="/account_recovery" />
{hasPassword ? (
<PageRecoveryKeyAdd path="/account_recovery" />
) : (
<Redirect from="/account_recovery" to="/settings" noThrow />
)}
<PageSecondaryEmailAdd path="/emails" />
<PageSecondaryEmailVerify path="/emails/verify" />
<PageTwoStepAuthentication path="/two_step_authentication" />
<Page2faReplaceRecoveryCodes path="/two_step_authentication/replace_codes" />
{hasPassword ? (
<PageTwoStepAuthentication path="/two_step_authentication" />
) : (
<Redirect
from="/two_step_authentication"
to="/settings"
noThrow
/>
)}
{hasPassword ? (
<Page2faReplaceRecoveryCodes path="/two_step_authentication/replace_codes" />
) : (
<Redirect
from="/two_step_authentication/replace_codes"
to="/settings"
noThrow
/>
)}
<PageDeleteAccount path="/delete_account" />
<Redirect
from="/clients"
Expand Down
84 changes: 54 additions & 30 deletions packages/fxa-settings/src/components/UnitRow/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,8 @@ type UnitRowProps = {
hideCtaText?: boolean;
prefixDataTestId?: string;
isLevelWithRefreshButton?: boolean;
disabled?: boolean;
disabledReason?: string;
};

export const UnitRow = ({
Expand All @@ -105,6 +107,8 @@ export const UnitRow = ({
hideCtaText,
prefixDataTestId = '',
isLevelWithRefreshButton = false,
disabled = false,
disabledReason = '',
}: UnitRowProps & RouteComponentProps) => {
const { l10n } = useLocalization();
const localizedCtaAdd = l10n.getString(
Expand Down Expand Up @@ -158,46 +162,66 @@ export const UnitRow = ({

<div className="unit-row-actions">
<div className="flex items-center">
{!hideCtaText && route && (
<Link
{disabled ? (
<button
className={classNames(
'cta-neutral cta-base transition-standard rtl:ml-1',
isLevelWithRefreshButton && 'mobileLandscape:mr-9'
)}
data-testid={formatDataTestId('unit-row-route')}
to={`${route}${location.search}`}
title={disabledReason}
disabled={disabled}
>
{ctaText}
</Link>
)}
{!hideCtaText && ctaText}
</button>
) : (
<>
{!hideCtaText && route && (
<Link
className={classNames(
'cta-neutral cta-base transition-standard rtl:ml-1',
isLevelWithRefreshButton && 'mobileLandscape:mr-9'
)}
data-testid={formatDataTestId('unit-row-route')}
to={`${route}${location.search}`}
>
{ctaText}
</Link>
)}

{revealModal && (
<ModalButton
{...{ revealModal, ctaText, alertBarRevealed, prefixDataTestId }}
/>
)}
{revealModal && (
<ModalButton
{...{
revealModal,
ctaText,
alertBarRevealed,
prefixDataTestId,
}}
/>
)}

{secondaryCtaRoute && (
<Link
className="cta-neutral cta-base transition-standard ltr:mr-1 rtl:ml-1"
data-testid={formatDataTestId('unit-row-route')}
to={`${secondaryCtaRoute}${location.search}`}
>
{secondaryCtaText}
</Link>
)}
{secondaryCtaRoute && (
<Link
className="cta-neutral cta-base transition-standard ltr:mr-1 rtl:ml-1"
data-testid={formatDataTestId('unit-row-route')}
to={`${secondaryCtaRoute}${location.search}`}
>
{secondaryCtaText}
</Link>
)}

{revealSecondaryModal && (
<ModalButton
leftSpaced={multiButton}
revealModal={revealSecondaryModal}
ctaText={secondaryCtaText}
className={secondaryButtonClassName}
alertBarRevealed={alertBarRevealed}
prefixDataTestId={secondaryButtonTestId}
/>
{revealSecondaryModal && (
<ModalButton
leftSpaced={multiButton}
revealModal={revealSecondaryModal}
ctaText={secondaryCtaText}
className={secondaryButtonClassName}
alertBarRevealed={alertBarRevealed}
prefixDataTestId={secondaryButtonTestId}
/>
)}
</>
)}

{actionContent}
</div>
</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { Account, AppContext } from '../../models';
import * as Metrics from '../../lib/metrics';

const account = {
hasPassword: true,
recoveryKey: true,
deleteRecoveryKey: jest.fn().mockResolvedValue(true),
} as unknown as Account;
Expand All @@ -40,6 +41,7 @@ describe('UnitRowRecoveryKey', () => {

it('renders when recovery key is not set', () => {
const account = {
hasPassword: true,
recoveryKey: false,
} as unknown as Account;
renderWithRouter(
Expand All @@ -58,8 +60,34 @@ describe('UnitRowRecoveryKey', () => {
).toContain('Create');
});

it('renders disabled state when account has no password', () => {
const account = {
hasPassword: false,
recoveryKey: false,
} as unknown as Account;

renderWithRouter(
<AppContext.Provider value={mockAppContext({ account })}>
<UnitRowRecoveryKey />
</AppContext.Provider>
);

expect(
screen.getByTestId('recovery-key-unit-row-route').textContent
).toContain('Create');

expect(
screen
.getByTestId('recovery-key-unit-row-route')
.attributes.getNamedItem('title')?.value
).toEqual(
'Set a password to use Firefox Sync and certain account security features.'
);
});

it('can be refreshed', async () => {
const account = {
hasPassword: true,
recoveryKey: false,
refresh: jest.fn(),
} as unknown as Account;
Expand Down Expand Up @@ -98,6 +126,7 @@ describe('UnitRowRecoveryKey', () => {

const removeRecoveryKey = async (process = false) => {
const account = {
hasPassword: true,
recoveryKey: true,
} as unknown as Account;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,12 @@ export const UnitRowRecoveryKey = () => {
? l10n.getString('rk-action-remove', null, 'Remove')
: l10n.getString('rk-action-create', null, 'Create')
}
disabled={!account.hasPassword}
disabledReason={l10n.getString(
'security-set-password',
null,
'Set a password to use Firefox Sync and certain account security features.'
)}
alertBarRevealed
headerContent={
<ButtonIconReload
Expand All @@ -68,7 +74,7 @@ export const UnitRowRecoveryKey = () => {
title={l10n.getString('rk-refresh-key')}
classNames="hidden mobileLandscape:inline-block ltr:ml-1 rtl:mr-1"
testId="recovery-key-refresh"
disabled={account.loading}
disabled={account.loading || !account.hasPassword}
onClick={() => account.refresh('recovery')}
/>
}
Expand Down
Loading