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

Move snap_manageAccounts to a gated permitted method #2869

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from
Draft
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
38 changes: 37 additions & 1 deletion packages/snaps-controllers/src/snaps/SnapController.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
handlerEndowments,
SnapEndowments,
} from '@metamask/snaps-rpc-methods';
import type { SnapId } from '@metamask/snaps-sdk';
import type { Snap, SnapId } from '@metamask/snaps-sdk';
import { AuxiliaryFileEncoding, text } from '@metamask/snaps-sdk';
import { Text } from '@metamask/snaps-sdk/jsx';
import type { SnapPermissions, RpcOrigins } from '@metamask/snaps-utils';
Expand Down Expand Up @@ -1010,6 +1010,42 @@
snapController.destroy();
});

it('filters out removed permissions', async () => {
const messenger = getSnapControllerMessenger();
const initialPermissions: SnapPermissions = {
[handlerEndowments.onRpcRequest as string]: { snaps: false, dapps: true },
// eslint-disable-next-line @typescript-eslint/naming-convention
snap_manageAccounts: {},
};

const { manifest } = await getMockSnapFilesWithUpdatedChecksum({
manifest: getSnapManifest({
initialPermissions,
}),
});

const snapController = getSnapController(
getSnapControllerOptions({
messenger,
detectSnapLocation: loopbackDetect({
manifest: manifest.result,
}),
}),
);

const snap = await snapController.installSnaps(MOCK_ORIGIN, {
[MOCK_SNAP_ID]: {},
});

const permissions = (snap[MOCK_SNAP_ID] as Snap).initialPermissions;

expect(permissions).toStrictEqual({
[handlerEndowments.onRpcRequest as string]: { snaps: false, dapps: true },
});

snapController.destroy();
});

