content-security-policyhtml-webpack-plugincsp-html-webpack-plugin

How to use CspHtmlWebpackPlugin for static html and js files?


I am using HtmlWebpackPlugin for a react site so I've decided to use the CspHtmlWebpackPlugin plugin for it. This plugin is correctly producing nonces and hashes for the bundles and files that webpack is recognizing. The problem I'm having is that I reference some static html and static js files which are not being nonced or hashed (because they're static?). I'm not sure how to get these integrated properly with my CSP setup. Here is my webpack configuration for the CSP plugin:

  cspPlugin: {
    enabled: true,
    policy: {
      'script-src': [
        `'self'`,
        `https://www.googletagmanager.com`
      ],
      'style-src': [
        `'unsafe-inline'`,
        `'self'`,
        `'unsafe-eval'`,
        `https://fonts.googleapis.com`
      ]
    },
    hashEnabled: {
      'script-src': true,
      'style-src': false
    },
    nonceEnabled: {
      'script-src': true,
      'style-src': false
    },
    processFn: generateNginxBaseHeaderFile
  }

This is generating something simlar to the following headers:

content-security-policy-report-only: base-uri 'self'; object-src 'none';
  script-src 'self' https://www.googletagmanager.com
  'sha256-Cudo9RvyD4crXHpdRlNVVHb29bDV+/+TsYuDgFpxVwY=' 'sha256-afmMNrePPscv0A0DHOtUey1aVoZppHkmcGz+ddjnv2M='
  'nonce-1vbzuUPh7Nd+vV9Glkq5+w==' 'nonce-sSfmgIuXxcAr6qfwuAO3vg==' 'nonce-h/1RsCNeHX65s+sJ9AbOnQ=='
  'nonce-PO2OQxOi4WkSY4sukJAbZg==' 'nonce-5uEE3hj9xUaFxjf7+lAxVQ==';
  style-src 'unsafe-inline' 'self' 'unsafe-eval' https://fonts.googleapis.com;

When visiting the site itself I have errors such as this for multiple static html and/or js files:

[Report Only] Refused to execute inline script because it violates the following Content Security Policy directive: (...redacted...)
  Either the 'unsafe-inline' keyword, a hash ('sha256-Lb8dFvdAxwTPI2Stpzv1lYq3YtfRcVGhzizMUGcR1jU='),
  or a nonce ('nonce-...') is required to enable inline execution.

Is there a way to get the plugin to handle these files or do I need to do something manually to make it work properly?


Solution

  • The error message says "Refused to execute inline script", so it is not your static files, they are allowed by 'self'. It is either inline script or event attributes (like onclick). If it is an inline script there will likely be a link in the error message to the script and adding the hash will resolve it. If it is an event attribute adding the hash will not help and you will need to rewrite it with an event listener instead.