From 2e40d744af6e6e4213ebc47644982d4eb94422d4 Mon Sep 17 00:00:00 2001 From: Nat Carey Date: Fri, 4 Jun 2021 17:16:19 +0100 Subject: [PATCH] Allow nonce attribute to be set on inline script Not all services are able to follow the currently recommended approach of using hashes to allow specific inline scripts as part of their Content Security Policy. An alternative approach is to use a nonce which requires the attribute to be set on the script itself. Introduce a new Nunjucks variable `cspNonce` for the page template to allow users to do this. --- src/govuk/template.njk | 2 +- src/govuk/template.test.js | 12 ++++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/src/govuk/template.njk b/src/govuk/template.njk index 13a170f25c..55f19553da 100644 --- a/src/govuk/template.njk +++ b/src/govuk/template.njk @@ -28,7 +28,7 @@ - + document.body.className = ((document.body.className) ? document.body.className + ' js-enabled' : 'js-enabled'); {% block bodyStart %}{% endblock %} {% block skipLink %} diff --git a/src/govuk/template.test.js b/src/govuk/template.test.js index 7f3dbc4f4e..ddbdbdc4ef 100644 --- a/src/govuk/template.test.js +++ b/src/govuk/template.test.js @@ -165,6 +165,18 @@ describe('Template', () => { // updating the hash published in https://frontend.design-system.service.gov.uk/importing-css-assets-and-javascript/#if-your-javascript-isn-t-working-properly expect('sha256-' + hash).toEqual('sha256-+6WnXIl4mbFTCARd8N3COQmT3bJJmo32N8q8ZSQAIcU=') }) + it('should not have a nonce attribute by default', () => { + const $ = renderTemplate() + const scriptTag = $('body > script').first() + + expect(scriptTag.attr('nonce')).toEqual(undefined) + }) + it('should have a nonce attribute when nonce is provided', () => { + const $ = renderTemplate({ cspNonce: 'abcdef' }) + const scriptTag = $('body > script').first() + + expect(scriptTag.attr('nonce')).toEqual('abcdef') + }) }) describe('skip link', () => {