From d90954ef3b6a07b3a0b01f8909f133c0ef504ef1 Mon Sep 17 00:00:00 2001 From: Guy Mac Date: Mon, 14 Mar 2022 18:02:10 +0000 Subject: [PATCH] fix(csp): remove script nonce if inline scripts are disabled (#700) Co-authored-by: guym4c Co-authored-by: Jonny Adshead --- __tests__/server/middleware/csp.spec.js | 8 ++------ src/server/middleware/csp.js | 4 ++-- 2 files changed, 4 insertions(+), 8 deletions(-) diff --git a/__tests__/server/middleware/csp.spec.js b/__tests__/server/middleware/csp.spec.js index 810c16b9..8fbf767d 100644 --- a/__tests__/server/middleware/csp.spec.js +++ b/__tests__/server/middleware/csp.spec.js @@ -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', () => { @@ -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(); }); }); diff --git a/src/server/middleware/csp.js b/src/server/middleware/csp.js index 0abd0a90..33a4fd87 100644 --- a/src/server/middleware/csp.js +++ b/src/server/middleware/csp.js @@ -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); }