Skip to content

Commit

Permalink
Merge pull request #2245 from dorightdigital/script-nonce
Browse files Browse the repository at this point in the history
Allow the CSP `nonce` attribute to be set on the inline script in the page template
  • Loading branch information
36degrees authored Jun 11, 2021
2 parents 90dd9db + 2e40d74 commit 279606d
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/govuk/template.njk
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
<meta property="og:image" content="{{ assetUrl | default('/assets') }}/images/govuk-opengraph-image.png">
</head>
<body class="govuk-template__body {{ bodyClasses }}" {%- for attribute, value in bodyAttributes %} {{attribute}}="{{value}}"{% endfor %}>
<script>document.body.className = ((document.body.className) ? document.body.className + ' js-enabled' : 'js-enabled');</script>
<script{% if cspNonce %} nonce="{{ cspNonce }}"{% endif %}>document.body.className = ((document.body.className) ? document.body.className + ' js-enabled' : 'js-enabled');</script>
{% block bodyStart %}{% endblock %}

{% block skipLink %}
Expand Down
12 changes: 12 additions & 0 deletions src/govuk/template.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down

0 comments on commit 279606d

Please sign in to comment.