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 14 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
33 changes: 33 additions & 0 deletions app/scripts/background.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ import {
// TODO: Remove restricted import
itsyoboieltr marked this conversation as resolved.
Show resolved Hide resolved
// eslint-disable-next-line import/no-restricted-paths
import { getCurrentChainId } from '../../ui/selectors';
import { CSP } from '../../shared/modules/content-security-policy';
import migrations from './migrations';
import Migrator from './lib/migrator';
import ExtensionPlatform from './platforms/extension';
Expand Down Expand Up @@ -331,6 +332,34 @@ function maybeDetectPhishing(theController) {
);
}

/**
* Overrides the Content-Security-Policy Header, acting as a workaround for an MV2 Firefox Bug.
itsyoboieltr marked this conversation as resolved.
Show resolved Hide resolved
*/
function overrideContentSecurityPolicyHeader() {
browser.webRequest.onHeadersReceived.addListener(
({ responseHeaders }) => {
for (const header of responseHeaders) {
itsyoboieltr marked this conversation as resolved.
Show resolved Hide resolved
if (header.name.toLowerCase() === 'content-security-policy') {
const contentSecurityPolicy = CSP.parse(header.value);
const nonce = `'nonce-${btoa(browser.runtime.getURL('/'))}'`;
const scriptSrc = Object.keys(contentSecurityPolicy).find(
(directive) => directive.toLowerCase() === 'script-src',
);
if (scriptSrc) {
contentSecurityPolicy[scriptSrc].push(nonce);
} else {
contentSecurityPolicy['script-src'] = [nonce];
}
itsyoboieltr marked this conversation as resolved.
Show resolved Hide resolved
header.value = CSP.stringify(contentSecurityPolicy);
}
}
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 @@ -477,6 +506,10 @@ async function initialize() {

if (!isManifestV3) {
await loadPhishingWarningPage();
const platform = getPlatform();
if (platform === PLATFORM_FIREFOX) {
overrideContentSecurityPolicyHeader();
}
itsyoboieltr marked this conversation as resolved.
Show resolved Hide resolved
}
await sendReadyMessageToTabs();
log.info('MetaMask initialization complete.');
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(browser.runtime.getURL('/'));d.documentElement.appendChild(s).remove();}`;
itsyoboieltr marked this conversation as resolved.
Show resolved Hide resolved
writeFileSync(filePath, js, 'utf8');
}

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(browser.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(browser.runtime.getURL('/'));d.documentElement.appendChild(s).remove()}`,
);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,7 @@ export class SelfInjectPlugin {
`\`\\n//# sourceURL=\${${this.options.sourceUrlExpression(file)}};\``,
);
newSource.add(`;`);
newSource.add(`s.nonce=btoa(browser.runtime.getURL('/'));`);
itsyoboieltr marked this conversation as resolved.
Show resolved Hide resolved
// add and immediately remove the script to avoid modifying the DOM.
newSource.add(`d.documentElement.appendChild(s).remove()`);
newSource.add(`}`);
Expand Down
65 changes: 65 additions & 0 deletions shared/modules/content-security-policy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
// ASCII whitespace is U+0009 TAB, U+000A LF, U+000C FF, U+000D CR, or U+0020 SPACE.
// See <https://infra.spec.whatwg.org/#ascii-whitespace>.
const ASCII_WHITESPACE_CHARS = '\t\n\f\r ';
const ASCII_WHITESPACE = RegExp(`[${ASCII_WHITESPACE_CHARS}]+`);
const ASCII_WHITESPACE_AT_START = RegExp(`^[${ASCII_WHITESPACE_CHARS}]+`);
const ASCII_WHITESPACE_AT_END = RegExp(`[${ASCII_WHITESPACE_CHARS}]+$`);
itsyoboieltr marked this conversation as resolved.
Show resolved Hide resolved

// An ASCII code point is a code point in the range U+0000 NULL to U+007F DELETE, inclusive.
// See <https://infra.spec.whatwg.org/#ascii-string>.
const ASCII = /^[\x00-\x7f]*$/;

export type ContentSecurityPolicy = Record<string, string[]>;

/**
* An intrinsic object that provides functions to handle the Content Security Policy (CSP) format.
*/
export const CSP = {
/**
* Converts a Content Security Policy (CSP) string into an object according to [the spec][0].
*
* [0]: https://w3c.github.io/webappsec-csp/#parse-serialized-policy
*
* @param text The Content Security Policy (CSP) string to parse.
* @returns A Content Security Policy (CSP) object.
*/
parse: (text: string) => {
const contentSecurityPolicy: ContentSecurityPolicy = {};

// For each token returned by strictly splitting serialized on the
// U+003B SEMICOLON character (;):
const tokens = text.split(';');

for (const token of tokens) {
// Strip leading and trailing ASCII whitespace from token.
const strippedToken = token
.replace(ASCII_WHITESPACE_AT_START, '')
.replace(ASCII_WHITESPACE_AT_END, '');

// If strippedToken is an empty string, or if strippedToken is not an ASCII string, continue.
if (!strippedToken || !ASCII.test(strippedToken)) continue;

// Directive name is the result of collecting a sequence of code points from token which are not ASCII whitespace.
// Directive values are the result of splitting token on ASCII whitespace.
const [name, ...values] = strippedToken.split(ASCII_WHITESPACE);
itsyoboieltr marked this conversation as resolved.
Show resolved Hide resolved

contentSecurityPolicy[name] = values;
itsyoboieltr marked this conversation as resolved.
Show resolved Hide resolved
}

return contentSecurityPolicy;
},
/**
* Converts a Content Security Policy (CSP) object into a string.
*
* @param contentSecurityPolicy The Content Security Policy (CSP) object to stringify.
* @returns A Content Security Policy (CSP) string.
*/
stringify: (contentSecurityPolicy: ContentSecurityPolicy) => {
return Object.entries(contentSecurityPolicy)
.map(([name, values]) => {
const value = values.length ? ` ${values.join(' ')}` : '';
return `${name}${value}`;
})
.join('; ');
},
};