Skip to content
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
14 changes: 14 additions & 0 deletions packages/keyring-eth-money-mpc/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,24 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Added

- Add a read-only mode for clients without MFA ([#722](https://github.com/MetaMask/accounts/pull/722))
- With `isMfaAvailable: false`, `setup` reads the address of the active key from `check-key-share` with a profile token without 2FA, and stores only the address.
- Signing, `rotateKeyShares`, `checkKeyShare` and `syncKeyShare` throw before any network call.
- A read-only keyring keeps a full persisted state, but does not sign with it.
- A read/write keyring that loads an address-only state imports the key share on `setup`, and throws if the imported address differs.
- The V2 `MpcMoneyKeyring` returns read-only accounts without methods.
- Add `isReadOnly` to the `MpcMoneyKeyring` contract.
- `CheckKeyShareResult` includes the optional `publicKey` of the latest share.

### Changed

- **BREAKING:** Require the `isMfaAvailable` constructor option ([#722](https://github.com/MetaMask/accounts/pull/722))
- Pass `true` to keep the current behavior.
- Call `check-key-share` with `GET` instead of `POST` ([#717](https://github.com/MetaMask/accounts/pull/717))
- Requires an MPC backend that serves `GET /v1/check-key-share`.
- The V2 `createAccounts` always runs the inner `setup`, which is a no-op once the keyring is set up ([#722](https://github.com/MetaMask/accounts/pull/722))

## [0.4.0]

Expand Down
15 changes: 15 additions & 0 deletions packages/keyring-eth-money-mpc/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,21 @@ The keyring first calls `/sign` with a profile token without 2FA, and sends the

Key generation, import, share rotation, share sync, and transaction signing always use a 2FA token.

## Read-only mode

Pass `isMfaAvailable` when constructing the keyring. Derive it from the client's MFA feature flag.

With `isMfaAvailable: false`, the keyring never requests a 2FA token:

- `setup` calls `check-key-share` with a profile token without 2FA. It stores only the address derived from the returned `publicKey`.
- `setup` throws when the profile has no active key.
- Signing, `rotateKeyShares`, `checkKeyShare`, and `syncKeyShare` throw.
- The V2 adapter returns the account without methods.

A read-only keyring that loads a full persisted state keeps it, but doesn't sign with it.

When MFA becomes available, construct the keyring with `isMfaAvailable: true` and call `setup` (or the V2 `createAccounts`). The keyring imports the key share with a 2FA token. It throws if the imported address differs from the stored one.

## Device-share backups

Provide `getPrimaryMnemonic: () => Promise<number[]>` when constructing the keyring.
Expand Down
32 changes: 32 additions & 0 deletions packages/keyring-eth-money-mpc/src/cloud.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -462,6 +462,38 @@ describe('cloud helpers', () => {
);
});

it('returns the latest share public key with the epochs', async () => {
okJson({
latestShareEpoch: 1,
latestBackupEpoch: 1,
activeEpoch: 1,
publicKey: '0x010203',
});

expect(
await checkKeyShare({
baseURL: 'https://cloud.example',
token: 'token-1',
}),
).toStrictEqual({
latestShareEpoch: 1,
latestBackupEpoch: 1,
activeEpoch: 1,
publicKey: '0x010203',
});
});

it('rejects a public key that is not 0x-prefixed hex', async () => {
okJson({ activeEpoch: 1, publicKey: '010203' });

await expect(
checkKeyShare({
baseURL: 'https://cloud.example',
token: 'token-1',
}),
).rejects.toThrow(/^Failed to check key share: bad response format$/u);
});

it('rejects key share epoch metadata with the wrong shape', async () => {
okJson({ activeEpoch: '1' });

Expand Down
10 changes: 8 additions & 2 deletions packages/keyring-eth-money-mpc/src/cloud.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
string,
type,
} from '@metamask/superstruct';
import { base64ToBytes, bytesToBase64 } from '@metamask/utils';
import { base64ToBytes, bytesToBase64, StrictHexStruct } from '@metamask/utils';

import { MFA_REQUIRED_CODE } from './types.js';
import type { MoneyAccountSignatureRequest } from './types.js';
Expand All @@ -31,6 +31,11 @@ const CheckKeyShareResponseStruct = type({
latestShareEpoch: exactOptional(shareEpochStruct),
latestBackupEpoch: exactOptional(shareEpochStruct),
activeEpoch: exactOptional(shareEpochStruct),
/**
* Public key of the latest share: the pending share when one exists,
* otherwise the active share.
*/
publicKey: exactOptional(StrictHexStruct),
});

export type CheckKeyShareResult = Infer<typeof CheckKeyShareResponseStruct>;
Expand Down Expand Up @@ -400,7 +405,8 @@ export async function storeKeyShareBackup(opts: {
}

/**
* Return the latest share/backup epochs and the active epoch from the backend.
* Return the latest share/backup epochs, the active epoch, and the latest
* share public key from the backend.
*
* @param opts - Request options.
* @param opts.baseURL - MPC backend base URL.
Expand Down
226 changes: 226 additions & 0 deletions packages/keyring-eth-money-mpc/src/mpc-money-keyring.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -194,8 +194,10 @@ const makeRootSession = (statusPayload = 'data persisted') => {
const makeKeyring = (
getProfileToken = jest.fn().mockResolvedValue('token'),
getPrimaryMnemonic = jest.fn().mockResolvedValue(mockMnemonicBytes),
isMfaAvailable = true,
) =>
new MpcMoneyKeyring({
isMfaAvailable,
cl24Lib: {} as never,
dkls23Lib: {} as never,
cloudURL: 'https://cloud.example',
Expand Down Expand Up @@ -267,6 +269,7 @@ describe('MpcMoneyKeyring', () => {
const webSocket = { send: jest.fn() };

const keyring = new MpcMoneyKeyring({
isMfaAvailable: true,
cl24Lib: {} as never,
dkls23Lib: {} as never,
cloudURL: 'https://cloud.example',
Expand Down Expand Up @@ -1325,4 +1328,227 @@ describe('MpcMoneyKeyring', () => {
`getAppKeyAddress(${mockDerivedAddress}, example.com): not implemented`,
);
});

describe('address-only state', () => {
const otherAddress = '0x2222222222222222222222222222222222222222' as Hex;

it('round-trips an address-only state', async () => {
const keyring = makeKeyring();

await keyring.deserialize({ address: mockDerivedAddress });

expect(await keyring.serialize()).toStrictEqual({
address: mockDerivedAddress,
});
expect(await keyring.getAccounts()).toStrictEqual([mockDerivedAddress]);
expect(await keyring.addAccounts()).toStrictEqual([mockDerivedAddress]);
});

it('rejects an address-only state with an invalid address', async () => {
const keyring = makeKeyring();

await expect(keyring.deserialize({ address: '0x1234' })).rejects.toThrow(
'Invalid state',
);
});

it('requires setup before signing', async () => {
const getProfileToken = jest.fn().mockResolvedValue('token');
const keyring = makeKeyring(getProfileToken);
await keyring.deserialize({ address: mockDerivedAddress });

await expect(
keyring.signPersonalMessage(mockDerivedAddress, '0x68656c6c6f'),
).rejects.toThrow('MpcMoneyKeyring: no key share, run setup first');
expect(getProfileToken).not.toHaveBeenCalled();
expect(mockStartSign).not.toHaveBeenCalled();
});

it('imports the key share for the stored address on setup', async () => {
const getProfileToken = jest.fn().mockResolvedValue('token');
const keyring = makeKeyring(getProfileToken);
await keyring.deserialize({ address: mockDerivedAddress });
mockCreateIdentity.mockResolvedValueOnce({ partyId: 'imported-user' });
mockThresholdKeyFromJson.mockReturnValueOnce(makeThresholdKey());

await keyring.setup();

expect(getProfileToken).toHaveBeenCalledWith({ twoFactor: true });
expect(mockCheckKeyShare).not.toHaveBeenCalled();
expect(mockStartCreateKey).not.toHaveBeenCalled();
expect(mockRegisterClient).toHaveBeenCalledWith({
baseURL: 'https://cloud.example',
token: 'token',
clientNetId: 'imported-user',
});
expect(await keyring.getAccounts()).toStrictEqual([mockDerivedAddress]);
expect(await keyring.serialize()).toStrictEqual({
netCreds: { partyId: 'imported-user' },
keyShare: makeThresholdKey(),
serverNetId: 'cloud-user',
shareEpoch: mockShareEpoch,
tssSetup: null,
});
});

it('rejects an imported key share for another address', async () => {
const keyring = makeKeyring();
await keyring.deserialize({ address: otherAddress });
mockCreateIdentity.mockResolvedValueOnce({ partyId: 'imported-user' });
mockThresholdKeyFromJson.mockReturnValueOnce(makeThresholdKey());

await expect(keyring.setup()).rejects.toThrow(
'MpcMoneyKeyring: imported key share address does not match expected account',
);
expect(mockRegisterClient).not.toHaveBeenCalled();
expect(await keyring.serialize()).toStrictEqual({
address: otherAddress,
});
});
});

describe('read-only mode', () => {
const mockPublicKey = '0x04010203' as Hex;

const makeReadOnlyKeyring = (
getProfileToken = jest.fn().mockResolvedValue('token'),
getPrimaryMnemonic = jest.fn().mockResolvedValue(mockMnemonicBytes),
) => makeKeyring(getProfileToken, getPrimaryMnemonic, false);

it('reports whether the keyring is read-only', () => {
expect(makeReadOnlyKeyring().isReadOnly).toBe(true);
expect(makeKeyring().isReadOnly).toBe(false);
});

it('fetches only the address on setup', async () => {
const getProfileToken = jest.fn().mockResolvedValue('token');
const getPrimaryMnemonic = jest.fn();
const keyring = makeReadOnlyKeyring(getProfileToken, getPrimaryMnemonic);
mockCheckKeyShare.mockResolvedValueOnce({
latestShareEpoch: mockShareEpoch,
latestBackupEpoch: mockShareEpoch,
activeEpoch: mockShareEpoch,
publicKey: mockPublicKey,
});

await keyring.setup();

expect(getProfileToken).toHaveBeenCalledTimes(1);
expect(getProfileToken).toHaveBeenCalledWith();
expect(mockCheckKeyShare).toHaveBeenCalledWith({
baseURL: 'https://cloud.example',
token: 'token',
});
expect(
jest.requireMock('./util').publicKeyToAddressHex,
).toHaveBeenCalledWith(new Uint8Array([4, 1, 2, 3]));
expect(getPrimaryMnemonic).not.toHaveBeenCalled();
expect(mockCreateIdentity).not.toHaveBeenCalled();
expect(mockGetNetId).not.toHaveBeenCalled();
expect(mockStartCreateKey).not.toHaveBeenCalled();
expect(mockLoadKeyShareBackup).not.toHaveBeenCalled();
expect(await keyring.getAccounts()).toStrictEqual([mockDerivedAddress]);
expect(await keyring.serialize()).toStrictEqual({
address: mockDerivedAddress,
});
});

it.each([
['no key', {}],
[
'only a pending share',
{ latestShareEpoch: 1, latestBackupEpoch: 1, publicKey: mockPublicKey },
],
[
'no public key',
{ latestShareEpoch: 1, latestBackupEpoch: 1, activeEpoch: 1 },
],
])('throws on setup when the backend has %s', async (_name, check) => {
const keyring = makeReadOnlyKeyring();
mockCheckKeyShare.mockResolvedValueOnce(check);

await expect(keyring.setup()).rejects.toThrow(
'MpcMoneyKeyring: no MPC key for this profile',
);
expect(await keyring.serialize()).toStrictEqual({});
expect(await keyring.getAccounts()).toStrictEqual([]);
});

it.each([
['an address-only state', { address: mockDerivedAddress }],
['a full state', makeSerializedState()],
])('setup is a no-op with %s', async (_name, state) => {
const keyring = makeReadOnlyKeyring();
await keyring.deserialize(state as unknown as Json);

await keyring.setup();

expect(mockCheckKeyShare).not.toHaveBeenCalled();
expect(mockLoadKeyShareBackup).not.toHaveBeenCalled();
expect(await keyring.serialize()).toStrictEqual(state);
});

it('keeps a full state without signing with it', async () => {
const keyring = makeReadOnlyKeyring();
const state = makeSerializedState();
await deserializeState(keyring, state);

expect(await keyring.getAccounts()).toStrictEqual([mockDerivedAddress]);
await expect(
keyring.signPersonalMessage(mockDerivedAddress, '0x68656c6c6f'),
).rejects.toThrow('MpcMoneyKeyring: read-only, MFA is not available');
expect(await keyring.serialize()).toStrictEqual(state);
});

it.each([
[
'signPersonalMessage',
async (keyring: MpcMoneyKeyring) =>
keyring.signPersonalMessage(mockDerivedAddress, '0x68656c6c6f'),
],
[
'signTypedData',
async (keyring: MpcMoneyKeyring) =>
keyring.signTypedData(
mockDerivedAddress,
[{ type: 'string', name: 'message', value: 'hello' }],
{},
),
],
[
'signEip7702Authorization',
async (keyring: MpcMoneyKeyring) =>
keyring.signEip7702Authorization(mockDerivedAddress, [
1,
'0x1234567890abcdef1234567890abcdef12345678',
1,
]),
],
[
'rotateKeyShares',
async (keyring: MpcMoneyKeyring) => keyring.rotateKeyShares(),
],
[
'checkKeyShare',
async (keyring: MpcMoneyKeyring) => keyring.checkKeyShare(),
],
[
'syncKeyShare',
async (keyring: MpcMoneyKeyring) => keyring.syncKeyShare(),
],
])('blocks %s before any network call', async (_name, operation) => {
const getProfileToken = jest.fn().mockResolvedValue('token');
const keyring = makeReadOnlyKeyring(getProfileToken);
await keyring.deserialize({ address: mockDerivedAddress });

await expect(operation(keyring)).rejects.toThrow(
'MpcMoneyKeyring: read-only, MFA is not available',
);
expect(getProfileToken).not.toHaveBeenCalled();
expect(mockCheckKeyShare).not.toHaveBeenCalled();
expect(mockStartSign).not.toHaveBeenCalled();
expect(mockStartRotateKeyShares).not.toHaveBeenCalled();
expect(mockLoadKeyShareBackup).not.toHaveBeenCalled();
});
});
});
Loading
Loading