DEV: Memoize CSP nonce placeholder on response (#25724)

That way, the same value is used even if the helper is called in the context of different controllers

Followup to c8a1b49ddd
This commit is contained in:
David Taylor 2024-02-16 12:15:55 +00:00 committed by GitHub
parent b1f74ab59e
commit 1672a24490
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 6 additions and 7 deletions

View File

@ -66,12 +66,9 @@ module ApplicationHelper
end end
def csp_nonce_placeholder def csp_nonce_placeholder
@csp_nonce_placeholder ||= response.headers[
begin ::Middleware::CspScriptNonceInjector::PLACEHOLDER_HEADER
placeholder = "[[csp_nonce_placeholder_#{SecureRandom.hex}]]" ] ||= "[[csp_nonce_placeholder_#{SecureRandom.hex}]]"
response.headers["Discourse-CSP-Nonce-Placeholder"] = placeholder
placeholder
end
end end
def shared_session_key def shared_session_key

View File

@ -2,6 +2,8 @@
module Middleware module Middleware
class CspScriptNonceInjector class CspScriptNonceInjector
PLACEHOLDER_HEADER = "Discourse-CSP-Nonce-Placeholder"
def initialize(app, settings = {}) def initialize(app, settings = {})
@app = app @app = app
end end
@ -9,7 +11,7 @@ module Middleware
def call(env) def call(env)
status, headers, response = @app.call(env) status, headers, response = @app.call(env)
if nonce_placeholder = headers.delete("Discourse-CSP-Nonce-Placeholder") if nonce_placeholder = headers.delete(PLACEHOLDER_HEADER)
nonce = SecureRandom.alphanumeric(25) nonce = SecureRandom.alphanumeric(25)
parts = [] parts = []
response.each { |part| parts << part.to_s.gsub(nonce_placeholder, nonce) } response.each { |part| parts << part.to_s.gsub(nonce_placeholder, nonce) }