Turbolinks broken by default with a secure CSP [SCI-8583] (#5529)

* Fix broken Turbolinks with CSP nonce [SCI-8583]
This commit is contained in:
Soufiane 2023-05-31 15:28:16 +02:00 committed by GitHub
parent caa160e7c6
commit b40c750965
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 20 additions and 3 deletions

View file

@ -0,0 +1,10 @@
document.addEventListener('turbolinks:request-start', function(event) {
var xhr = event.data.xhr;
xhr.setRequestHeader('X-Turbolinks-Nonce', $('meta[name="csp-nonce"]').prop('content'));
});
document.addEventListener('turbolinks:before-cache', function() {
$('script[nonce]').each(function(_index, element) {
$(element).attr('nonce', element.nonce);
});
});

View file

@ -12,7 +12,7 @@
<% end %>
<%= stylesheet_link_tag "tailwind", "data-turbo-track": "reload" %>
<%= stylesheet_link_tag 'application', media: 'all' %>
<%= csp_meta_tag %>
<% if ::NewRelic::Agent.instance.started? %>
<%= ::NewRelic::Agent.browser_timing_header(controller.request.content_security_policy_nonce) %>
<% end %>

View file

@ -18,8 +18,15 @@ Rails.application.config.content_security_policy do |policy|
# policy.report_uri "/csp-violation-report-endpoint"
end
# If you are using UJS then enable automatic nonce generation
Rails.application.config.content_security_policy_nonce_generator = ->_request { SecureRandom.base64(16) }
# https://discuss.rubyonrails.org/t/turbolinks-broken-by-default-with-a-secure-csp/74790
Rails.application.config.content_security_policy_nonce_generator = ->(request) do
# use the same csp nonce for turbolinks requests
if request.env['HTTP_TURBOLINKS_REFERRER'].present?
request.env['HTTP_X_TURBOLINKS_NONCE']
else
SecureRandom.base64(16)
end
end
# Set the nonce only to specific directives
Rails.application.config.content_security_policy_nonce_directives = %w(script-src)