Skip to content

Commit

Permalink
CAIP Multichain API with permission refactor changes (#4961)
Browse files Browse the repository at this point in the history
## Explanation

~~This diff is a bit messy since it also brings in the [core PR that
refactors the CAIP-25
permission](#4950) which the
[caip-multichain-api](https://github.com/MetaMask/core/tree/caip-multichain-api)
branch doesn't have yet.~~

The main thing this PR does is adds `getSessionScopes()` which massages
the new CAIP-25 permission into a `NormalizedScopesObject`


## References

<!--
Are there any issues that this pull request is tied to?
Are there other links that reviewers should consult to understand these
changes better?
Are there client or consumer pull requests to adopt any breaking
changes?

For example:

* Fixes #12345
* Related to #67890
-->

## Changelog

<!--
If you're making any consumer-facing changes, list those changes here as
if you were updating a changelog, using the template below as a guide.

(CATEGORY is one of BREAKING, ADDED, CHANGED, DEPRECATED, REMOVED, or
FIXED. For security-related issues, follow the Security Advisory
process.)

Please take care to name the exact pieces of the API you've added or
changed (e.g. types, interfaces, functions, or methods).

If there are any breaking changes, make sure to offer a solution for
consumers to follow once they upgrade to the changes.

Finally, if you're only making changes to development scripts or tests,
you may replace the template below with "None".
-->

### `@metamask/package-a`

- **<CATEGORY>**: Your change here
- **<CATEGORY>**: Your change here

### `@metamask/package-b`

- **<CATEGORY>**: Your change here
- **<CATEGORY>**: Your change here

## Checklist

- [ ] I've updated the test suite for new or updated code as appropriate
- [ ] I've updated documentation (JSDoc, Markdown, etc.) for new or
updated code as appropriate
- [ ] I've highlighted breaking changes using the "BREAKING" category
above as appropriate
- [ ] I've prepared draft pull requests for clients and consumer
packages to resolve any breaking changes

---------

Co-authored-by: Alex Donesky <adonesky@gmail.com>
  • Loading branch information
jiexi and adonesky1 authored Nov 21, 2024
1 parent d6dfc71 commit 0d167a3
Show file tree
Hide file tree
Showing 17 changed files with 393 additions and 79 deletions.
2 changes: 1 addition & 1 deletion packages/multichain/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@
},
"devDependencies": {
"@metamask/auto-changelog": "^3.4.4",
"@metamask/json-rpc-engine": "^9.0.3",
"@metamask/json-rpc-engine": "^10.0.1",
"@metamask/network-controller": "^22.0.2",
"@metamask/permission-controller": "^11.0.3",
"@open-rpc/meta-schema": "^1.14.6",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,9 @@ import {
Caip25CaveatType,
Caip25EndowmentPermissionName,
} from '../caip25Permission';
import { mergeScopes } from '../scope/transform';
import { KnownWalletScopeString, type ScopeString } from '../scope/types';
import { KnownWalletScopeString } from '../scope/constants';
import type { InternalScopeString } from '../scope/types';
import { getSessionScopes } from './caip-permission-adapter-session-scopes';

/**
* Middleware to handle CAIP-25 permission requests.
Expand Down Expand Up @@ -61,17 +62,14 @@ export async function caipPermissionAdapterMiddleware(
const { chainId } =
hooks.getNetworkConfigurationByNetworkClientId(networkClientId);

const scope: ScopeString = `eip155:${parseInt(chainId, 16)}`;
const scope: InternalScopeString = `eip155:${parseInt(chainId, 16)}`;

const scopesObject = mergeScopes(
caveat.value.requiredScopes,
caveat.value.optionalScopes,
);
const sesionScopes = getSessionScopes(caveat.value);

if (
!scopesObject[scope]?.methods?.includes(method) &&
!scopesObject[KnownWalletScopeString.Eip155]?.methods?.includes(method) &&
!scopesObject.wallet?.methods?.includes(method)
!sesionScopes[scope]?.methods?.includes(method) &&
!sesionScopes[KnownWalletScopeString.Eip155]?.methods?.includes(method) &&
!sesionScopes.wallet?.methods?.includes(method)
) {
return end(providerErrors.unauthorized());
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import {
KnownNotifications,
KnownRpcMethods,
KnownWalletNamespaceRpcMethods,
KnownWalletRpcMethods,
} from '../scope/constants';
import { getSessionScopes } from './caip-permission-adapter-session-scopes';

describe('CAIP-25 session scopes adapters', () => {
describe('getSessionScopes', () => {
it('returns a NormalizedScopesObject for the wallet scope', () => {
const result = getSessionScopes({
requiredScopes: {},
optionalScopes: {
wallet: {
accounts: [],
},
},
});

expect(result).toStrictEqual({
wallet: {
methods: KnownWalletRpcMethods,
notifications: [],
accounts: [],
},
});
});

it('returns a NormalizedScopesObject for the wallet:eip155 scope', () => {
const result = getSessionScopes({
requiredScopes: {},
optionalScopes: {
'wallet:eip155': {
accounts: ['wallet:eip155:0xdeadbeef'],
},
},
});

expect(result).toStrictEqual({
'wallet:eip155': {
methods: KnownWalletNamespaceRpcMethods.eip155,
notifications: [],
accounts: ['wallet:eip155:0xdeadbeef'],
},
});
});

it('returns a NormalizedScopesObject with empty methods and notifications for scope with wallet namespace and unknown reference', () => {
const result = getSessionScopes({
requiredScopes: {},
optionalScopes: {
'wallet:foobar': {
accounts: ['wallet:foobar:0xdeadbeef'],
},
},
});

expect(result).toStrictEqual({
'wallet:foobar': {
methods: [],
notifications: [],
accounts: ['wallet:foobar:0xdeadbeef'],
},
});
});

it('returns a NormalizedScopesObject for a eip155 namespaced scope', () => {
const result = getSessionScopes({
requiredScopes: {},
optionalScopes: {
'eip155:1': {
accounts: ['eip155:1:0xdeadbeef'],
},
},
});

expect(result).toStrictEqual({
'eip155:1': {
methods: KnownRpcMethods.eip155,
notifications: KnownNotifications.eip155,
accounts: ['eip155:1:0xdeadbeef'],
},
});
});
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import { KnownCaipNamespace } from '@metamask/utils';

import type { Caip25CaveatValue } from '../caip25Permission';
import {
KnownNotifications,
KnownRpcMethods,
KnownWalletNamespaceRpcMethods,
KnownWalletRpcMethods,
} from '../scope/constants';
import { mergeScopes } from '../scope/transform';
import type {
InternalScopesObject,
NonWalletKnownCaipNamespace,
NormalizedScopesObject,
} from '../scope/types';
import { parseScopeString } from '../scope/types';

/**
* Converts an InternalScopesObject to a NormalizedScopesObject.
* @param internalScopesObject - The InternalScopesObject to convert.
* @returns A NormalizedScopesObject.
*/
const getNormalizedScopesObject = (
internalScopesObject: InternalScopesObject,
) => {
const normalizedScopes: NormalizedScopesObject = {};

Object.entries(internalScopesObject).forEach(
([_scopeString, { accounts }]) => {
const scopeString = _scopeString as keyof typeof internalScopesObject;
const { namespace, reference } = parseScopeString(scopeString);
let methods: string[] = [];
let notifications: string[] = [];

if (namespace === KnownCaipNamespace.Wallet) {
if (reference) {
methods =
KnownWalletNamespaceRpcMethods[
reference as NonWalletKnownCaipNamespace
] ?? [];
} else {
methods = KnownWalletRpcMethods;
}
} else {
methods =
KnownRpcMethods[namespace as NonWalletKnownCaipNamespace] ?? [];
notifications =
KnownNotifications[namespace as NonWalletKnownCaipNamespace] ?? [];
}

normalizedScopes[scopeString] = {
methods,
notifications,
accounts,
};
},
);

return normalizedScopes;
};

/**
* Takes the scopes from an endowment:caip25 permission caveat value,
* hydrates them with supported methods and notifications, and returns a NormalizedScopesObject.
* @param caip25CaveatValue - The CAIP-25 CaveatValue to convert.
* @returns A NormalizedScopesObject.
*/
export const getSessionScopes = (
caip25CaveatValue: Pick<
Caip25CaveatValue,
'requiredScopes' | 'optionalScopes'
>,
) => {
return mergeScopes(
getNormalizedScopesObject(caip25CaveatValue.requiredScopes),
getNormalizedScopesObject(caip25CaveatValue.optionalScopes),
);
};
66 changes: 57 additions & 9 deletions packages/multichain/src/handlers/wallet-getSession.test.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,19 @@
import type { JsonRpcRequest } from '@metamask/utils';

import * as PermissionAdapterSessionScopes from '../adapters/caip-permission-adapter-session-scopes';
import {
Caip25CaveatType,
Caip25EndowmentPermissionName,
} from '../caip25Permission';
import { walletGetSession } from './wallet-getSession';

jest.mock('../adapters/caip-permission-adapter-session-scopes', () => ({
getSessionScopes: jest.fn(),
}));
const MockPermissionAdapterSessionScopes = jest.mocked(
PermissionAdapterSessionScopes,
);

const baseRequest: JsonRpcRequest & { origin: string } = {
origin: 'http://test.com',
jsonrpc: '2.0' as const,
Expand All @@ -21,25 +29,17 @@ const createMockedHandler = () => {
value: {
requiredScopes: {
'eip155:1': {
methods: ['eth_call'],
notifications: [],
accounts: [],
},
'eip155:5': {
methods: ['eth_chainId'],
notifications: [],
accounts: [],
},
},
optionalScopes: {
'eip155:1': {
methods: ['net_version'],
notifications: ['chainChanged'],
accounts: [],
},
wallet: {
methods: ['wallet_watchAsset'],
notifications: [],
accounts: [],
},
},
Expand Down Expand Up @@ -67,6 +67,10 @@ const createMockedHandler = () => {
};

describe('wallet_getSession', () => {
afterEach(() => {
jest.restoreAllMocks();
});

it('gets the authorized scopes from the CAIP-25 endowment permission', async () => {
const { handler, getCaveat } = createMockedHandler();

Expand All @@ -90,9 +94,53 @@ describe('wallet_getSession', () => {
});
});

it('returns the merged scopes', async () => {
it('gets the session scopes from the CAIP-25 caveat value', async () => {
const { handler } = createMockedHandler();

await handler(baseRequest);
expect(
MockPermissionAdapterSessionScopes.getSessionScopes,
).toHaveBeenCalledWith({
requiredScopes: {
'eip155:1': {
accounts: [],
},
'eip155:5': {
accounts: [],
},
},
optionalScopes: {
'eip155:1': {
accounts: [],
},
wallet: {
accounts: [],
},
},
});
});

it('returns the session scopes', async () => {
const { handler, response } = createMockedHandler();

MockPermissionAdapterSessionScopes.getSessionScopes.mockReturnValue({
'eip155:1': {
methods: ['eth_call', 'net_version'],
notifications: ['chainChanged'],
accounts: [],
},
'eip155:5': {
methods: ['eth_chainId'],
notifications: [],
accounts: [],
},
wallet: {
methods: ['wallet_watchAsset'],
notifications: [],
accounts: [],
},
});

await handler(baseRequest);
expect(response.result).toStrictEqual({
sessionScopes: {
Expand Down
11 changes: 4 additions & 7 deletions packages/multichain/src/handlers/wallet-getSession.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import type { Caveat } from '@metamask/permission-controller';
import type { JsonRpcRequest, JsonRpcSuccess } from '@metamask/utils';
import type { NormalizedScopesObject } from 'src/scope/types';

import { getSessionScopes } from '../adapters/caip-permission-adapter-session-scopes';
import type { Caip25CaveatValue } from '../caip25Permission';
import {
Caip25CaveatType,
Caip25EndowmentPermissionName,
} from '../caip25Permission';
import { mergeScopes } from '../scope/transform';
import type { ScopesObject } from '../scope/types';

/**
* Handler for the `wallet_getSession` RPC method.
Expand All @@ -21,7 +21,7 @@ import type { ScopesObject } from '../scope/types';
*/
async function walletGetSessionHandler(
request: JsonRpcRequest & { origin: string },
response: JsonRpcSuccess<{ sessionScopes: ScopesObject }>,
response: JsonRpcSuccess<{ sessionScopes: NormalizedScopesObject }>,
_next: () => void,
end: () => void,
hooks: {
Expand Down Expand Up @@ -49,10 +49,7 @@ async function walletGetSessionHandler(
}

response.result = {
sessionScopes: mergeScopes(
caveat.value.requiredScopes,
caveat.value.optionalScopes,
),
sessionScopes: getSessionScopes(caveat.value),
};
return end();
}
Expand Down
Loading

0 comments on commit 0d167a3

Please sign in to comment.