Skip to content

Commit

Permalink
DEV: Memoize CSP nonce placeholder on response (discourse#25724)
Browse files Browse the repository at this point in the history
That way, the same value is used even if the helper is called in the context of different controllers

Followup to c8a1b49
  • Loading branch information
davidtaylorhq authored Feb 16, 2024
1 parent b1f74ab commit 1672a24
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 7 deletions.
9 changes: 3 additions & 6 deletions app/helpers/application_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -66,12 +66,9 @@ def google_tag_manager_json
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
Expand Down
4 changes: 3 additions & 1 deletion lib/middleware/csp_script_nonce_injector.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,16 @@

module Middleware
class CspScriptNonceInjector
PLACEHOLDER_HEADER = "Discourse-CSP-Nonce-Placeholder"

def initialize(app, settings = {})
@app = app
end

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) }
Expand Down

0 comments on commit 1672a24

Please sign in to comment.