Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: mv2 firefox csp header #27770

Merged
merged 53 commits into from
Nov 7, 2024
Merged
Show file tree
Hide file tree
Changes from 48 commits
Commits
Show all changes
53 commits
Select commit Hold shift + click to select a range
f8014e2
fix: mv2 firefox csp header
itsyoboieltr Oct 10, 2024
51e7033
Merge branch 'develop' into fix-firefox-csp
itsyoboieltr Oct 11, 2024
c6bd1bd
feat: nonce
itsyoboieltr Oct 14, 2024
1905247
fix: nonce
itsyoboieltr Oct 15, 2024
cd551fd
fix: random url
itsyoboieltr Oct 15, 2024
a35b17e
Merge branch 'develop' into fix-firefox-csp
itsyoboieltr Oct 15, 2024
d1a84c2
fix: webpack tests
itsyoboieltr Oct 15, 2024
885c320
fix: regex
itsyoboieltr Oct 15, 2024
ba383e4
fix: regex whitespace
itsyoboieltr Oct 15, 2024
c048d41
feat: addNonceToCsp with tests
itsyoboieltr Oct 15, 2024
dc0d053
Merge branch 'develop' into fix-firefox-csp
itsyoboieltr Oct 17, 2024
95b3ad8
fix: limit types
itsyoboieltr Oct 17, 2024
ab2896d
fix: getPlatform
itsyoboieltr Oct 17, 2024
9a7cd35
feat: CSP
itsyoboieltr Oct 17, 2024
d1e0bce
fix: new RegExp
itsyoboieltr Oct 18, 2024
267a35c
feat: comments
itsyoboieltr Oct 18, 2024
52053ab
feat: array of directives
itsyoboieltr Oct 18, 2024
8f68b2a
fix: lint
itsyoboieltr Oct 21, 2024
9baaa86
feat: respect whitespace
itsyoboieltr Oct 21, 2024
fe9188e
feat: make it simpler
itsyoboieltr Oct 22, 2024
f32f598
fix: filename
itsyoboieltr Oct 22, 2024
2e53360
Merge branch 'develop' into fix-firefox-csp
itsyoboieltr Oct 22, 2024
f72aa1d
fix: casing
itsyoboieltr Oct 22, 2024
a939b23
feat: tests
itsyoboieltr Oct 22, 2024
fe6f667
Merge branch 'develop' into fix-firefox-csp
itsyoboieltr Oct 24, 2024
3d903f9
Merge branch 'develop' into fix-firefox-csp
itsyoboieltr Oct 25, 2024
8e65468
feat: nonce explanation
itsyoboieltr Oct 25, 2024
ce4709f
feat: nonceExpression
itsyoboieltr Oct 25, 2024
5483bd8
feat: checkURLForProviderInjection
itsyoboieltr Oct 25, 2024
83f3908
feat: e2e test
itsyoboieltr Oct 30, 2024
a014742
fix: getRuntimeURLExpression placement
itsyoboieltr Oct 30, 2024
851cc5e
fix: location mock
itsyoboieltr Oct 30, 2024
73a22d3
fix: placement
itsyoboieltr Oct 30, 2024
30494d5
Merge branch 'develop' into fix-firefox-csp
itsyoboieltr Oct 31, 2024
031f530
Update development/webpack/utils/plugins/SelfInjectPlugin/types.ts
itsyoboieltr Oct 31, 2024
dab24be
feat: @types/serve-handler
itsyoboieltr Oct 31, 2024
49b6924
Merge branch 'develop' into fix-firefox-csp
itsyoboieltr Oct 31, 2024
41498b0
fix: csp header in e2e
itsyoboieltr Oct 31, 2024
8a3f90a
Merge branch 'develop' into fix-firefox-csp
itsyoboieltr Oct 31, 2024
b6e2e25
Update content-security-policy.spec.ts
itsyoboieltr Oct 31, 2024
31c2349
Merge branch 'develop' into fix-firefox-csp
itsyoboieltr Oct 31, 2024
75e16be
feat: ui toggle
itsyoboieltr Nov 4, 2024
b482cac
Update background.js
itsyoboieltr Nov 4, 2024
289dc50
Update settings-search.test.js
itsyoboieltr Nov 4, 2024
5163ec9
fix: description
itsyoboieltr Nov 5, 2024
ab1f3df
feat: only show on firefox
itsyoboieltr Nov 5, 2024
33508e7
Update settings-search.test.js
itsyoboieltr Nov 5, 2024
0fb3c3f
Update settings-search.test.js
itsyoboieltr Nov 5, 2024
f50e960
Merge branch 'develop' into fix-firefox-csp
itsyoboieltr Nov 6, 2024
07d10be
Merge branch 'develop' into fix-firefox-csp
itsyoboieltr Nov 6, 2024
3bf6b9b
fix
itsyoboieltr Nov 6, 2024
6e9ed23
fixture
itsyoboieltr Nov 6, 2024
cec02cb
Update fixture-builder.js
itsyoboieltr Nov 6, 2024
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
6 changes: 6 additions & 0 deletions app/_locales/en/messages.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

