From ceeef26fd43ab6daff19042db73abd49d9ed5d61 Mon Sep 17 00:00:00 2001 From: George Claghorn Date: Fri, 8 Mar 2019 15:25:24 -0500 Subject: Read the CSP nonce on page load Turbolinks replaces the CSP nonce tag on page change, but inline scripts inserted by UJS need the nonce from the initial page load. In general, it doesn't matter to UJS if the nonce changes after the page loads: only the initial value is relevant. --- actionview/app/assets/javascripts/rails-ujs/start.coffee | 2 ++ actionview/app/assets/javascripts/rails-ujs/utils/csp.coffee | 12 ++++++++---- 2 files changed, 10 insertions(+), 4 deletions(-) (limited to 'actionview/app') diff --git a/actionview/app/assets/javascripts/rails-ujs/start.coffee b/actionview/app/assets/javascripts/rails-ujs/start.coffee index 5c1214df59..0347058195 100644 --- a/actionview/app/assets/javascripts/rails-ujs/start.coffee +++ b/actionview/app/assets/javascripts/rails-ujs/start.coffee @@ -2,6 +2,7 @@ fire, delegate getData, $ refreshCSRFTokens, CSRFProtection + loadCSPNonce enableElement, disableElement, handleDisabledElement handleConfirm, preventInsignificantClick handleRemote, formSubmitButtonClick, @@ -67,6 +68,7 @@ Rails.start = -> delegate document, Rails.formInputClickSelector, 'click', formSubmitButtonClick document.addEventListener('DOMContentLoaded', refreshCSRFTokens) + document.addEventListener('DOMContentLoaded', loadCSPNonce) window._rails_loaded = true if window.Rails is Rails and fire(document, 'rails:attachBindings') diff --git a/actionview/app/assets/javascripts/rails-ujs/utils/csp.coffee b/actionview/app/assets/javascripts/rails-ujs/utils/csp.coffee index 8d2d6ce447..a33f531375 100644 --- a/actionview/app/assets/javascripts/rails-ujs/utils/csp.coffee +++ b/actionview/app/assets/javascripts/rails-ujs/utils/csp.coffee @@ -1,4 +1,8 @@ -# Content-Security-Policy nonce for inline scripts -cspNonce = Rails.cspNonce = -> - meta = document.querySelector('meta[name=csp-nonce]') - meta and meta.content +nonce = null + +Rails.loadCSPNonce = -> + nonce = document.querySelector("meta[name=csp-nonce]")?.content + +# Returns the Content-Security-Policy nonce for inline scripts. +Rails.cspNonce = -> + nonce ? Rails.loadCSPNonce() -- cgit v1.2.3