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:
parent
b1f74ab59e
commit
1672a24490
|
@ -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
|
||||||
|
|
|
@ -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) }
|
||||||
|
|
Loading…
Reference in New Issue