41 changes: 41 additions & 0 deletions app/scripts/background.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@ import {
// TODO: Remove restricted import
// eslint-disable-next-line import/no-restricted-paths
import { getCurrentChainId } from '../../ui/selectors';
import { addNonceToCsp } from '../../shared/modules/add-nonce-to-csp';
import { checkURLForProviderInjection } from '../../shared/modules/provider-injection';
import migrations from './migrations';
import Migrator from './lib/migrator';
import ExtensionPlatform from './platforms/extension';
Expand Down Expand Up @@ -333,6 +335,40 @@ function maybeDetectPhishing(theController) {
);
}

/**
* Overrides the Content-Security-Policy (CSP) header by adding a nonce to the `script-src` directive.
* This is a workaround for [Bug #1446231](https://bugzilla.mozilla.org/show_bug.cgi?id=1446231),
* which involves overriding the page CSP for inline script nodes injected by extension content scripts.
*/
function overrideContentSecurityPolicyHeader() {
// The extension url is unique per install on Firefox, so we can safely add it as a nonce to the CSP header
const nonce = btoa(browser.runtime.getURL('/'));
browser.webRequest.onHeadersReceived.addListener(
({ responseHeaders, url }) => {
// Check whether inpage.js is going to be injected into the page or not.
// There is no reason to modify the headers if we are not injecting inpage.js.
const isInjected = checkURLForProviderInjection(new URL(url));

// Check if the user has enabled the overrideContentSecurityPolicyHeader preference
const isEnabled =
controller.preferencesController.state
.overrideContentSecurityPolicyHeader;

if (isInjected && isEnabled) {
for (const header of responseHeaders) {
if (header.name.toLowerCase() === 'content-security-policy') {
header.value = addNonceToCsp(header.value, nonce);
}
}
}

return { responseHeaders };
},
{ types: ['main_frame', 'sub_frame'], urls: ['http://*/*', 'https://*/*'] },
['blocking', 'responseHeaders'],
);
}

// These are set after initialization
let connectRemote;
let connectExternalExtension;
Expand Down Expand Up @@ -479,6 +515,11 @@ async function initialize() {

if (!isManifestV3) {
await loadPhishingWarningPage();
// Workaround for Bug #1446231 to override page CSP for inline script nodes injected by extension content scripts
// https://bugzilla.mozilla.org/show_bug.cgi?id=1446231
if (getPlatform() === PLATFORM_FIREFOX) {
overrideContentSecurityPolicyHeader();
}
}
await sendReadyMessageToTabs();
log.info('MetaMask initialization complete.');
Expand Down
1 change: 1 addition & 0 deletions app/scripts/constants/sentry-state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,7 @@ export const SENTRY_BACKGROUND_STATE = {
advancedGasFee: true,
currentLocale: true,
dismissSeedBackUpReminder: true,
overrideContentSecurityPolicyHeader: true,
featureFlags: true,
forgottenPassword: true,
identities: false,
Expand Down
17 changes: 17 additions & 0 deletions app/scripts/controllers/preferences-controller.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -837,6 +837,23 @@ describe('preferences controller', () => {
});
});

describe('overrideContentSecurityPolicyHeader', () => {
it('defaults overrideContentSecurityPolicyHeader to true', () => {
const { controller } = setupController({});
expect(
controller.state.overrideContentSecurityPolicyHeader,
).toStrictEqual(true);
});

it('set overrideContentSecurityPolicyHeader to false', () => {
const { controller } = setupController({});
controller.setOverrideContentSecurityPolicyHeader(false);
expect(
controller.state.overrideContentSecurityPolicyHeader,
).toStrictEqual(false);
});
});

