ruby-on-railscontent-security-policy

How to use unsafe-hashes Content Security Policy with Ruby on Rails


I have a Ruby on Rails application, (rails v 6.1.7.9) which allows user generated content, so I want to use a content security policy. I have one custom javascript call I want to trigger on an event handler (it is a text-area, I update a preview with the oninput event).

I'm trying to follow the w3c guidance for using unsafe-hashes:

MegaCorp, Inc. can’t quite get rid of the following HTML on anything resembling a reasonable schedule:

<button id="action" onclick="doSubmit()">

Rather than reducing security by specifying "'unsafe-inline'", they decide to use "'unsafe-hashes'" along with a hash source expression corresponding to doSubmit(), as follows:

Content-Security-Policy: script-src 'unsafe-hashes' 'sha256-jzgBGA4UWFFmpOBq0JpdsySukE1FrEN5bUpoK8Z29fY='

Rails lets me define a content security policy as outlined in the docs by editing config/initializers/content_security_policy.rb:

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

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

But, I can't find any way to specify unsafe-hashes under policy.script_src. If I add :unsafe_hashes and my sha256 string in quotes, I get the following error:

Unknown content security policy source mapping: :unsafe_hashes

It seems like the DSL wants only pre-defined sources, how can I manually specify text that should be included in the CSP headers, or otherwise use unsafe-hashes?


Solution

  • Rails 6.1.7.9 does not have a mapping for unsafe_hashes which was introduced in 7.1 by this commit

    That being said looking at the commit it appears you might be able to use:

     policy.script_src  :strict_dynamic, "'unsafe-hashes'", "'YOUR_SHA256_STRING'"