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

Configure nonce also for preloaded scripts #85

Closed
wants to merge 2 commits into from
Closed
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
27 changes: 27 additions & 0 deletions plugin.jest.js
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,33 @@ describe('CspHtmlWebpackPlugin', () => {
});
});

it('inserts the default policy, including sha-256 hashes of other inline scripts and styles found, and nonce hashes of external scripts found using data-csp="script-src" directive', (done) => {
const config = createWebpackConfig([
new HtmlWebpackPlugin({
filename: path.join(WEBPACK_OUTPUT_DIR, 'index.html'),
template: path.join(
__dirname,
'test-utils',
'fixtures',
'with-preload-script-and-style.html'
),
}),
new CspHtmlWebpackPlugin(),
]);

webpackCompile(config, (csps) => {
const expected =
"base-uri 'self';" +
" object-src 'none';" +
" script-src 'unsafe-inline' 'self' 'unsafe-eval' 'nonce-mockedbase64string-1' 'nonce-mockedbase64string-2';" +
" style-src 'unsafe-inline' 'self' 'unsafe-eval'";

expect(csps['index.html']).toEqual(expected);

done();
});
});

it('inserts a custom policy if one is defined', (done) => {
const config = createWebpackConfig([
new HtmlWebpackPlugin({
Expand Down
6 changes: 5 additions & 1 deletion plugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -324,7 +324,11 @@ class CspHtmlWebpackPlugin {
}

// get all nonces for script and style tags
const scriptNonce = this.setNonce($, 'script-src', 'script[src]');
const scriptNonce = this.setNonce(
$,
'script-src',
'script[src], [data-csp="script-src"]'
);
const styleNonce = this.setNonce($, 'style-src', 'link[rel="stylesheet"]');

// get all shas for script and style tags
Expand Down
11 changes: 11 additions & 0 deletions test-utils/fixtures/with-preload-script-and-style.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<!doctype html>
<html lang="en-US">
<head>
<meta name="author" content="Slack">
<title>Slack CSP HTML Webpack Plugin Tests</title>
<link rel="preload" href="https://example.com/preload-example.js" as="script" data-csp="script-src">
</head>
<body>
Body
</body>
</html>