1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-11-25 11:28:51 +01:00
metamask-extension/ui/selectors/permissions.js
Erik Marks 31cf7c10a4
Permission System 2.0 (#12243)
# Permission System 2.0

## Background

This PR migrates the extension permission system to [the new `PermissionController`](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions).
The original permission system, based on [`rpc-cap`](https://github.com/MetaMask/rpc-cap), introduced [`ZCAP-LD`](https://w3c-ccg.github.io/zcap-ld/)-like permissions to our JSON-RPC stack.
We used it to [implement](https://github.com/MetaMask/metamask-extension/pull/7004) what we called "LoginPerSite" in [version 7.7.0](https://github.com/MetaMask/metamask-extension/releases/tag/v7.7.0) of the extension, which enabled the user to choose which accounts, if any, should be exposed to each dapp.
While that was a worthwhile feature in and of itself, we wanted a permission _system_ in order to enable everything we are going to with Snaps.
Unfortunately, the original permission system was difficult to use, and necessitated the creation of the original `PermissionsController` (note the "s"), which was more or less a wrapper for `rpc-cap`.

With this PR, we shake off the yoke of the original permission system, in favor of the modular, self-contained, ergonomic, and more mature permission system 2.0.

Note that [the `PermissionController` readme](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions/README.md) explains how the new permission system works.

The `PermissionController` and `SubjectMetadataController` are currently shipped via `@metamask/snap-controllers`. This is a temporary state of affairs, and we'll move them to `@metamask/controllers` once they've landed in prod.

## Changes in Detail

First, the changes in this PR are not as big as they seem. Roughly half of the additions in this PR are fixtures in the test for the new migration (number 68), and a significant portion of the remaining ~2500 lines are due to find-and-replace changes in other test fixtures and UI files.

- The extension `PermissionsController` has been deleted, and completely replaced with the new `PermissionController` from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The original `PermissionsController` "domain metadata" functionality is now managed by the new `SubjectMetadataController`, also from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers).
- The permission activity and history log controller has been renamed `PermissionLogController` and has its own top-level state key, but is otherwise functionally equivalent to the existing implementation.
- Migration number 68 has been added to account for the new state changes.
- The tests in `app/scripts/controllers/permissions` have been migrated from `mocha` to `jest`.

Reviewers should focus their attention on the following files:

- `app/scripts/`
  - `metamask-controller.js`
    - This is where most of the integration work for the new `PermissionController` occurs.
      Some functions that were internal to the original controller were moved here.
  - `controllers/permissions/`
    - `selectors.js`
      - These selectors are for `ControllerMessenger` selector subscriptions. The actual subscriptions occur in `metamask-controller.js`. See the `ControllerMessenger` implementation for details.
    - `specifications.js`
      - The caveat and permission specifications are required by the new `PermissionController`, and are used to specify the `eth_accounts` permission and its JSON-RPC method implementation.
        See the `PermissionController` readme for details.
  - `migrations/068.js`
    - The new state should be cross-referenced with the controllers that manage it.
      The accompanying tests should also be thoroughly reviewed.

Some files may appear new but have just moved and/or been renamed:

- `app/scripts/lib/rpc-method-middleware/handlers/request-accounts.js`
  - This was previously implemented in `controllers/permissions/permissionsMethodMiddleware.js`.
- `test/mocks/permissions.js`
  - A truncated version of `test/mocks/permission-controller.js`.

Co-authored-by: Mark Stacey <markjstacey@gmail.com>
2021-12-06 19:16:49 -08:00

273 lines
7.6 KiB
JavaScript

import { CaveatTypes } from '../../shared/constants/permissions';
import {
getMetaMaskAccountsOrdered,
getOriginOfCurrentTab,
getSelectedAddress,
} from '.';
// selectors
/**
* Get the permission subjects object.
*
* @param {Object} state - The current state.
* @returns {Object} The permissions subjects object.
*/
export function getPermissionSubjects(state) {
return state.metamask.subjects || {};
}
/**
* Get the permission subjects metadata object.
*
* @param {Object} state - The current state.
* @returns {Object} The permission subjects metadata object.
*/
export function getPermissionSubjectsMetadata(state) {
return state.metamask.subjectMetadata || {};
}
/**
* Selects the permitted accounts from the eth_accounts permission given state
* and an origin.
*
* @param {Object} state - The current state.
* @param {string} origin - The origin/subject to get the permitted accounts for.
* @returns {Array<string>} An empty array or an array of accounts.
*/
export function getPermittedAccounts(state, origin) {
return getAccountsFromPermission(
getAccountsPermissionFromSubject(subjectSelector(state, origin)),
);
}
/**
* Selects the permitted accounts from the eth_accounts permission for the
* origin of the current tab.
*
* @param {Object} state - The current state.
* @returns {Array<string>} An empty array or an array of accounts.
*/
export function getPermittedAccountsForCurrentTab(state) {
return getPermittedAccounts(state, getOriginOfCurrentTab(state));
}
/**
* Returns a map of permitted accounts by origin for all origins.
*
* @param {Object} state - The current state.
* @returns {Object} Permitted accounts by origin.
*/
export function getPermittedAccountsByOrigin(state) {
const subjects = getPermissionSubjects(state);
return Object.keys(subjects).reduce((acc, subjectKey) => {
const accounts = getAccountsFromSubject(subjects[subjectKey]);
if (accounts.length > 0) {
acc[subjectKey] = accounts;
}
return acc;
}, {});
}
/**
* Returns an array of connected subject objects, with the following properties:
* - extensionId
* - key (i.e. origin)
* - name
* - icon
*
* @param {Object} state - The current state.
* @returns {Array<Object>} An array of connected subject objects.
*/
export function getConnectedSubjectsForSelectedAddress(state) {
const { selectedAddress } = state.metamask;
const subjects = getPermissionSubjects(state);
const subjectMetadata = getPermissionSubjectsMetadata(state);
const connectedSubjects = [];
Object.entries(subjects).forEach(([subjectKey, subjectValue]) => {
const exposedAccounts = getAccountsFromSubject(subjectValue);
if (!exposedAccounts.includes(selectedAddress)) {
return;
}
const { extensionId, name, iconUrl } = subjectMetadata[subjectKey] || {};
connectedSubjects.push({
extensionId,
origin: subjectKey,
name,
iconUrl,
});
});
return connectedSubjects;
}
/**
* Returns an object mapping addresses to objects mapping origins to connected
* subject info. Subject info objects have the following properties:
* - iconUrl
* - name
*
* @param {Object} state - The current state.
* @returns {Object} A mapping of addresses to a mapping of origins to
* connected subject info.
*/
export function getAddressConnectedSubjectMap(state) {
const subjectMetadata = getPermissionSubjectsMetadata(state);
const accountsMap = getPermittedAccountsByOrigin(state);
const addressConnectedIconMap = {};
Object.keys(accountsMap).forEach((subjectKey) => {
const { iconUrl, name } = subjectMetadata[subjectKey] || {};
accountsMap[subjectKey].forEach((address) => {
const nameToRender = name || subjectKey;
addressConnectedIconMap[address] = addressConnectedIconMap[address]
? {
...addressConnectedIconMap[address],
[subjectKey]: { iconUrl, name: nameToRender },
}
: { [subjectKey]: { iconUrl, name: nameToRender } };
});
});
return addressConnectedIconMap;
}
// selector helpers
function getAccountsFromSubject(subject) {
return getAccountsFromPermission(getAccountsPermissionFromSubject(subject));
}
function getAccountsPermissionFromSubject(subject = {}) {
return subject.permissions?.eth_accounts || {};
}
function getAccountsFromPermission(accountsPermission) {
const accountsCaveat = getAccountsCaveatFromPermission(accountsPermission);
return accountsCaveat && Array.isArray(accountsCaveat.value)
? accountsCaveat.value
: [];
}
function getAccountsCaveatFromPermission(accountsPermission = {}) {
return (
Array.isArray(accountsPermission.caveats) &&
accountsPermission.caveats.find(
(caveat) => caveat.type === CaveatTypes.restrictReturnedAccounts,
)
);
}
function subjectSelector(state, origin) {
return origin && state.metamask.subjects?.[origin];
}
export function getAccountToConnectToActiveTab(state) {
const selectedAddress = getSelectedAddress(state);
const connectedAccounts = getPermittedAccountsForCurrentTab(state);
const {
metamask: { identities },
} = state;
const numberOfAccounts = Object.keys(identities).length;
if (
connectedAccounts.length &&
connectedAccounts.length !== numberOfAccounts
) {
if (
connectedAccounts.findIndex((address) => address === selectedAddress) ===
-1
) {
return identities[selectedAddress];
}
}
return undefined;
}
export function getOrderedConnectedAccountsForActiveTab(state) {
const {
activeTab,
metamask: { permissionHistory },
} = state;
const permissionHistoryByAccount =
// eslint-disable-next-line camelcase
permissionHistory[activeTab.origin]?.eth_accounts?.accounts;
const orderedAccounts = getMetaMaskAccountsOrdered(state);
const connectedAccounts = getPermittedAccountsForCurrentTab(state);
return orderedAccounts
.filter((account) => connectedAccounts.includes(account.address))
.map((account) => ({
...account,
lastActive: permissionHistoryByAccount?.[account.address],
}))
.sort(
({ lastSelected: lastSelectedA }, { lastSelected: lastSelectedB }) => {
if (lastSelectedA === lastSelectedB) {
return 0;
} else if (lastSelectedA === undefined) {
return 1;
} else if (lastSelectedB === undefined) {
return -1;
}
return lastSelectedB - lastSelectedA;
},
);
}
export function getPermissionsForActiveTab(state) {
const { activeTab, metamask } = state;
const { subjects = {} } = metamask;
return Object.keys(subjects[activeTab.origin]?.permissions || {}).map(
(parentCapability) => {
return {
key: parentCapability,
};
},
);
}
export function activeTabHasPermissions(state) {
const { activeTab, metamask } = state;
const { subjects = {} } = metamask;
return Boolean(
Object.keys(subjects[activeTab.origin]?.permissions || {}).length > 0,
);
}
export function getLastConnectedInfo(state) {
const { permissionHistory = {} } = state.metamask;
return Object.keys(permissionHistory).reduce((acc, origin) => {
const ethAccountsHistory = JSON.parse(
JSON.stringify(permissionHistory[origin].eth_accounts),
);
return {
...acc,
[origin]: ethAccountsHistory,
};
}, {});
}
export function getPermissionsRequests(state) {
return Object.values(state.metamask.pendingApprovals)
.filter(({ type }) => type === 'wallet_requestPermissions')
.map(({ requestData }) => requestData);
}
export function getFirstPermissionRequest(state) {
const requests = getPermissionsRequests(state);
return requests && requests[0] ? requests[0] : null;
}