Skip to content

Commit

Permalink
fix: phishing detector validation to drop invalid configs from detect…
Browse files Browse the repository at this point in the history
…or (#4820)

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

We need to ensure that only valid configurations are processed by the
phishing detector. Currently, if one configuration fails validation, it
causes all configurations to fail, preventing the detector from
receiving updates.

The validation process needs to be updated so that invalid
configurations are filtered out, while valid configurations are still
passed to the detector.

**Solution:**

The `processConfigs` function has been introduced to:

- Filter out invalid configurations using the `validateConfig` function.
- Log any validation errors encountered during this filtering process.

This ensures that any configuration passed to the phishing detector is
both valid and properly formatted. Invalid configurations are logged and
discarded.

## 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/phishing-controller`

- **CHANGED**: `processConfigs` function to filter and validate phishing
detector configurations, discarding invalid ones.
- **CHANGED**: Instead of throwing an error and failing to update the
`detector` when validation failed on any one config, invalid
configurations are now logged via console.error and skipped.


## Checklist

- [x] I've updated the test suite for new or updated code as appropriate
- [x] I've updated documentation (JSDoc, Markdown, etc.) for new or
updated code as appropriate
- [x] I've highlighted breaking changes using the "BREAKING" category
above as appropriate
- [x] I've prepared draft pull requests for clients and consumer
packages to resolve any breaking changes
  • Loading branch information
AugmentedMode authored Oct 24, 2024
1 parent 63c38b7 commit a974371
Show file tree
Hide file tree
Showing 3 changed files with 292 additions and 73 deletions.
199 changes: 142 additions & 57 deletions packages/phishing-controller/src/PhishingDetector.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ describe('PhishingDetector', () => {
);
});