describe('snapsAddSnapAccountModalDismissed', () => {
it('defaults snapsAddSnapAccountModalDismissed to false', () => {
const { controller } = setupController({});
Expand Down
20 changes: 20 additions & 0 deletions app/scripts/controllers/preferences-controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@ export type PreferencesControllerState = Omit<
useNonceField: boolean;
usePhishDetect: boolean;
dismissSeedBackUpReminder: boolean;
overrideContentSecurityPolicyHeader: boolean;
useMultiAccountBalanceChecker: boolean;
useSafeChainsListValidation: boolean;
use4ByteResolution: boolean;
Expand Down Expand Up @@ -172,6 +173,7 @@ export const getDefaultPreferencesControllerState =
useNonceField: false,
usePhishDetect: true,
dismissSeedBackUpReminder: false,
overrideContentSecurityPolicyHeader: true,
useMultiAccountBalanceChecker: true,
useSafeChainsListValidation: true,
// set to true means the dynamic list from the API is being used
Expand Down Expand Up @@ -300,6 +302,10 @@ const controllerMetadata = {
persist: true,
anonymous: true,
},
overrideContentSecurityPolicyHeader: {
persist: true,
anonymous: true,
},
useMultiAccountBalanceChecker: {
persist: true,
anonymous: true,
Expand Down Expand Up @@ -985,6 +991,20 @@ export class PreferencesController extends BaseController<
});
}

/**
* A setter for the user preference to override the Content-Security-Policy header
*
* @param overrideContentSecurityPolicyHeader - User preference for overriding the Content-Security-Policy header.
*/
setOverrideContentSecurityPolicyHeader(
overrideContentSecurityPolicyHeader: boolean,
): void {
this.update((state) => {
state.overrideContentSecurityPolicyHeader =
overrideContentSecurityPolicyHeader;
});
}

/**
* A setter for the incomingTransactions in preference to be updated
*
Expand Down
1 change: 1 addition & 0 deletions app/scripts/lib/backup.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,7 @@ const jsonData = JSON.stringify({
useNonceField: false,
usePhishDetect: true,
dismissSeedBackUpReminder: false,
overrideContentSecurityPolicyHeader: true,
useTokenDetection: false,
useCollectibleDetection: false,
openSeaEnabled: false,
Expand Down
4 changes: 4 additions & 0 deletions app/scripts/metamask-controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -3485,6 +3485,10 @@ export default class MetamaskController extends EventEmitter {
preferencesController.setDismissSeedBackUpReminder.bind(
preferencesController,
),
setOverrideContentSecurityPolicyHeader:
preferencesController.setOverrideContentSecurityPolicyHeader.bind(
preferencesController,
),
setAdvancedGasFee: preferencesController.setAdvancedGasFee.bind(
preferencesController,
),
Expand Down
2 changes: 1 addition & 1 deletion development/build/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -293,7 +293,7 @@ function getBuildName({
function makeSelfInjecting(filePath) {
const fileContents = readFileSync(filePath, 'utf8');
const textContent = JSON.stringify(fileContents);
const js = `{let d=document,s=d.createElement('script');s.textContent=${textContent};d.documentElement.appendChild(s).remove();}`;
const js = `{let d=document,s=d.createElement('script');s.textContent=${textContent};s.nonce=btoa((globalThis.browser||chrome).runtime.getURL('/'));d.documentElement.appendChild(s).remove();}`;
writeFileSync(filePath, js, 'utf8');
}

Expand Down
13 changes: 10 additions & 3 deletions development/create-static-server.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,25 @@ const path = require('path');

const serveHandler = require('serve-handler');

const createStaticServer = (rootDirectory) => {
/**
* Creates an HTTP server that serves static files from a directory using serve-handler.
* If a request URL starts with `/node_modules/`, it rewrites the URL and serves files from the `node_modules` directory.
*
* @param { NonNullable<Parameters<typeof import("serve-handler")>[2]> } options - Configuration options for serve-handler. Documentation can be found here: https://github.com/vercel/serve-handler
* @returns {http.Server} An instance of an HTTP server configured with the specified options.
*/
const createStaticServer = (options) => {
return http.createServer((request, response) => {
if (request.url.startsWith('/node_modules/')) {
request.url = request.url.substr(14);
request.url = request.url.slice(14);
return serveHandler(request, response, {
directoryListing: false,
public: path.resolve('./node_modules'),
});
}
return serveHandler(request, response, {
directoryListing: false,
public: rootDirectory,
...options,
});
});
};
Expand Down
2 changes: 1 addition & 1 deletion development/static-server.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ const onRequest = (request, response) => {
};

const startServer = ({ port, rootDirectory }) => {
const server = createStaticServer(rootDirectory);
const server = createStaticServer({ public: rootDirectory });

server.on('request', onRequest);

Expand Down
4 changes: 2 additions & 2 deletions development/webpack/test/plugins.SelfInjectPlugin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ describe('SelfInjectPlugin', () => {
// reference the `sourceMappingURL`
assert.strictEqual(
newSource,
`{let d=document,s=d.createElement('script');s.textContent="${source}\\n//# sourceMappingURL=${filename}.map"+\`\\n//# sourceURL=\${(globalThis.browser||chrome).runtime.getURL("${filename}")};\`;d.documentElement.appendChild(s).remove()}`,
`{let d=document,s=d.createElement('script');s.textContent="${source}\\n//# sourceMappingURL=${filename}.map"+\`\\n//# sourceURL=\${(globalThis.browser||chrome).runtime.getURL("${filename}")};\`;s.nonce=btoa((globalThis.browser||chrome).runtime.getURL("/"));d.documentElement.appendChild(s).remove()}`,
);
} else {
// the new source should NOT reference the new sourcemap, since it's
Expand All @@ -66,7 +66,7 @@ describe('SelfInjectPlugin', () => {
// console.
assert.strictEqual(
newSource,
`{let d=document,s=d.createElement('script');s.textContent="console.log(3);"+\`\\n//# sourceURL=\${(globalThis.browser||chrome).runtime.getURL("${filename}")};\`;d.documentElement.appendChild(s).remove()}`,
`{let d=document,s=d.createElement('script');s.textContent="console.log(3);"+\`\\n//# sourceURL=\${(globalThis.browser||chrome).runtime.getURL("${filename}")};\`;s.nonce=btoa((globalThis.browser||chrome).runtime.getURL("/"));d.documentElement.appendChild(s).remove()}`,
);
}

Expand Down
21 changes: 19 additions & 2 deletions development/webpack/utils/plugins/SelfInjectPlugin/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,31 @@ import type { SelfInjectPluginOptions, Source, Compiler } from './types';

export { type SelfInjectPluginOptions } from './types';

/**
* Generates a runtime URL expression for a given path.
*
* This function constructs a URL string using the `runtime.getURL` method
* from either the `globalThis.browser` or `chrome` object, depending on
* which one is available in the global scope.
*
* @param path - The path of the runtime URL.
* @returns The constructed runtime URL string.
*/
const getRuntimeURLExpression = (path: string) =>
`(globalThis.browser||chrome).runtime.getURL(${JSON.stringify(path)})`;

/**
* Default options for the SelfInjectPlugin.
*/
const defaultOptions = {
// The default `sourceUrlExpression` is configured for browser extensions.
// It generates the absolute url of the given file as an extension url.
// e.g., `chrome-extension://<extension-id>/scripts/inpage.js`
sourceUrlExpression: (filename: string) =>
`(globalThis.browser||chrome).runtime.getURL(${JSON.stringify(filename)})`,
sourceUrlExpression: getRuntimeURLExpression,
// The default `nonceExpression` is configured for browser extensions.
// It generates the absolute url of a path as an extension url in base64.
// e.g., `Y2hyb21lLWV4dGVuc2lvbjovLzxleHRlbnNpb24taWQ+Lw==`
nonceExpression: (path: string) => `btoa(${getRuntimeURLExpression(path)})`,
} satisfies SelfInjectPluginOptions;

/**
Expand Down Expand Up @@ -142,6 +158,7 @@ export class SelfInjectPlugin {
`\`\\n//# sourceURL=\${${this.options.sourceUrlExpression(file)}};\``,
);
newSource.add(`;`);
newSource.add(`s.nonce=${this.options.nonceExpression('/')};`);
// add and immediately remove the script to avoid modifying the DOM.
newSource.add(`d.documentElement.appendChild(s).remove()`);
newSource.add(`}`);
Expand Down
15 changes: 13 additions & 2 deletions development/webpack/utils/plugins/SelfInjectPlugin/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export type SelfInjectPluginOptions = {
* will be injected into matched file to provide a sourceURL for the self
* injected script.
*
* Defaults to `(filename: string) => (globalThis.browser||globalThis.chrome).runtime.getURL("${filename}")`
* Defaults to `(filename: string) => (globalThis.browser||chrome).runtime.getURL("${filename}")`
*
* @example Custom
* ```js
Expand All @@ -39,11 +39,22 @@ export type SelfInjectPluginOptions = {
*
* ```js
* {
* sourceUrlExpression: (filename) => `(globalThis.browser||globalThis.chrome).runtime.getURL("${filename}")`
* sourceUrlExpression: (filename) => `(globalThis.browser||chrome).runtime.getURL("${filename}")`
* }
* ```
* @param filename - the chunk's relative filename as it will exist in the output directory
* @returns
*/
sourceUrlExpression?: (filename: string) => string;
/**
* A function that returns a JavaScript expression escaped as a string which
* will be injected into matched file to set a nonce for the self
* injected script.
*
* Defaults to `(path: string) => btoa((globalThis.browser||chrome).runtime.getURL("${path}"))`
*
* @param path - the path to be encoded as a nonce
* @returns
*/
nonceExpression?: (path: string) => string;
};
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -526,6 +526,7 @@
"@types/redux-mock-store": "1.0.6",
"@types/remote-redux-devtools": "^0.5.5",
"@types/selenium-webdriver": "^4.1.19",
"@types/serve-handler": "^6.1.4",
"@types/sinon": "^10.0.13",
"@types/sprintf-js": "^1",
"@types/w3c-web-hid": "^1.0.3",
Expand Down
Loading