Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion lib/secure_headers/view_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,11 @@ def nonced_stylesheet_pack_tag(*args, &block)
# Public: use the content security policy nonce for this request directly.
# Instructs secure_headers to append a nonce to style/script-src directives.
#
# type - (optional) The type of nonce to generate (:script or :style).
# Defaults to :script to match Rails' content_security_policy_nonce behavior.
#
# Returns a non-html-safe nonce value.
def _content_security_policy_nonce(type)
def _content_security_policy_nonce(type = :script)
case type
when :script
SecureHeaders.content_security_policy_script_nonce(@_request)
Expand Down
55 changes: 55 additions & 0 deletions spec/lib/secure_headers/view_helpers_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -188,5 +188,60 @@ module SecureHeaders
expect(env[ContentSecurityPolicyConfig::HEADER_NAME]).not_to match(/rails-nonce/)
end
end

it "supports calling content_security_policy_nonce without parameters (Rails compatibility)" do
allow(SecureRandom).to receive(:base64).and_return("xyz789")

# Create a test class that simulates Rails-compatible usage
# where content_security_policy_nonce is called without any parameters
test_class = Class.new(Message) do
def self.template
<<-TEMPLATE
<script nonce="<%= content_security_policy_nonce %>">
console.log("test")
</script>
TEMPLATE
end
end

message = test_class.new(request)
result = message.result

# The nonce should be included in the rendered output
expect(result).to include('nonce="xyz789"')

# Call middleware to generate headers
_, env = middleware.call request.env

# The nonce should be added to script-src in the CSP header (default behavior)
expect(env[ContentSecurityPolicyConfig::HEADER_NAME]).to match(/script-src[^;]*'nonce-xyz789'/)
end

it "supports calling content_security_policy_nonce with :style parameter" do
allow(SecureRandom).to receive(:base64).and_return("style123")

# Create a test class that calls content_security_policy_nonce with :style
test_class = Class.new(Message) do
def self.template
<<-TEMPLATE
<style nonce="<%= content_security_policy_nonce(:style) %>">
body { background: red; }
</style>
TEMPLATE
end
end

message = test_class.new(request)
result = message.result

# The nonce should be included in the rendered output
expect(result).to include('nonce="style123"')

# Call middleware to generate headers
_, env = middleware.call request.env

# The nonce should be added to style-src in the CSP header
expect(env[ContentSecurityPolicyConfig::HEADER_NAME]).to match(/style-src[^;]*'nonce-style123'/)
end
end
end