Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 5.2: Best practice for setting CSP nonce

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>
like image 884
AirWick219 Avatar asked Feb 04 '19 22:02

AirWick219


1 Answers

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 -%>
like image 55
AirWick219 Avatar answered Nov 03 '22 23:11

AirWick219