Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Add the ability to disable the global CSP in a controller
e.g:

    class LegacyPagesController < ApplicationController
      content_security_policy false, only: :index
    end
  • Loading branch information
pixeltrix committed Mar 8, 2018
1 parent 42fc4a5 commit 619b1b6
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 1 deletion.
8 changes: 8 additions & 0 deletions actionpack/CHANGELOG.md
@@ -1,3 +1,11 @@
* Add the ability to disable the global CSP in a controller, e.g:

class LegacyPagesController < ApplicationController
content_security_policy false, only: :index
end

*Andrew White*

* Add alias method `to_hash` to `to_h` for `cookies`.
Add alias method `to_h` to `to_hash` for `session`.

Expand Down
Expand Up @@ -14,13 +14,17 @@ module ContentSecurityPolicy
end

module ClassMethods
def content_security_policy(**options, &block)
def content_security_policy(enabled = true, **options, &block)
before_action(options) do
if block_given?
policy = request.content_security_policy.clone
yield policy
request.content_security_policy = policy
end

unless enabled
request.content_security_policy = nil
end
end
end

Expand Down
14 changes: 14 additions & 0 deletions actionpack/test/dispatch/content_security_policy_test.rb
Expand Up @@ -258,6 +258,8 @@ class PolicyController < ActionController::Base
p.script_src :self
end

content_security_policy(false, only: :no_policy)

content_security_policy_report_only only: :report_only

def index
Expand All @@ -280,6 +282,10 @@ def script_src
head :ok
end

def no_policy
head :ok
end

private
def condition?
params[:condition] == "true"
Expand All @@ -294,6 +300,7 @@ def condition?
get "/conditional", to: "policy#conditional"
get "/report-only", to: "policy#report_only"
get "/script-src", to: "policy#script_src"
get "/no-policy", to: "policy#no_policy"
end
end

Expand Down Expand Up @@ -353,6 +360,13 @@ def test_adds_nonce_to_script_src_content_security_policy
assert_policy "script-src 'self' 'nonce-iyhD0Yc0W+c='"
end

def test_generates_no_content_security_policy
get "/no-policy"

assert_nil response.headers["Content-Security-Policy"]
assert_nil response.headers["Content-Security-Policy-Report-Only"]
end

private

def env_config
Expand Down

0 comments on commit 619b1b6

Please sign in to comment.