Skip to content

Commit

Permalink
Merge pull request #680 from abrom/main
Browse files Browse the repository at this point in the history
Add support for `Content-Security-Policy-Report-Only` nonces
  • Loading branch information
flyerhzm committed Oct 6, 2023
2 parents 90b2c1a + 0b48242 commit 4f81fa9
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
3 changes: 2 additions & 1 deletion lib/bullet/rack.rb
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,8 @@ def xhr_script(nonce = nil)
end

def with_security_policy_nonce(headers)
matched = (headers['Content-Security-Policy'] || '').match(NONCE_MATCHER)
csp = headers['Content-Security-Policy'] || headers['Content-Security-Policy-Report-Only'] || ''
matched = csp.match(NONCE_MATCHER)
nonce = matched[:nonce] if matched

if nonce
Expand Down
18 changes: 18 additions & 0 deletions spec/bullet/rack_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,24 @@ module Bullet
expect(headers['Content-Length']).to eq(size.to_s)
end

it 'should include CSP nonce in inline script if console_enabled and a CSP (report only) is applied' do
allow(Bullet).to receive(:add_footer).at_least(:once).and_return(true)
expect(Bullet).to receive(:console_enabled?).and_return(true)
allow(middleware).to receive(:xhr_script).and_call_original

nonce = '+t9/wTlgG6xbHxXYUaDNzQ=='
app.headers = {
'Content-Type' => 'text/html',
'Content-Security-Policy-Report-Only' =>
"default-src 'self' https:; script-src 'self' https: 'nonce-#{nonce}'"
}

_, headers, response = middleware.call('Content-Type' => 'text/html')

size = 56 + middleware.send(:footer_note).length + middleware.send(:xhr_script, nonce).length
expect(headers['Content-Length']).to eq(size.to_s)
end

it 'should change response body for html safe string if console_enabled is true' do
expect(Bullet).to receive(:console_enabled?).and_return(true)
app.response =
Expand Down

0 comments on commit 4f81fa9

Please sign in to comment.