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

## [Unreleased]

### Added

- Support path-based phishing lists (`blocklistPaths`, `whitelistPaths`) and path-aware URL scanning for shared gateways (for example IPFS gateways and `sites.google.com`) via `getPhishingDetectionScanUrlParam`, `isPhishingDetectionPathBasedHostname`, and `PHISHING_DETECTION_PATH_BASED_ROOT_DOMAINS` ([#8662](https://github.com/MetaMask/core/pull/8662))

### Changed

- Bump `@metamask/messenger` from `^1.0.0` to `^1.1.1` ([#8364](https://github.com/MetaMask/core/pull/8364), [#8373](https://github.com/MetaMask/core/pull/8373))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,9 @@ export type PhishingControllerBypassAction = {
};

/**
* Scan a URL for phishing. It will only scan the hostname of the URL. It also only supports
* web URLs.
* Scan a URL for phishing. For most hosts only the hostname is sent to the API; for known
* shared gateways the pathname is included (see `PHISHING_DETECTION_PATH_BASED_ROOT_DOMAINS`).
* Only supports web URLs (`http:` / `https:`).
*
* @param url - The URL to scan.
* @returns The phishing detection scan result.
Expand Down
52 changes: 51 additions & 1 deletion packages/phishing-controller/src/PhishingController.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2813,7 +2813,7 @@ describe('PhishingController', () => {
it('should return a PhishingDetectionScanResult with a fetchError on timeout', async () => {
const scope = nock(PHISHING_DETECTION_BASE_URL)
.get(`/${PHISHING_DETECTION_SCAN_ENDPOINT}`)
.query({ url: testUrl })
.query({ url: 'example.com' })
.delayConnection(10000)
.reply(200, {});

Expand Down Expand Up @@ -2935,6 +2935,56 @@ describe('PhishingController', () => {
expect(response).toMatchObject(mockResponse);
expect(scope.isDone()).toBe(true);
});

it('should send hostname and path for path-based gateways and cache per path', async () => {
const urlA = 'https://ipfs.io/ipfs/QmAAA';
const urlB = 'https://ipfs.io/ipfs/QmBBB';

const scopeA = nock(PHISHING_DETECTION_BASE_URL)
.get(`/${PHISHING_DETECTION_SCAN_ENDPOINT}`)
.query({ url: 'ipfs.io/ipfs/QmAAA' })
.reply(200, {
recommendedAction: RecommendedAction.Warn,
});

const scopeB = nock(PHISHING_DETECTION_BASE_URL)
.get(`/${PHISHING_DETECTION_SCAN_ENDPOINT}`)
.query({ url: 'ipfs.io/ipfs/QmBBB' })
.reply(200, {
recommendedAction: RecommendedAction.Block,
});

const fetchSpy = jest.spyOn(global, 'fetch');

const resultA1 = await rootMessenger.call(
'PhishingController:scanUrl',
urlA,
);
const resultB = await rootMessenger.call(
'PhishingController:scanUrl',
urlB,
);
const resultA2 = await rootMessenger.call(
'PhishingController:scanUrl',
urlA,
);

expect(resultA1).toMatchObject({
hostname: 'ipfs.io',
recommendedAction: RecommendedAction.Warn,
});
expect(resultB).toMatchObject({
hostname: 'ipfs.io',
recommendedAction: RecommendedAction.Block,
});
expect(resultA2).toStrictEqual(resultA1);

expect(scopeA.isDone()).toBe(true);
expect(scopeB.isDone()).toBe(true);
expect(fetchSpy).toHaveBeenCalledTimes(2);

fetchSpy.mockRestore();
});
});

describe('bulkScanUrls', () => {
Expand Down
18 changes: 11 additions & 7 deletions packages/phishing-controller/src/PhishingController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ import {
getHostnameFromUrl,
roundToNearestMinute,
getHostnameFromWebUrl,
getPhishingDetectionScanUrlParam,
buildCacheKey,
splitCacheHits,
resolveChainName,
Expand Down Expand Up @@ -910,31 +911,34 @@ export class PhishingController extends BaseController<
}

/**
* Scan a URL for phishing. It will only scan the hostname of the URL. It also only supports
* web URLs.
* Scan a URL for phishing. For most hosts only the hostname is sent to the API; for known
* shared gateways the pathname is included (see `PHISHING_DETECTION_PATH_BASED_ROOT_DOMAINS`).
* Only supports web URLs (`http:` / `https:`).
*
* @param url - The URL to scan.
* @returns The phishing detection scan result.
*/
async scanUrl(url: string): Promise<PhishingDetectionScanResult> {
const [hostname, ok] = getHostnameFromWebUrl(url);
if (!ok) {
const [scanUrlParam, scanParamOk] = getPhishingDetectionScanUrlParam(url);
if (!scanParamOk) {
return {
hostname: '',
recommendedAction: RecommendedAction.None,
fetchError: 'url is not a valid web URL',
};
}

const cachedResult = this.#urlScanCache.get(hostname);
const [hostname] = getHostnameFromWebUrl(url);

const cachedResult = this.#urlScanCache.get(scanUrlParam);
if (cachedResult) {
return cachedResult;
}

const apiResponse = await safelyExecuteWithTimeout(
async () => {
const res = await fetch(
`${PHISHING_DETECTION_BASE_URL}/${PHISHING_DETECTION_SCAN_ENDPOINT}?url=${encodeURIComponent(hostname)}`,
`${PHISHING_DETECTION_BASE_URL}/${PHISHING_DETECTION_SCAN_ENDPOINT}?url=${encodeURIComponent(scanUrlParam)}`,
{
method: 'GET',
headers: {
Expand Down Expand Up @@ -974,7 +978,7 @@ export class PhishingController extends BaseController<
recommendedAction: apiResponse.recommendedAction,
};

this.#urlScanCache.set(hostname, result);
this.#urlScanCache.set(scanUrlParam, result);
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shared cache uses inconsistent keys across methods

Medium Severity

scanUrl now reads/writes #urlScanCache using scanUrlParam (e.g. ipfs.io/ipfs/QmAAA) as the key, but bulkScanUrls still reads/writes the same shared #urlScanCache using plain hostname (e.g. ipfs.io). Before this change both methods used hostname, so the cache was coherent. Now, for path-based gateway hosts, results cached by one method are invisible to the other, causing redundant API calls and inconsistent cache-hit behavior depending on which method was called first.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 7229179. Configure here.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Known limitation with this PR but should have minimal impact since bulk scans are only used by the NftController, therefore the overlap in scans should be low.

We can address this in a follow-up PR


return result;
}
Expand Down
5 changes: 5 additions & 0 deletions packages/phishing-controller/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,11 @@ export {
ApprovalFeatureType,
} from './types';
export type { CacheEntry } from './CacheManager';
export {
PHISHING_DETECTION_PATH_BASED_ROOT_DOMAINS,
getPhishingDetectionScanUrlParam,
isPhishingDetectionPathBasedHostname,
} from './utils';

export type {
PhishingControllerMaybeUpdateStateAction,
Expand Down
50 changes: 50 additions & 0 deletions packages/phishing-controller/src/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import {
getHostnameAndPathComponents,
getHostnameFromUrl,
getHostnameFromWebUrl,
getPhishingDetectionScanUrlParam,
isPhishingDetectionPathBasedHostname,
matchPartsAgainstList,
processConfigs,
processDomainList,
Expand Down Expand Up @@ -981,6 +983,54 @@ describe('getHostnameFromWebUrl', () => {
);
});

describe('isPhishingDetectionPathBasedHostname', () => {
it('returns true for registered roots and subdomains', () => {
expect(isPhishingDetectionPathBasedHostname('ipfs.io')).toBe(true);
expect(isPhishingDetectionPathBasedHostname('gateway.ipfs.io')).toBe(true);
expect(isPhishingDetectionPathBasedHostname('dweb.link')).toBe(true);
expect(isPhishingDetectionPathBasedHostname('sites.google.com')).toBe(true);
});

it('is case-insensitive', () => {
expect(isPhishingDetectionPathBasedHostname('IPFS.IO')).toBe(true);
expect(isPhishingDetectionPathBasedHostname('Gateway.IPFS.IO')).toBe(true);
});

it('returns false for unrelated hosts', () => {
expect(isPhishingDetectionPathBasedHostname('example.com')).toBe(false);
expect(isPhishingDetectionPathBasedHostname('evil-ipfs.io')).toBe(false);
});
});

describe('getPhishingDetectionScanUrlParam', () => {
it('returns hostname only for non-gateway hosts', () => {
expect(
getPhishingDetectionScanUrlParam('https://example.com/path?q=1#h'),
).toStrictEqual(['example.com', true]);
});

it('returns hostname plus path for path-based gateway hosts', () => {
expect(
getPhishingDetectionScanUrlParam(
'https://ipfs.io/ipfs/QmAAA/foo?x=1#frag',
),
).toStrictEqual(['ipfs.io/ipfs/QmAAA/foo', true]);
});

it('does not append path when pathname is /', () => {
expect(
getPhishingDetectionScanUrlParam('https://dweb.link/'),
).toStrictEqual(['dweb.link', true]);
});

it('returns ok false for invalid web URLs', () => {
expect(getPhishingDetectionScanUrlParam('not-a-url')).toStrictEqual([
'',
false,
]);
});
});

/**
* Extracts the domain name (e.g., example.com) from a given hostname.
*
Expand Down
54 changes: 54 additions & 0 deletions packages/phishing-controller/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,60 @@ export const getHostnameFromWebUrl = (url: string): [string, boolean] => {
return [hostname || '', Boolean(hostname)];
};

/**
* Hosts where PDS single-URL scans include the URL path (shared gateways / hosts where many sites
* share one origin). For all other hosts, only the hostname is sent.
*/
export const PHISHING_DETECTION_PATH_BASED_ROOT_DOMAINS = [
'ipfs.io',
'dweb.link',
'cf-ipfs.com',
'cloudflare-ipfs.com',
'irys.xyz',
'sites.google.com',
] as const;

/**
* @param hostname - Lowercase normalization is applied for matching registered roots and subdomains.
* @returns Whether {@link getPhishingDetectionScanUrlParam} appends pathname for this hostname.
*/
export function isPhishingDetectionPathBasedHostname(
hostname: string,
): boolean {
const normalizedHost = hostname.toLowerCase();
return PHISHING_DETECTION_PATH_BASED_ROOT_DOMAINS.some(
(root) => normalizedHost === root || normalizedHost.endsWith(`.${root}`),
);
}

/**
* Builds the `url` query parameter for {@link PhishingController.scanUrl}. For hosts in
* {@link PHISHING_DETECTION_PATH_BASED_ROOT_DOMAINS} (and their subdomains), the value is hostname
* plus pathname, without protocol, query, or fragment. For all other hosts, only hostname is used.
*
* @param url - A web URL string (must use `http:` or `https:` — same rules as {@link getHostnameFromWebUrl}).
* @returns A tuple of `[scanUrlParam, ok]` where `ok` is false when the URL is not a valid web URL.
*/
export const getPhishingDetectionScanUrlParam = (
url: string,
): [scanUrlParam: string, ok: boolean] => {
const [hostname, ok] = getHostnameFromWebUrl(url);
if (!ok) {
return ['', false];
}

if (!isPhishingDetectionPathBasedHostname(hostname)) {
return [hostname, true];
}

// `getHostnameFromWebUrl` already required a successful `new URL(url)` parse.
const { pathname } = new URL(url);
const pathSuffix = pathname === '/' ? '' : pathname;
const scanUrlParam = pathSuffix ? `${hostname}${pathSuffix}` : hostname;

return [scanUrlParam, true];
};

export const getPathnameFromUrl = (url: string): string => {
try {
const { pathname } = new URL(url);
Expand Down
Loading