Skip to content

Commit

Permalink
Allow response.content_security_plugin = false to avoid setting polic…
Browse files Browse the repository at this point in the history
…y in content_security_policy plugin

This is useful if you are serving multiple subdomains in the same
application, and want only want to use the policy in a subset
of the subdomains.
  • Loading branch information
jeremyevans committed Nov 1, 2024
1 parent 13ad4ed commit 7ba726b
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 3 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
= master

* Allow response.content_security_plugin = false to avoid setting policy in content_security_policy plugin (jeremyevans)

= 3.85.0 (2024-10-11)

* Avoid deprecation warning in public plugin when using Ruby 3.4.0-preview2 (jeremyevans)
Expand Down
20 changes: 17 additions & 3 deletions lib/roda/plugins/content_security_policy.rb
Original file line number Diff line number Diff line change
Expand Up @@ -293,23 +293,37 @@ def content_security_policy
end

module ResponseMethods
# Set the content security policy for the response. Can be set to false
# to disable setting the content-security-policy header in the response.
attr_writer :content_security_policy

# Unset any content security policy when reinitializing
def initialize
super
@content_security_policy &&= nil
@content_security_policy = nil
end

# The current content security policy to be used for this response.
def content_security_policy
@content_security_policy ||= roda_class.opts[:content_security_policy].dup
return @content_security_policy unless @content_security_policy.nil?
@content_security_policy = roda_class.opts[:content_security_policy].dup
end

private

# Set the appropriate content security policy header.
def set_default_headers
super
(@content_security_policy || roda_class.opts[:content_security_policy]).set_header(headers)

csp = @content_security_policy

if csp.nil?
csp = roda_class.opts[:content_security_policy]
end

if csp
csp.set_header(headers)
end
end
end
end
Expand Down
8 changes: 8 additions & 0 deletions spec/plugin/content_security_policy_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,14 @@
header(RodaResponseHeaders::CONTENT_SECURITY_POLICY).must_equal "default_src 'none';"
end

it "should not set policy if response.content_security_policy = false" do
app(:content_security_policy) do |r|
response.content_security_policy = false
''
end
header(RodaResponseHeaders::CONTENT_SECURITY_POLICY).must_be_nil
end

it "works with error_handler" do
app(:bare) do
plugin(:error_handler){|_| ''}
Expand Down

0 comments on commit 7ba726b

Please sign in to comment.