Skip to content

Commit

Permalink
Add tests for KeyringController edge cases (#3847)
Browse files Browse the repository at this point in the history
## Explanation

<!--
Thanks for your contribution! Take a moment to answer these questions so
that reviewers have the information they need to properly understand
your changes:

* What is the current state of things and why does it need to change?
* What is the solution your changes offer and how does it work?
* Are there any changes whose purpose might not obvious to those
unfamiliar with the domain?
* If your primary goal was to update one package but you found you had
to update another one along the way, why did you do so?
* If you had to upgrade a dependency, why did you do so?
-->

This PR adds additional tests for edge cases, useful for #3830.
Some `istanbul ignore if` statements are also being removed

## 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?

For example:

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

* Fixes #3767 
* See #3830 

## 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".
-->

No functional changes

## 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
  • Loading branch information
mikesposito authored Jan 26, 2024
1 parent c8ea3ea commit 79ebb87
Show file tree
Hide file tree
Showing 2 changed files with 280 additions and 6 deletions.
282 changes: 280 additions & 2 deletions packages/keyring-controller/src/KeyringController.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,38 @@ describe('KeyringController', () => {
sinon.restore();
});

describe('constructor', () => {
it('should use the default encryptor if none is provided', async () => {
expect(
() =>
new KeyringController({
messenger: buildKeyringControllerMessenger(),
cacheEncryptionKey: true,
updateIdentities: jest.fn(),
setAccountLabel: jest.fn(),
syncIdentities: jest.fn(),
setSelectedAddress: jest.fn(),
}),
).not.toThrow();
});

it('should throw error if cacheEncryptionKey is true and encryptor does not support key export', () => {
expect(
() =>
// @ts-expect-error testing an invalid encryptor
new KeyringController({
messenger: buildKeyringControllerMessenger(),
cacheEncryptionKey: true,
encryptor: { encrypt: jest.fn(), decrypt: jest.fn() },
updateIdentities: jest.fn(),
setAccountLabel: jest.fn(),
syncIdentities: jest.fn(),
setSelectedAddress: jest.fn(),
}),
).toThrow(KeyringControllerError.UnsupportedEncryptionKeyExport);
});
});

describe('addNewAccount', () => {
describe('when accountCount is not provided', () => {
it('should add new account', async () => {
Expand Down Expand Up @@ -157,6 +189,17 @@ describe('KeyringController', () => {
});
});
});

it('should throw error with no HD keyring', async () => {
await withController(
{ skipVaultCreation: true },
async ({ controller }) => {
await expect(controller.addNewAccount()).rejects.toThrow(
'No HD keyring found',
);
},
);
});
});

describe('addNewAccountForKeyring', () => {
Expand Down Expand Up @@ -310,6 +353,17 @@ describe('KeyringController', () => {
},
);
});

it('should throw error with no HD keyring', async () => {
await withController(
{ skipVaultCreation: true },
async ({ controller }) => {
await expect(controller.addNewAccountWithoutUpdate()).rejects.toThrow(
'No HD keyring found',
);
},
);
});
});

describe('addNewKeyring', () => {
Expand Down Expand Up @@ -459,6 +513,20 @@ describe('KeyringController', () => {
expect(controller.state.vault).toBeDefined();
});
});

it('should throw error if password is of wrong type', async () => {
await withController(
{ skipVaultCreation: true },
async ({ controller }) => {
await expect(
controller.createNewVaultAndKeychain(
// @ts-expect-error invalid password
123,
),
).rejects.toThrow(KeyringControllerError.WrongPasswordType);
},
);
});
});

describe('when there is an existing vault', () => {
Expand Down Expand Up @@ -784,6 +852,21 @@ describe('KeyringController', () => {
);
});
});

it('should throw an error if there are no keyrings', async () => {
await withController(
{ skipVaultCreation: true },
async ({ controller }) => {
await expect(
controller.getKeyringForAccount(
'0x51253087e6f8358b5f10c0a94315d69db3357859',
),
).rejects.toThrow(
'KeyringController - No keyring found. Error info: There are no keyrings',
);
},
);
});
});
});

Expand Down Expand Up @@ -826,6 +909,16 @@ describe('KeyringController', () => {
expect(controller.state.keyrings[0].accounts[1]).toBe(addedAccount);
});
});

it('should throw error when locked', async () => {
await withController(async ({ controller }) => {
await controller.setLocked();

await expect(controller.persistAllKeyrings()).rejects.toThrow(
KeyringControllerError.MissingCredentials,
);
});
});
});

describe('importAccountWithStrategy', () => {
Expand Down Expand Up @@ -936,6 +1029,23 @@ describe('KeyringController', () => {
expect(preferences.setSelectedAddress.called).toBe(false);
});
});

it('should throw error when importing a duplicate account', async () => {
await withController(async ({ controller }) => {
const somePassword = 'holachao123';
await controller.importAccountWithStrategy(
AccountImportStrategy.json,
[input, somePassword],
);

await expect(
controller.importAccountWithStrategy(AccountImportStrategy.json, [
input,
somePassword,
]),
).rejects.toThrow(KeyringControllerError.DuplicatedAccount);
});
});
});

