From c1ec80a5f0dea47e7af0e5595363e02ab23efcf4 Mon Sep 17 00:00:00 2001 From: Martin Emde Date: Wed, 31 Jan 2024 12:34:05 -0800 Subject: [PATCH] Force session to exist so nonce exists --- config/initializers/content_security_policy.rb | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/config/initializers/content_security_policy.rb b/config/initializers/content_security_policy.rb index cb9ccb432c6..fda3014069a 100644 --- a/config/initializers/content_security_policy.rb +++ b/config/initializers/content_security_policy.rb @@ -11,7 +11,6 @@ "https://*.fastly-insights.com", "https://avatars.githubusercontent.com" policy.object_src :none policy.script_src :self, - :unsafe_inline, "https://secure.gaug.es", "https://www.fastly-insights.com", "https://unpkg.com/@hotwired/stimulus/dist/stimulus.umd.js", @@ -50,7 +49,12 @@ end # Generate session nonces for permitted importmap, inline scripts, and inline styles. -Rails.application.config.content_security_policy_nonce_generator = ->(request) { request.session.id.to_s } +Rails.application.config.content_security_policy_nonce_generator = lambda { |request| + # Suggested nonce generator doesn't work on first page load https://github.com/rails/rails/issues/48463 + # Related PR attempting to fix: https://github.com/rails/rails/pull/48510 + request.session.update({}) # force session to exist + request.session.id.to_s.presence || raise("No session ID available in #{request.inspect}") +} Rails.application.config.content_security_policy_nonce_directives = %w[script-src style-src] # Report CSP violations to a specified URI. See: