Skip to content

Commit

Permalink
feat: Adding delete metametrics data to security and privacy tab (#24571
Browse files Browse the repository at this point in the history
)

<!--
Please submit this PR as a draft initially.
Do not mark it as "Ready for review" until the template has been
completely filled out, and PR status checks have passed at least once.
-->

**This  PR is dependant on #24503** 
## **Description**

- Added a new functional component as an entry to the Security & Privacy
tab with the `Delete MetaMetrics Data` button.
- A new Delete MetaMetrics Data model will open when you click the
button.
- Clicking the `Clear` button in the modal will create a data deletion
regulation, update the state, and close the modal, deactivating the
`Delete MetaMetrics Data` button.
- The Erroring on the `Clear` button click opens a new error modal.

**Scenarios to disable the DeleteMetaMetrics button:**


1. Metametrics ID not created / not available
2. Just performed a deletion independent on participate in metametrics
toggle
3. Participate in metric opt-out & no data is recorded after deletion.
4. Status of current delete regulation as INITIALIZED, RUNNING, or
FINISHED and (Participate in metric opt-out/no data recorded after
deletion)


<!--
Write a short description of the changes included in this pull request,
also include relevant motivation and context. Have in mind the following
questions:
1. What is the reason for the change?
2. What is the improvement/solution?
-->

[![Open in GitHub
Codespaces](https://github.com/codespaces/badge.svg)](https://codespaces.new/MetaMask/metamask-extension/pull/24571?quickstart=1)

## **Related issues**

Fixes #24406, #24407,
MetaMask/MetaMask-planning#2523
## **Manual testing steps**

Perquisite:
Provide the following details in the `.metamaskrc` file:
```
ANALYTICS_DATA_DELETION_SOURCE_ID="wygFTooEUUtcckty9kaMc"
ANALYTICS_DATA_DELETION_ENDPOINT="https://proxy.dev-api.cx.metamask.io/segment/v1"
```

1. Make a build(`yarn`, `yarn dist`) against the code.
2. Load the extension in any browser.
3. Navigate to the "Security & privacy" in the Settings 
4. Click on the "Delete MetaMetrics data" button which enables when the
"Participate in MetaMetrics" is selected.
5. Validate the post request is made in the service worker with the id -
`wygFTooEUUtcckty9kaMc`.

## **Screenshots/Recordings**

<!-- If applicable, add screenshots and/or recordings to visualize the
before and after of your change. -->

### **Before**

<!-- [screenshots/recordings] -->

### **After**

<!-- [screenshots/recordings] -->

## **Pre-merge author checklist**

- [ ] I’ve followed [MetaMask Coding
Standards](https://github.com/MetaMask/metamask-extension/blob/develop/.github/guidelines/CODING_GUIDELINES.md).
- [ ] I've completed the PR template to the best of my ability
- [ ] I’ve included tests if applicable
- [ ] I’ve documented my code using [JSDoc](https://jsdoc.app/) format
if applicable
- [ ] I’ve applied the right labels on the PR (see [labeling
guidelines](https://github.com/MetaMask/metamask-extension/blob/develop/.github/guidelines/LABELING_GUIDELINES.md)).
Not required for external contributors.

## **Pre-merge reviewer checklist**

- [ ] I've manually tested the PR (e.g. pull and build branch, run the
app, test code being changed).
- [ ] I confirm that this PR addresses all acceptance criteria described
in the ticket it closes and includes the necessary testing evidence such
as recordings and or screenshots.

---------

Co-authored-by: seaona <54408225+seaona@users.noreply.github.com>
  • Loading branch information
NiranjanaBinoy and seaona authored Oct 7, 2024
1 parent 43f3989 commit 11ca25b
Show file tree
Hide file tree
Showing 28 changed files with 1,278 additions and 4 deletions.
26 changes: 26 additions & 0 deletions app/_locales/en/messages.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions privacy-snapshot.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
"mainnet.infura.io",
"metamask.eth",
"metamask.github.io",
"metametrics.metamask.test",
"min-api.cryptocompare.com",
"nft.api.cx.metamask.io",
"oidc.api.cx.metamask.io",
Expand All @@ -42,6 +43,7 @@
"portfolio.metamask.io",
"price.api.cx.metamask.io",
"proxy.api.cx.metamask.io",
"proxy.dev-api.cx.metamask.io",
"raw.githubusercontent.com",
"registry.npmjs.org",
"responsive-rpc.test",
Expand Down
2 changes: 2 additions & 0 deletions shared/constants/metametrics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -536,6 +536,7 @@ export enum MetaMetricsEventName {
EncryptionPublicKeyApproved = 'Encryption Approved',
EncryptionPublicKeyRejected = 'Encryption Rejected',
EncryptionPublicKeyRequested = 'Encryption Requested',
ErrorOccured = 'Error occured',
ExternalLinkClicked = 'External Link Clicked',
KeyExportSelected = 'Key Export Selected',
KeyExportRequested = 'Key Export Requested',
Expand All @@ -552,6 +553,7 @@ export enum MetaMetricsEventName {
MarkAllNotificationsRead = 'Notifications Marked All as Read',
MetricsOptIn = 'Metrics Opt In',
MetricsOptOut = 'Metrics Opt Out',
MetricsDataDeletionRequest = 'Delete MetaMetrics Data Request Submitted',
NavAccountMenuOpened = 'Account Menu Opened',
NavConnectedSitesOpened = 'Connected Sites Opened',
NavMainMenuOpened = 'Main Menu Opened',
Expand Down
246 changes: 246 additions & 0 deletions test/e2e/tests/metrics/delete-metametrics-data.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,246 @@
import { strict as assert } from 'assert';
import { MockedEndpoint, Mockttp } from 'mockttp';
import { Suite } from 'mocha';
import {
defaultGanacheOptions,
withFixtures,
getEventPayloads,
unlockWallet,
} from '../../helpers';
import FixtureBuilder from '../../fixture-builder';
import { Driver } from '../../webdriver/driver';
import { TestSuiteArguments } from '../confirmations/transactions/shared';
import { WebElementWithWaitForElementState } from '../../webdriver/types';

const selectors = {
accountOptionsMenuButton: '[data-testid="account-options-menu-button"]',
globalMenuSettingsButton: '[data-testid="global-menu-settings"]',
securityAndPrivacySettings: { text: 'Security & privacy', tag: 'div' },
experimentalSettings: { text: 'Experimental', tag: 'div' },
deletMetaMetricsSettings: '[data-testid="delete-metametrics-data-button"]',
deleteMetaMetricsDataButton: {
text: 'Delete MetaMetrics data',
tag: 'button',
},
clearButton: { text: 'Clear', tag: 'button' },
backButton: '[data-testid="settings-back-button"]',
};

/**
* mocks the segment api multiple times for specific payloads that we expect to
* see when these tests are run. In this case we are looking for
* 'Permissions Requested' and 'Permissions Received'. Do not use the constants
* from the metrics constants files, because if these change we want a strong
* indicator to our data team that the shape of data will change.
*
* @param mockServer
* @returns
*/
const mockSegment = async (mockServer: Mockttp) => {
return [
await mockServer
.forPost('https://api.segment.io/v1/batch')
.withJsonBodyIncluding({
batch: [
{ type: 'track', event: 'Delete MetaMetrics Data Request Submitted' },
],
})
.thenCallback(() => {
return {
statusCode: 200,
};
}),
await mockServer
.forPost('https://metametrics.metamask.test/regulations/sources/test')
.withHeaders({ 'Content-Type': 'application/vnd.segment.v1+json' })
.withBodyIncluding(
JSON.stringify({
regulationType: 'DELETE_ONLY',
subjectType: 'USER_ID',
subjectIds: ['fake-metrics-id'],
}),
)
.thenCallback(() => ({
statusCode: 200,
json: { data: { regulateId: 'fake-delete-regulation-id' } },
})),
await mockServer
.forGet(
'https://metametrics.metamask.test/regulations/fake-delete-regulation-id',
)
.withHeaders({ 'Content-Type': 'application/vnd.segment.v1+json' })
.thenCallback(() => ({
statusCode: 200,
json: {
data: {
regulation: {
overallStatus: 'FINISHED',
},
},
},
})),
];
};
/**
* Scenarios:
* 1. Deletion while Metrics is Opted in.
* 2. Deletion while Metrics is Opted out.
* 3. Deletion when user never opted for metrics.
*/
describe('Delete MetaMetrics Data @no-mmi', function (this: Suite) {
it('while user has opted in for metrics tracking', async function () {
await withFixtures(
{
fixtures: new FixtureBuilder()
.withMetaMetricsController({
metaMetricsId: 'fake-metrics-id',
participateInMetaMetrics: true,
})
.build(),
defaultGanacheOptions,
title: this.test?.fullTitle(),
testSpecificMock: mockSegment,
},
async ({
driver,
mockedEndpoint: mockedEndpoints,
}: TestSuiteArguments) => {
await unlockWallet(driver);

await driver.clickElement(selectors.accountOptionsMenuButton);
await driver.clickElement(selectors.globalMenuSettingsButton);
await driver.clickElement(selectors.securityAndPrivacySettings);

await driver.findElement(selectors.deletMetaMetricsSettings);
await driver.clickElement(selectors.deleteMetaMetricsDataButton);

// there is a race condition, where we need to wait before clicking clear button otherwise an error is thrown in the background
// we cannot wait for a UI conditon, so we a delay to mitigate this until another solution is found
await driver.delay(3000);
await driver.clickElementAndWaitToDisappear(selectors.clearButton);

const deleteMetaMetricsDataButton = await driver.findElement(
selectors.deleteMetaMetricsDataButton,
);
await (
deleteMetaMetricsDataButton as WebElementWithWaitForElementState
).waitForElementState('disabled');

const events = await getEventPayloads(
driver,
mockedEndpoints as MockedEndpoint[],
);
assert.equal(events.length, 3);
assert.deepStrictEqual(events[0].properties, {
category: 'Settings',
locale: 'en',
chain_id: '0x539',
environment_type: 'fullscreen',
});

await driver.clickElementAndWaitToDisappear(
'.mm-box button[aria-label="Close"]',
);
await driver.clickElement(selectors.accountOptionsMenuButton);
await driver.clickElement(selectors.globalMenuSettingsButton);
await driver.clickElement(selectors.securityAndPrivacySettings);

const deleteMetaMetricsDataButtonRefreshed =
await driver.findClickableElement(
selectors.deleteMetaMetricsDataButton,
);
assert.equal(
await deleteMetaMetricsDataButtonRefreshed.isEnabled(),
true,
'Delete MetaMetrics data button is enabled',
);
},
);
});
it('while user has opted out for metrics tracking', async function () {
await withFixtures(
{
fixtures: new FixtureBuilder()
.withMetaMetricsController({
metaMetricsId: 'fake-metrics-id',
})
.build(),
defaultGanacheOptions,
title: this.test?.fullTitle(),
testSpecificMock: mockSegment,
},
async ({
driver,
mockedEndpoint: mockedEndpoints,
}: TestSuiteArguments) => {
await unlockWallet(driver);

await driver.clickElement(selectors.accountOptionsMenuButton);
await driver.clickElement(selectors.globalMenuSettingsButton);
await driver.clickElement(selectors.securityAndPrivacySettings);

await driver.findElement(selectors.deletMetaMetricsSettings);
await driver.clickElement(selectors.deleteMetaMetricsDataButton);

// there is a race condition, where we need to wait before clicking clear button otherwise an error is thrown in the background
// we cannot wait for a UI conditon, so we a delay to mitigate this until another solution is found
await driver.delay(3000);
await driver.clickElementAndWaitToDisappear(selectors.clearButton);

const deleteMetaMetricsDataButton = await driver.findElement(
selectors.deleteMetaMetricsDataButton,
);
await (
deleteMetaMetricsDataButton as WebElementWithWaitForElementState
).waitForElementState('disabled');

const events = await getEventPayloads(
driver,
mockedEndpoints as MockedEndpoint[],
);
assert.equal(events.length, 2);

await driver.clickElementAndWaitToDisappear(
'.mm-box button[aria-label="Close"]',
);
await driver.clickElement(selectors.accountOptionsMenuButton);
await driver.clickElement(selectors.globalMenuSettingsButton);
await driver.clickElement(selectors.securityAndPrivacySettings);

const deleteMetaMetricsDataButtonRefreshed = await driver.findElement(
selectors.deleteMetaMetricsDataButton,
);
await (
deleteMetaMetricsDataButtonRefreshed as WebElementWithWaitForElementState
).waitForElementState('disabled');
},
);
});
it('when the user has never opted in for metrics', async function () {
await withFixtures(
{
fixtures: new FixtureBuilder().build(),
defaultGanacheOptions,
title: this.test?.fullTitle(),
testSpecificMock: mockSegment,
},
async ({ driver }: { driver: Driver }) => {
await unlockWallet(driver);

await driver.clickElement(selectors.accountOptionsMenuButton);
await driver.clickElement(selectors.globalMenuSettingsButton);
await driver.clickElement(selectors.securityAndPrivacySettings);
await driver.findElement(selectors.deletMetaMetricsSettings);

const deleteMetaMetricsDataButton = await driver.findElement(
selectors.deleteMetaMetricsDataButton,
);
assert.equal(
await deleteMetaMetricsDataButton.isEnabled(),
false,
'Delete MetaMetrics data button is disabled',
);
},
);
});
});
2 changes: 2 additions & 0 deletions test/e2e/webdriver/driver.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,8 @@ function wrapElementWithAPI(element, driver) {
return await driver.wait(until.stalenessOf(element), timeout);
case 'visible':
return await driver.wait(until.elementIsVisible(element), timeout);
case 'disabled':
return await driver.wait(until.elementIsDisabled(element), timeout);
default:
throw new Error(`Provided state: '${state}' is not supported`);
}
Expand Down
5 changes: 5 additions & 0 deletions test/e2e/webdriver/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { WebElement, WebElementPromise } from 'selenium-webdriver';

export type WebElementWithWaitForElementState = WebElement & {
waitForElementState: (state: unknown, timeout?: unknown) => WebElementPromise;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import * as React from 'react';
import { fireEvent } from '@testing-library/react';
import configureStore from '../../../store/store';
import { renderWithProvider } from '../../../../test/lib/render-helpers';
import * as Actions from '../../../store/actions';
import { DELETE_METAMETRICS_DATA_MODAL_CLOSE } from '../../../store/actionConstants';
import ClearMetaMetricsData from './clear-metametrics-data';

const mockCloseDeleteMetaMetricsDataModal = jest.fn().mockImplementation(() => {
return {
type: DELETE_METAMETRICS_DATA_MODAL_CLOSE,
};
});

jest.mock('../../../store/actions', () => ({
createMetaMetricsDataDeletionTask: jest.fn(),
}));

jest.mock('../../../ducks/app/app.ts', () => {
return {
hideDeleteMetaMetricsDataModal: () => {
return mockCloseDeleteMetaMetricsDataModal();
},
};
});

describe('ClearMetaMetricsData', () => {
afterEach(() => {
jest.clearAllMocks();
});

it('should render the data deletion error modal', async () => {
const store = configureStore({});
const { getByText } = renderWithProvider(<ClearMetaMetricsData />, store);

expect(getByText('Delete MetaMetrics data?')).toBeInTheDocument();
expect(
getByText(
'We are about to remove all your MetaMetrics data. Are you sure?',
),
).toBeInTheDocument();
});

it('should call createMetaMetricsDataDeletionTask when Clear button is clicked', () => {
const store = configureStore({});
const { getByText } = renderWithProvider(<ClearMetaMetricsData />, store);
expect(getByText('Clear')).toBeEnabled();
fireEvent.click(getByText('Clear'));
expect(Actions.createMetaMetricsDataDeletionTask).toHaveBeenCalledTimes(1);
});

it('should call hideDeleteMetaMetricsDataModal when Cancel button is clicked', () => {
const store = configureStore({});
const { getByText } = renderWithProvider(<ClearMetaMetricsData />, store);
expect(getByText('Cancel')).toBeEnabled();
fireEvent.click(getByText('Cancel'));
expect(mockCloseDeleteMetaMetricsDataModal).toHaveBeenCalledTimes(1);
});
});
Loading

0 comments on commit 11ca25b

Please sign in to comment.