简体   繁体   中英

nonce for style-src in Rails is added to script-src by mistake

I have a single inline style tag in a Rails app, and I'm trying to whitelist it with a nonce.

The error: Content Security Policy: The page's settings observed the loading of a resource at inline (“style-src”). A CSP report is being sent. Content Security Policy: The page's settings observed the loading of a resource at inline (“style-src”). A CSP report is being sent.

The style gets injected by a helper when using the invisible_captcha gem:

<%= invisible_captcha nonce: true %>

Comparing the view and the header shows that the nonce is being added to both, but it's being added to script-src instead of style-src .

View: <style media="screen" nonce="5Cq/QyoJ5Co+LdarO1uvrg==">

Header: Content-Security-Policy-Report-Only script-src 'self' https: 'nonce-5Cq/QyoJ5Co+LdarO1uvrg=='; style-src 'self' https:; Content-Security-Policy-Report-Only script-src 'self' https: 'nonce-5Cq/QyoJ5Co+LdarO1uvrg=='; style-src 'self' https:;

This is my content_security_policy.rb :

Rails.application.config.content_security_policy do |config|
 config.style_src  :self, :https    
end

Rails.application.config.content_security_policy_nonce_generator = -> request { SecureRandom.base64(16) }
Rails.application.config.content_security_policy_nonce_directives = %w(style-src script-src)

Why is it going to the wrong directive, and how can I make it go to style-src ?

Yes, that will interfere with your CSP (or, more accuately, your CSP will interfere with your <script> tag).

When using a hash, you need to compute the hash of every <script> tag, and output the hash in the CSP header as a script-src . If you place a literal <script> tag in your ERB files, Rails has no way of knowing about that tag, and it won't compute the hash or add it to your header.

Rails (to the best of my knowledge) does not support hashes as a source. You can use the secure-headers gem, which provides a hashed_javascript_tag method to use instead of <script> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM