I’m working on a Ruby on Rails 7.1 application and encountering an issue with Content Security Policy (CSP). When I make an AJAX request using get() in a .js.erb file, I get the following error in the browser console:
application-8846f773213213213332321321321323.js:83759 U**ncaught EvalError: Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive:** "script-src 'unsafe-inline' 'nonce-ewqe321PNhjdasdafdse2q3eurY42hk10fVB7en='".
The error occurs in this create.js.erb file:
get("<%= action_button_index_path(object_type: @object_type, format: :js) %>");
This is my CSP configuration in config/application.rb:
Rails.application.configure do
config.content_security_policy do |policy|
policy.default_src :self, :unsafe_inline
policy.font_src :self, "https://fonts.gstatic.com"
policy.frame_src :self
policy.script_src :unsafe_inline
policy.script_src_elem :self, :unsafe_inline, "https://www.recaptcha.net"
policy.connect_src :self, "*.nr-data.net"m"
policy.style_src_elem :self, :unsafe_inline, "https://fonts.googleapis.com", "https://www.gstatic.com"
policy.img_src :self, :unsafe_inline, "data:"
policy.object_src :none
policy.base_uri :self
policy.report_uri "/csp_violation"
end
config.content_security_policy_nonce_generator = ->(_request) { SecureRandom.base64(32) }
config.content_security_policy_nonce_directives = %w[script-src]
config.content_security_policy_report_only = false
end
I want to avoid adding ‘unsafe-eval’ to my CSP because it weakens security against XSS attacks. How can I refactor my code to load or execute the JavaScript from widget_button_index_path(widget_type: @widget_type, format: :js) without requiring ‘unsafe-eval’? Ideally, I’d like a solution that works with my current setup (Rails, jQuery, and CSP with nonce).
Any suggestions or examples would be greatly appreciated! Thanks!