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
def csp_nonce_placeholder
@csp_nonce_placeholder ||=
begin
placeholder = "[[csp_nonce_placeholder_#{SecureRandom.hex}]]"
response.headers["Discourse-CSP-Nonce-Placeholder"] = placeholder
placeholder
end
response.headers[
::Middleware::CspScriptNonceInjector::PLACEHOLDER_HEADER
] ||= "[[csp_nonce_placeholder_#{SecureRandom.hex}]]"
end
def shared_session_key

View File

@ -2,6 +2,8 @@
module Middleware
class CspScriptNonceInjector
PLACEHOLDER_HEADER = "Discourse-CSP-Nonce-Placeholder"
def initialize(app, settings = {})
@app = app
end
@ -9,7 +11,7 @@ module Middleware
def 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)
parts = []
response.each { |part| parts << part.to_s.gsub(nonce_placeholder, nonce) }