Skip to content
This repository has been archived by the owner on May 3, 2024. It is now read-only.

Commit

Permalink
fix(csp): remove script nonce if inline scripts are disabled (#700)
Browse files Browse the repository at this point in the history
Co-authored-by: guym4c <hi@guymac.eu>
Co-authored-by: Jonny Adshead <JAdshead@users.noreply.github.com>
  • Loading branch information
3 people authored Mar 14, 2022
1 parent 30770a5 commit d90954e
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 8 deletions.
8 changes: 2 additions & 6 deletions __tests__/server/middleware/csp.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ describe('csp', () => {
const headers = res._getHeaders();
const { scriptNonce } = res;
expect(headers).toHaveProperty('content-security-policy');
expect(headers['content-security-policy'].search(scriptNonce)).not.toEqual(-1);
expect(headers['content-security-policy'].includes(scriptNonce)).toBe(true);
});

it('does not set the script nonce if this has been disabled in development', () => {
Expand All @@ -139,11 +139,7 @@ describe('csp', () => {
const { updateCSP } = requiredCsp;
updateCSP("default-src 'none'; script-src 'self';");
cspMiddleware()(req, res, next);
// eslint-disable-next-line no-underscore-dangle
const headers = res._getHeaders();
const { scriptNonce } = res;
expect(headers).toHaveProperty('content-security-policy');
expect(headers['content-security-policy'].search(scriptNonce)).toEqual(-1);
expect(res.scriptNonce).toBeUndefined();
});
});

Expand Down
4 changes: 2 additions & 2 deletions src/server/middleware/csp.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,15 +66,15 @@ const csp = () => (req, res, next) => {
if (process.env.ONE_CSP_ALLOW_INLINE_SCRIPTS === 'true') {
updatedScriptSrc = insertSource(policy, 'script-src', developmentAdditions);
} else {
res.scriptNonce = scriptNonce;
updatedScriptSrc = insertSource(policy, 'script-src', `'nonce-${scriptNonce}' ${developmentAdditions}`);
}
updatedPolicy = insertSource(updatedScriptSrc, 'connect-src', developmentAdditions);
} else {
res.scriptNonce = scriptNonce;
updatedPolicy = insertSource(policy, 'script-src', `'nonce-${scriptNonce}'`);
}

res.scriptNonce = scriptNonce;

if (process.env.ONE_DANGEROUSLY_DISABLE_CSP !== 'true') {
res.setHeader('Content-Security-Policy', updatedPolicy);
}
Expand Down

0 comments on commit d90954e

Please sign in to comment.