thoughtbot / administrate

A Rails engine that helps you put together a super-flexible admin dashboard.
http://administrate-demo.herokuapp.com
MIT License
5.87k stars 1.11k forks source link

Inline Style doesn't work with Content Security Policy #2087

Closed michaelbaisch closed 2 years ago

michaelbaisch commented 2 years ago

Hello,

after enabling CSP I get this error in the browser console when opening administrate:

Refused to apply a stylesheet because its hash, its nonce, or 'unsafe-inline' does not appear in the style-src directive of the Content Security Policy.

Referencing this line:

<svg xmlns="http://www.w3.org/2000/svg" style="display: none;">

Maybe this simple style could be transferred to the administrate css?

Greetings, Michael

pablobm commented 2 years ago

My understanding of CSP is rusty at the moment :sweat: How did you enable CSP in your app? Do you know what the alternatives are?

michaelbaisch commented 2 years ago

That's pretty straight forward - see https://edgeguides.rubyonrails.org/security.html#content-security-policy

In config/initializers/content_security_policy.rb active this:

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
end

If you want to allow inline style and js (but only in a separate tag) you need to activate nonce generation:

Rails.application.config.content_security_policy_nonce_generator = -> request { SecureRandom.base64(16) }

Rails.application.config.content_security_policy_nonce_directives = %w(script-src style-src)

This way you could so things like:

<%= javascript_tag nonce: true do %>
<% end -%>

<style type="text/css" nonce="<%= content_security_policy_nonce %>">
</style>

But as I said earlier it would be a cleaner solution if that display: none would be in a regular css file and not inline.

pablobm commented 2 years ago

I see, that makes sense. I wonder if the style was put inline originally due to some browser incompatibility or some such?

Browsers are better-behaved creatures these days, so perhaps we can try move this into the stylesheets as you first proposed. Would you be able to create a PR?

kaka-ruto commented 6 months ago

It was the grammarly browser extension for me that I had to disable 🤦🏽‍♂️

pablobm commented 1 month ago

@kaka-ruto - Thank you for sharing that! 🙌 It may be helpful to other people who end up here in the future.