hotwired / turbo-rails

Use Turbo in your Ruby on Rails app
https://turbo.hotwired.dev
MIT License
2.14k stars 329 forks source link

Content Security Policy Error with style tag #458

Open timfsw opened 1 year ago

timfsw commented 1 year ago

Has anyone any idea with the style tag doesn't work in Firefox with activated Content Security Policy and Turbo? The script tag works well.

When i visit the page directly (without turbo) there is no CSP error.

The error is thrown in replaceWith with following error message: Content Security Policy: The page's settings blocked the loading of a resource at inline ("style-src").

var PageRenderer = class extends Renderer {
  static renderElement(currentElement, newElement) {
    if (document.body && newElement instanceof HTMLBodyElement) {
      document.body.replaceWith(newElement);
    } else {
      document.documentElement.appendChild(newElement);
    }
  }
}
<%= javascript_tag nonce: true, defer: true, data: { turbo_temporary: true } do %>
  console.log('Hello, World!');
<% end %>
<%= content_tag(:style, nonce: content_security_policy_nonce, defer: true, data: { turbo_temporary: true }) do
  'body { background-color: red; }'
end %>
Rails.application.configure do
  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, '\'sha256-WAyOw4V+FqDc35lQPyRADLBWbuNK8ahvYEaQIYF1+Ps=\''
    # Specify URI for violation reports
    # policy.report_uri "/csp-violation-report-endpoint"
  end

  # Generate session nonces for permitted importmap and inline scripts
  config.content_security_policy_nonce_generator = ->(request) { request.session.id.to_s }
  config.content_security_policy_nonce_directives = %w(script-src style-src)

  # Report violations without enforcing the policy.
  # config.content_security_policy_report_only = true
end
rience commented 1 year ago

Hi,

I have been affected by the same problem. At the moment the only workaround is to add data-turbo-track="reload" to stylesheet tag.

I've created sample application that shows this problem (take a look at readme - it describes how to recreate it): https://github.com/rience/turbo-and-nonce