From 79dfb3a372a7cde637ea34fbb2f563f0b15ba475 Mon Sep 17 00:00:00 2001 From: Tyler Rick Date: Tue, 10 Sep 2019 15:59:30 -0700 Subject: [PATCH] Automatically add a nonce to script tag if a csp-nonce meta tag is available to get it from Resolves #100 --- lib/xray/middleware.rb | 7 ++++++- spec/dummy/app/controllers/application_controller.rb | 8 ++++++++ spec/dummy/app/views/layouts/application.html.erb | 1 + spec/dummy/config/initializers/content_security_policy.rb | 5 +++++ spec/xray/middleware_spec.rb | 6 ++++++ 5 files changed, 26 insertions(+), 1 deletion(-) create mode 100644 spec/dummy/config/initializers/content_security_policy.rb diff --git a/lib/xray/middleware.rb b/lib/xray/middleware.rb index 9079644..d55e1a9 100644 --- a/lib/xray/middleware.rb +++ b/lib/xray/middleware.rb @@ -110,10 +110,15 @@ def script_matcher(script_name) /x end + def nonce_from_meta_tag(html) + (match = html.match(/ "all" %> <%= javascript_include_tag "application" %> <%= csrf_meta_tags %> + <%= csp_meta_tag %> diff --git a/spec/dummy/config/initializers/content_security_policy.rb b/spec/dummy/config/initializers/content_security_policy.rb new file mode 100644 index 0000000..f89b30f --- /dev/null +++ b/spec/dummy/config/initializers/content_security_policy.rb @@ -0,0 +1,5 @@ +Rails.application.config.content_security_policy do |policy| + # Empty +end + +Rails.application.config.content_security_policy_nonce_generator = -> request { SecureRandom.base64(16) } diff --git a/spec/xray/middleware_spec.rb b/spec/xray/middleware_spec.rb index 84ef1bd..1f9f92e 100644 --- a/spec/xray/middleware_spec.rb +++ b/spec/xray/middleware_spec.rb @@ -95,6 +95,12 @@ def mock_response(status, content_type, body) expect(page).to have_selector('script[src^="/assets/xray"]') end + it "adds nonce to the script tag" do + visit '/' + expect(page).to have_selector('script[src^="/assets/xray"][nonce]') + expect(page.find('script[src^="/assets/xray"]')[:nonce]).to eq page.find('meta[name="csp-nonce"]')[:content] + end + it "injects the xray bar into the response" do visit '/' expect(page).to have_selector('#xray-bar')