How can I deal with Highcharts inline styles to prevent Content-Security-Policy violations?

Viewed 821

I have an app that uses Highcharts to display data to users, and it's working well. I'm now applying a Content-Security-Policy header to this app and, again, that's working fine (in Report-Only mode for now).

The issue is that Highcharts uses inline styles, and these are obviously reported as violations of the CSP. I'd therefore like to prevent these violations of the policy, without just allowing inline styles (which reduces the value of having a CSP).

My question is thus: is there a way to inject the nonce into Highcharts so that the violations stop?

The error report is:

[Report Only] Refused to apply inline style because it violates the following Content Security Policy directive: "style-src 'self' https: 'nonce-M/dyQoRv6ZpuH6yj1/q6tA=='". Either the 'unsafe-inline' keyword, a hash ('sha256-7wj/+4oyhC/Un8WKFeS81vcvueSVhV/Hk8Tuw/NlDC8='), or a nonce ('nonce-...') is required to enable inline execution. H @ highcharts.js:91

The app is built with Rails 6.0.2 using webpacker and Highcharts 7.2.1.

My config/initializers/content_security_policy.rb file is pretty much the default:

# frozen_string_literal: true

Rails.application.config.content_security_policy do |policy|
  policy.default_src :self, :https
  policy.font_src    :self, :https, :data
  policy.img_src     :self, :https, :data
  policy.object_src  :none
  policy.script_src  :self, :https
  policy.style_src   :self, :https
  # If you are using webpack-dev-server then specify webpack-dev-server host
  policy.connect_src :self, :https, "http://localhost:3035", "ws://localhost:3035" if Rails.env.development? || Rails.env.test?

  # Specify URI for violation reports
  # policy.report_uri "/csp-violation-report-endpoint"
end

# If you are using UJS then enable automatic nonce generation
Rails.application.config.content_security_policy_nonce_generator = -> request { SecureRandom.base64(16) }

Rails.application.config.content_security_policy_report_only = true
1 Answers

As noted in the comments to the original question, the answer is enabling styledMode. This stops HighCharts using inline styles and instead uses a stylesheet. This may mean updating the default stylesheets to reflect how you want the charts to look, because the commands used to do this in the default mode will now do nothing (for colours, lines, markers etc.).

API: https://api.highcharts.com/highcharts/chart.styledMode

Related