Skip to content

Commit

Permalink
Allow nonce attribute to be set on inline script
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
nataliecarey committed Jun 10, 2021
1 parent 7416216 commit 2e40d74
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 2e40d74

Please sign in to comment.