Rails 5.2: Best practice for setting CSP nonce
Asked Answered
S

1

10

Our application is on Rails 5.2 and it is serving assets with webpacker without the asset pipeline. I was wondering what is the best way to set the nonce attributes on the script tag.

In content_security_policy.rb, there is a content_security_policy_nonce_generator for UJS, I was wondering if I can still use that without any side effect. The following work and I was just wondering what is the best practice for doing something like this.

#initializers/content_security_policy.rb

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

In application.html.erb, if I want to have nonce on the script tag, I will have to get it from the request. According here: https://api.rubyonrails.org/classes/ActionDispatch/ContentSecurityPolicy/Request.html#method-i-content_security_policy_nonce

#app/views/layouts/application.html.erb

<!DOCTYPE html>
<html dir="ltr">
  <head>
    <title>FruitsMarket</title>
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>

    <%= stylesheet_pack_tag 'application' %>
    <%= javascript_pack_tag 'polyfills' %>
    <%= javascript_pack_tag 'application' %>
    <script type="text/javascript" nonce=<%= request.content_security_policy_nonce %>>
      alert('hi');
    </script>
  </head>

  <body>
    <%= yield %>
  </body>
</html>
Spelt answered 4/2, 2019 at 22:52 Comment(0)
S
15

Found it https://api.rubyonrails.org/classes/ActionView/Helpers/JavaScriptHelper.html turns out there is a ruby view helper for that

<%= javascript_tag nonce: true do -%>
  alert('All is good')
<% end -%>
Spelt answered 12/2, 2019 at 22:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.