[
it.each([
undefined,
null,
true,
Expand All @@ -88,46 +88,116 @@ describe('PhishingDetector', () => {
return { name: 'test', version: 1 };
},
{},
].forEach((mockInvalidName) => {
it('throws an error when config name is invalid', async () => {
await expect(
withPhishingDetector(
[
{
allowlist: [],
blocklist: ['blocked-by-first.com'],
fuzzylist: [],
// @ts-expect-error testing invalid input
name: mockInvalidName,
tolerance: 2,
version: 1,
},
],
async () => mockInvalidName,
),
).rejects.toThrow("Invalid config parameter: 'name'");
});
])('logs an error when config name is %p', async (mockInvalidName) => {
// Mock console.error to track error logs without cluttering test output
const consoleErrorMock = jest.spyOn(console, 'error');

let detector;

await withPhishingDetector(
[
{
allowlist: [],
blocklist: ['blocked-by-first.com'],
fuzzylist: [],
// @ts-expect-error Testing invalid input
name: mockInvalidName,
tolerance: 2,
version: 1,
},
],
async ({ detector: d }) => {
detector = d;
},
);

// Ensure the detector is still defined
expect(detector).toBeDefined();

// Check that console.error was called (you can further specify the error if needed)
expect(console.error).toHaveBeenCalled();

// Restore the original console.error implementation
consoleErrorMock.mockRestore();
});

it('throws an error when tolerance is provided without fuzzylist', async () => {
await expect(
withPhishingDetector(
[
// @ts-expect-error testing invalid input
{
allowlist: [],
blocklist: [],
name: 'first',
tolerance: 2,
version: 1,
},
],
async () => null,
),
).rejects.toThrow('Fuzzylist tolerance provided without fuzzylist');
it('drops the invalid config and retains the valid config', async () => {
const consoleErrorMock = jest.spyOn(console, 'error');

let detector: PhishingDetector | undefined;

await withPhishingDetector(
[
// Invalid config
{
allowlist: [],
blocklist: ['blocked-by-first.com'],
fuzzylist: [],
name: undefined,
tolerance: 2,
version: 1,
},
// Valid config
{
allowlist: [],
blocklist: ['blocked-by-second.com'],
fuzzylist: [],
name: 'MetaMask',
tolerance: 2,
version: 1,
},
],
async ({ detector: d }) => {
detector = d;
},
);

expect(detector).toBeDefined();

const result = detector?.check('https://blocked-by-second.com');

expect(result).toBeDefined();
expect(result?.type).toBe('blocklist');

const resultInvalid = detector?.check('https://blocked-by-first.com');

expect(resultInvalid).toBeDefined();
expect(resultInvalid?.type).toBe('all');

expect(console.error).toHaveBeenCalled();

consoleErrorMock.mockRestore();
});

[
it('logs an error when tolerance is provided without fuzzylist', async () => {
const consoleErrorMock = jest.spyOn(console, 'error');

let detector;

await withPhishingDetector(
[
// @ts-expect-error testing invalid input
{
allowlist: [],
blocklist: [],
name: 'first',
tolerance: 2,
version: 1,
},
],
async ({ detector: d }) => {
detector = d;
},
);

expect(detector).toBeDefined();

expect(console.error).toHaveBeenCalledWith(expect.any(Error));

consoleErrorMock.mockRestore();
});

it.each([
undefined,
null,
true,
Expand All @@ -137,26 +207,41 @@ describe('PhishingDetector', () => {
return { name: 'test', version: 1 };
},
{},
].forEach((mockInvalidVersion) => {
it('throws an error when config version is invalid', async () => {
await expect(
withPhishingDetector(
[
{
allowlist: [],
blocklist: ['blocked-by-first.com'],
fuzzylist: [],
name: 'first',
tolerance: 2,
// @ts-expect-error testing invalid input
version: mockInvalidVersion,
},
],
async () => null,
),
).rejects.toThrow("Invalid config parameter: 'version'");
});
});
])(
'logs an error when config version is %p',
async (mockInvalidVersion) => {
// Mock console.error to track error logs without cluttering test output
const consoleErrorMock = jest.spyOn(console, 'error');

let detector;

await withPhishingDetector(
[
{
allowlist: [],
blocklist: ['blocked-by-first.com'],
fuzzylist: [],
name: 'first',
tolerance: 2,
// @ts-expect-error Testing invalid input
version: mockInvalidVersion,
},
],
async ({ detector: d }) => {
detector = d;
},
);

// Ensure the detector is still defined
expect(detector).toBeDefined();

// Check that console.error was called with an error
expect(console.error).toHaveBeenCalledWith(expect.any(Error));

// Restore the original console.error implementation
consoleErrorMock.mockRestore();
},
);
});

describe('with legacy config', () => {
Expand Down
138 changes: 130 additions & 8 deletions packages/phishing-controller/src/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
getHostnameFromUrl,
matchPartsAgainstList,
processConfigs,
// processConfigs,
processDomainList,
roundToNearestMinute,
sha256Hash,
Expand Down Expand Up @@ -287,30 +288,151 @@ describe('domainToParts', () => {
});

describe('processConfigs', () => {
it('correctly converts a list of configs to a list of processed configs', () => {
let consoleErrorMock: jest.SpyInstance;

beforeEach(() => {
consoleErrorMock = jest.spyOn(console, 'error');
});

afterEach(() => {
consoleErrorMock.mockRestore();
});

it('correctly processes a list of valid configs', () => {
const configs = [
{
allowlist: ['example.com'],
blocklist: ['sub.example.com'],
fuzzylist: ['fuzzy.example.com'],
tolerance: 2,
version: 1,
name: 'MetaMask',
},
];

const result = processConfigs(configs);

expect(result).toStrictEqual([
expect(result).toHaveLength(1);
expect(result[0].name).toBe('MetaMask');

expect(console.error).not.toHaveBeenCalled();
});

it('filters out invalid configs and logs errors', () => {
const configs = [
{
allowlist: [['com', 'example']],
blocklist: [['com', 'example', 'sub']],
fuzzylist: [['com', 'example', 'fuzzy']],
allowlist: ['example.com'],
blocklist: ['sub.example.com'],
fuzzylist: [],
tolerance: 2,
version: 1,
name: 'MetaMask',
},
]);
{
allowlist: [],
version: 1,
name: undefined,
},
];

const result = processConfigs(configs);

expect(result).toHaveLength(1);
expect(result[0].name).toBe('MetaMask');

expect(console.error).toHaveBeenCalledTimes(1);
});

it('returns an empty array when called with no arguments', () => {
const result = processConfigs();
expect(result).toStrictEqual([]);
});

it('filters out invalid configs and logs errors with multiple configs', () => {
const configs = [
{
allowlist: ['example.com'],
blocklist: ['sub.example.com'],
fuzzylist: [],
tolerance: 2,
version: 1,
name: 'MetaMask',
},
{
allowlist: [],
version: 1,
name: undefined,
},
{
allowlist: ['example.com'],
blocklist: ['sub.example.com'],
fuzzylist: [],
tolerance: 2,
version: 1,
name: 'name',
},
{
allowlist: [],
version: 1,
name: '',
},
];

const result = processConfigs(configs);

expect(result).toHaveLength(2);
expect(result[0].name).toBe('MetaMask');
expect(result[1].name).toBe('name');

expect(console.error).toHaveBeenCalledTimes(2);
});

it('can be called with no arguments', () => {
expect(processConfigs()).toStrictEqual([]);
it('returns an empty array when all configs are invalid', () => {
const configs = [
{
allowlist: [],
version: 1,
name: undefined,
},
{
blocklist: [],
fuzzylist: [],
tolerance: 2,
version: null,
name: '',
},
];

// @ts-expect-error testing invalid input
const result = processConfigs(configs);

expect(result).toStrictEqual([]);

expect(console.error).toHaveBeenCalledTimes(2);
});

it('logs errors for invalid tolerance or version types', () => {
const configs = [
{
allowlist: ['example.com'],
blocklist: ['sub.example.com'],
tolerance: 'invalid',
version: 1,
},
{
allowlist: ['example.com'],
blocklist: ['sub.example.com'],
tolerance: 2,
version: {},
},
];

// @ts-expect-error testing invalid input
const result = processConfigs(configs);

expect(result).toStrictEqual([]);

expect(console.error).toHaveBeenCalledTimes(2);
});
});

Expand Down
Loading

0 comments on commit a974371

Please sign in to comment.