describe('when wrong data is provided', () => {
Expand Down Expand Up @@ -1824,6 +1934,68 @@ describe('KeyringController', () => {
);
});

it('should unlock also with unsupported keyrings', async () => {
await withController(
{ cacheEncryptionKey },
async ({ controller, encryptor }) => {
await controller.setLocked();
jest.spyOn(encryptor, 'decrypt').mockResolvedValueOnce([
{
type: 'UnsupportedKeyring',
data: '0x1234',
},
]);

await controller.submitPassword(password);

expect(controller.state.isUnlocked).toBe(true);
},
);
});

it('should throw error if vault unlocked has an unexpected shape', async () => {
await withController(
{ cacheEncryptionKey },
async ({ controller, encryptor }) => {
await controller.setLocked();
jest.spyOn(encryptor, 'decrypt').mockResolvedValueOnce([
{
foo: 'bar',
},
]);

await expect(controller.submitPassword(password)).rejects.toThrow(
KeyringControllerError.VaultDataError,
);
},
);
});

it('should throw error if vault is missing', async () => {
await withController(
{ skipVaultCreation: true },
async ({ controller }) => {
await expect(controller.submitPassword(password)).rejects.toThrow(
KeyringControllerError.VaultError,
);
},
);
});

!cacheEncryptionKey &&
it('should throw error if password is of wrong type', async () => {
await withController(
{ cacheEncryptionKey },
async ({ controller }) => {
await expect(
// @ts-expect-error we are testing the case of a user using
// the wrong password type
controller.submitPassword(12341234),
).rejects.toThrow(KeyringControllerError.WrongPasswordType);
},
);
});

cacheEncryptionKey &&
it('should set encryptionKey and encryptionSalt in state', async () => {
withController({ cacheEncryptionKey }, async ({ controller }) => {
Expand All @@ -1849,6 +2021,75 @@ describe('KeyringController', () => {
},
);
});

it('should unlock also with unsupported keyrings', async () => {
await withController(
{ cacheEncryptionKey: true },
async ({ controller, initialState, encryptor }) => {
await controller.setLocked();
jest.spyOn(encryptor, 'decrypt').mockResolvedValueOnce([
{
type: 'UnsupportedKeyring',
data: '0x1234',
},
]);

await controller.submitEncryptionKey(
MOCK_ENCRYPTION_KEY,
initialState.encryptionSalt as string,
);

expect(controller.state.isUnlocked).toBe(true);
},
);
});

it('should throw error if vault unlocked has an unexpected shape', async () => {
await withController(
{ cacheEncryptionKey: true },
async ({ controller, initialState, encryptor }) => {
jest.spyOn(encryptor, 'decrypt').mockResolvedValueOnce([
{
foo: 'bar',
},
]);

await expect(
controller.submitEncryptionKey(
MOCK_ENCRYPTION_KEY,
initialState.encryptionSalt as string,
),
).rejects.toThrow(KeyringControllerError.VaultDataError);
},
);
});

it('should throw error if encryptionSalt is different from the one in the vault', async () => {
await withController(
{ cacheEncryptionKey: true },
async ({ controller }) => {
await expect(
controller.submitEncryptionKey(MOCK_ENCRYPTION_KEY, '0x1234'),
).rejects.toThrow(KeyringControllerError.ExpiredCredentials);
},
);
});

it('should throw error if encryptionKey is of an unexpected type', async () => {
await withController(
{ cacheEncryptionKey: true },
async ({ controller, initialState }) => {
await expect(
controller.submitEncryptionKey(
// @ts-expect-error we are testing the case of a user using
// the wrong encryptionKey type
12341234,
initialState.encryptionSalt as string,
),
).rejects.toThrow(KeyringControllerError.WrongPasswordType);
},
);
});
});

describe('verifySeedPhrase', () => {
Expand Down Expand Up @@ -1879,6 +2120,17 @@ describe('KeyringController', () => {
);
});
});

it('should throw error with no HD keyring', async () => {
await withController(
{ skipVaultCreation: true },
async ({ controller }) => {
await expect(controller.verifySeedPhrase()).rejects.toThrow(
'No HD keyring found',
);
},
);
});
});

describe('verifyPassword', () => {
Expand All @@ -1890,6 +2142,17 @@ describe('KeyringController', () => {
}).not.toThrow();
});
});

it('should throw error if vault is missing', async () => {
await withController(
{ skipVaultCreation: true },
async ({ controller }) => {
await expect(controller.verifyPassword(password)).rejects.toThrow(
KeyringControllerError.VaultError,
);
},
);
});
});

describe('when wrong password is provided', () => {
Expand All @@ -1904,6 +2167,17 @@ describe('KeyringController', () => {
);
});
});

it('should throw error if vault is missing', async () => {
await withController(
{ skipVaultCreation: true },
async ({ controller }) => {
await expect(controller.verifyPassword('123')).rejects.toThrow(
KeyringControllerError.VaultError,
);
},
);
});
});
});

Expand Down Expand Up @@ -2832,7 +3106,9 @@ type WithControllerCallback<ReturnValue> = ({
messenger: KeyringControllerMessenger;
}) => Promise<ReturnValue> | ReturnValue;

type WithControllerOptions = Partial<KeyringControllerOptions>;
type WithControllerOptions = Partial<KeyringControllerOptions> & {
skipVaultCreation?: boolean;
};

type WithControllerArgs<ReturnValue> =
| [WithControllerCallback<ReturnValue>]
Expand Down Expand Up @@ -2910,7 +3186,9 @@ async function withController<ReturnValue>(
...preferences,
...rest,
});
await controller.createNewVaultAndKeychain(password);
if (!rest.skipVaultCreation) {
await controller.createNewVaultAndKeychain(password);
}
return await fn({
controller,
preferences,
Expand Down
Loading

0 comments on commit 79ebb87

Please sign in to comment.