it('throws an error if the installation is disabled during installSnaps', async () => {
const controller = getSnapController(
getSnapControllerOptions({
Expand Down Expand Up @@ -1850,7 +1886,7 @@
});

// This isn't stable in CI unfortunately
it.skip('throws if the Snap is terminated while executing', async () => {

Check warning on line 1889 in packages/snaps-controllers/src/snaps/SnapController.test.tsx

View workflow job for this annotation

GitHub Actions / Build, lint, and test / Lint (@metamask/snaps-controllers)

Disabled test
const { manifest, sourceCode, svgIcon } =
await getMockSnapFilesWithUpdatedChecksum({
sourceCode: `
Expand Down
8 changes: 4 additions & 4 deletions packages/snaps-rpc-methods/jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@ module.exports = deepmerge(baseConfig, {
],
coverageThreshold: {
global: {
branches: 92.85,
functions: 97.23,
lines: 97.8,
statements: 97.31,
branches: 92.88,
functions: 97.22,
lines: 97.81,
statements: 97.32,
},
},
});
9 changes: 0 additions & 9 deletions packages/snaps-rpc-methods/src/permissions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -211,15 +211,6 @@ describe('buildSnapRestrictedMethodSpecifications', () => {
],
"targetName": "snap_getPreferences",
},
"snap_manageAccounts": {
"allowedCaveats": null,
"methodImplementation": [Function],
"permissionType": "RestrictedMethod",
"subjectTypes": [
"snap",
],
"targetName": "snap_manageAccounts",
},
"snap_manageState": {
"allowedCaveats": null,
"methodImplementation": [Function],
Expand Down
51 changes: 38 additions & 13 deletions packages/snaps-rpc-methods/src/permissions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,21 @@ import {
} from './restricted';
import { selectHooks } from './utils';

const REMOVED_PERMISSIONS = Object.freeze(['snap_manageAccounts']);

/**
* Filters out permissions that have been removed from the Snap API.
*
* @param initialPermission - The initial permission to filter.
* @returns Whether the permission has been removed.
*/
export const filterRemovedPermissions = (
initialPermission: [string, unknown],
) => {
const [value] = initialPermission;
return !REMOVED_PERMISSIONS.some((permission) => permission === value);
};

/**
* Map initial permissions as defined in a Snap manifest to something that can
* be processed by the PermissionsController. Each caveat mapping function
Expand All @@ -30,22 +45,32 @@ export function processSnapPermissions(
initialPermissions: SnapPermissions,
): Record<string, Pick<PermissionConstraint, 'caveats'>> {
return Object.fromEntries(
Object.entries(initialPermissions).map(([initialPermission, value]) => {
if (hasProperty(caveatMappers, initialPermission)) {
return [initialPermission, caveatMappers[initialPermission](value)];
} else if (hasProperty(endowmentCaveatMappers, initialPermission)) {
Object.entries(initialPermissions)
.filter(filterRemovedPermissions)
.map(([initialPermission, value]) => {
if (
REMOVED_PERMISSIONS.some(
(permission) => permission === initialPermission,
)
) {
return [];
}

if (hasProperty(caveatMappers, initialPermission)) {
return [initialPermission, caveatMappers[initialPermission](value)];
} else if (hasProperty(endowmentCaveatMappers, initialPermission)) {
return [
initialPermission,
endowmentCaveatMappers[initialPermission](value),
];
}

// If we have no mapping, this may be a non-snap permission, return as-is
return [
initialPermission,
endowmentCaveatMappers[initialPermission](value),
value as Pick<PermissionConstraint, 'caveats'>,
];
}

// If we have no mapping, this may be a non-snap permission, return as-is
return [
initialPermission,
value as Pick<PermissionConstraint, 'caveats'>,
];
}),
}),
);
}

Expand Down
2 changes: 2 additions & 0 deletions packages/snaps-rpc-methods/src/permitted/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { getInterfaceStateHandler } from './getInterfaceState';
import { getSnapsHandler } from './getSnaps';
import { invokeKeyringHandler } from './invokeKeyring';
import { invokeSnapSugarHandler } from './invokeSnapSugar';
import { manageAccountsHandler } from './manageAccounts';
import { requestSnapsHandler } from './requestSnaps';
import { resolveInterfaceHandler } from './resolveInterface';
import { updateInterfaceHandler } from './updateInterface';
Expand All @@ -27,6 +28,7 @@ export const methodHandlers = {
snap_resolveInterface: resolveInterfaceHandler,
snap_getCurrencyRate: getCurrencyRateHandler,
snap_experimentalProviderRequest: providerRequestHandler,
snap_manageAccounts: manageAccountsHandler,
};
/* eslint-enable @typescript-eslint/naming-convention */

Expand Down
4 changes: 3 additions & 1 deletion packages/snaps-rpc-methods/src/permitted/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import type { GetClientStatusHooks } from './getClientStatus';
import type { GetCurrencyRateMethodHooks } from './getCurrencyRate';
import type { GetInterfaceStateMethodHooks } from './getInterfaceState';
import type { GetSnapsHooks } from './getSnaps';
import type { ManageAccountsMethodHooks } from './manageAccounts';
import type { RequestSnapsHooks } from './requestSnaps';
import type { ResolveInterfaceMethodHooks } from './resolveInterface';
import type { UpdateInterfaceMethodHooks } from './updateInterface';
Expand All @@ -18,7 +19,8 @@ export type PermittedRpcMethodHooks = GetAllSnapsHooks &
GetInterfaceStateMethodHooks &
ResolveInterfaceMethodHooks &
GetCurrencyRateMethodHooks &
ProviderRequestMethodHooks;
ProviderRequestMethodHooks &
ManageAccountsMethodHooks;

export * from './handlers';
export * from './middleware';
208 changes: 208 additions & 0 deletions packages/snaps-rpc-methods/src/permitted/manageAccounts.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,208 @@
import { JsonRpcEngine } from '@metamask/json-rpc-engine';
import { rpcErrors } from '@metamask/rpc-errors';
import type { ManageAccountsResult } from '@metamask/snaps-sdk';
import type {
JsonRpcFailure,
JsonRpcRequest,
PendingJsonRpcResponse,
} from '@metamask/utils';

import type { ManageAccountsParameters } from './manageAccounts';
import { manageAccountsHandler } from './manageAccounts';

describe('snap_manageAccounts', () => {
describe('manageAccountsHandler', () => {
it('has the expected shape', () => {
expect(manageAccountsHandler).toMatchObject({
methodNames: ['snap_manageAccounts'],
implementation: expect.any(Function),
hookNames: {
hasPermission: true,
handleKeyringSnapMessage: true,
},
});
});
});

describe('implementation', () => {
it('returns the result from the `handleKeyringSnapMessage` hook', async () => {
const { implementation } = manageAccountsHandler;

const hasPermission = jest.fn().mockReturnValue(true);
const handleKeyringSnapMessage = jest.fn().mockReturnValue('foo');

const hooks = {
hasPermission,
handleKeyringSnapMessage,
};

const engine = new JsonRpcEngine();

engine.push((request, response, next, end) => {
const result = implementation(
request as JsonRpcRequest<ManageAccountsParameters>,
response as PendingJsonRpcResponse<ManageAccountsResult>,
next,
end,
hooks,
);

result?.catch(end);
});

const response = await engine.handle({
jsonrpc: '2.0',
id: 1,
method: 'snap_manageAccounts',
params: {
method: 'foo',
params: { bar: 'baz' },
},
});

expect(handleKeyringSnapMessage).toHaveBeenCalledWith({
method: 'foo',
params: { bar: 'baz' },
});

expect(response).toStrictEqual({ jsonrpc: '2.0', id: 1, result: 'foo' });
});

it('throws an error if the snap does not have permission', async () => {
const { implementation } = manageAccountsHandler;

const hasPermission = jest.fn().mockReturnValue(false);
const handleKeyringSnapMessage = jest.fn().mockReturnValue('foo');

const hooks = {
hasPermission,
handleKeyringSnapMessage,
};

const engine = new JsonRpcEngine();

engine.push((request, response, next, end) => {
const result = implementation(
request as JsonRpcRequest<ManageAccountsParameters>,
response as PendingJsonRpcResponse<ManageAccountsResult>,
next,
end,
hooks,
);

result?.catch(end);
});

const response = (await engine.handle({
jsonrpc: '2.0',
id: 1,
method: 'snap_manageAccounts',
params: {
method: 'foo',
params: { bar: 'baz' },
},
})) as JsonRpcFailure;

expect(response.error).toStrictEqual({
...rpcErrors.methodNotFound().serialize(),
stack: expect.any(String),
});
});

it('throws an error if the `handleKeyringSnapMessage` hook throws', async () => {
const { implementation } = manageAccountsHandler;

const hasPermission = jest.fn().mockReturnValue(true);
const handleKeyringSnapMessage = jest
.fn()
.mockRejectedValue(new Error('foo'));

const hooks = {
hasPermission,
handleKeyringSnapMessage,
};

const engine = new JsonRpcEngine();

engine.push((request, response, next, end) => {
const result = implementation(
request as JsonRpcRequest<ManageAccountsParameters>,
response as PendingJsonRpcResponse<ManageAccountsResult>,
next,
end,
hooks,
);

result?.catch(end);
});

const response = (await engine.handle({
jsonrpc: '2.0',
id: 1,
method: 'snap_manageAccounts',
params: {
method: 'foo',
params: { bar: 'baz' },
},
})) as JsonRpcFailure;

expect(response.error).toStrictEqual({
code: -32603,
message: 'foo',
data: {
cause: {
message: 'foo',
stack: expect.any(String),
},
},
});
});

it('throws on invalid params', async () => {
const { implementation } = manageAccountsHandler;

const hasPermission = jest.fn().mockReturnValue(true);
const handleKeyringSnapMessage = jest.fn().mockReturnValue('foo');

const hooks = {
hasPermission,
handleKeyringSnapMessage,
};

const engine = new JsonRpcEngine();

engine.push((request, response, next, end) => {
const result = implementation(
request as JsonRpcRequest<ManageAccountsParameters>,
response as PendingJsonRpcResponse<ManageAccountsResult>,
next,
end,
hooks,
);

result?.catch(end);
});

const response = await engine.handle({
jsonrpc: '2.0',
id: 1,
method: 'snap_manageAccounts',
params: {
method: 'foo',
params: 42,
},
});

expect(response).toStrictEqual({
jsonrpc: '2.0',
id: 1,
error: {
code: -32602,
message:
'Invalid params: At path: params -- Expected the value to satisfy a union of `array | record`, but received: 42.',
stack: expect.any(String),
},
});
});
});
});
Loading
Loading