Skip to content

Instantly share code, notes, and snippets.

@hannalaakso
Last active July 14, 2020 16:31
Show Gist options
  • Save hannalaakso/998d7c4aa0124366cd7cef79fa57b7e6 to your computer and use it in GitHub Desktop.
Save hannalaakso/998d7c4aa0124366cd7cef79fa57b7e6 to your computer and use it in GitHub Desktop.
Document how to configure Content Security Policy (CSP) to work with the inline 'js-enabled' script

Background

We currently have an inline script tag in the page template that adds the 'js-enabled' class

<script>
    document.body.className = ((document.body.className) ? document.body.className + ' js-enabled' : 'js-enabled');
  </script>

This is for usability reasons: we don't want to have to wait for the GOV.UK Frontend JS file to load before the correct classes and styling is applied - this approach avoids the flash of content for instance hiding the toggleable content of details and accordion components.

Problem

If you have Content Security Policy (CSP) enabled for your application, you might see something like:

Refused to execute inline script because it violates the following Content Security Policy directive: "default-src 'self'". Either the 'unsafe-inline' keyword, a hash ('sha256-+6WnXIl4mbFTCARd8N3COQmT3bJJmo32N8q8ZSQAIcU='), or a nonce ('nonce-...') is required to enable inline execution. Note also that 'script-src' was not explicitly set, so 'default-src' is used as a fallback.

and the inline script is blocked.

See alphagov/govuk-frontend#1811 and alphagov/govuk-frontend#1657

Solution

Hash or nonce?

Hashes

Generate a hash of the script, include it in your CSP:

Content-Security-Policy: default-src 'self'; script-src 'sha256-+6WnXIl4mbFTCARd8N3COQmT3bJJmo32N8q8ZSQAIcU='

We don't expect the script tag to change much, if almost ever, so the hash will stay fairly static.

A change to the hash would be treatead as a breaking change, in case teams copy it manually instead of fetching it from the npm package.

Nonces

More convenient than the hash as you won't have to recalculate the hash every time the script tag changes (but we don't expect the script tag to change much - see above).

There are some reported ways to bypass nonces.

Adding a nonce to the page template markup would be a breaking change.

What next?

  • Speak to frontend community
  • Speak to GOV.UK regarding RFC 98
  • Check approach with cyber security
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment