Skip to content

Commit

Permalink
Merge pull request #44635 from imtayadeway/tjw/api-csp-i
Browse files Browse the repository at this point in the history
Generate content security policy for non-HTML responses
  • Loading branch information
tenderlove committed Apr 12, 2022
1 parent 459e7cf commit d225311
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 9 deletions.
5 changes: 4 additions & 1 deletion actionpack/CHANGELOG.md
@@ -1,8 +1,11 @@
* Allow Content Security Policy DSL to generate for API responses.

*Tim Wade*

## Rails 5.2.7 (March 10, 2022) ##

* No changes.


## Rails 5.2.6.3 (March 08, 2022) ##

* No changes.
Expand Down
Expand Up @@ -17,7 +17,6 @@ def call(env)
request = ActionDispatch::Request.new env
_, headers, _ = response = @app.call(env)

return response unless html_response?(headers)
return response if policy_present?(headers)

if policy = request.content_security_policy
Expand All @@ -30,13 +29,6 @@ def call(env)
end

private

def html_response?(headers)
if content_type = headers[CONTENT_TYPE]
content_type =~ /html/
end
end

def header_name(request)
if request.content_security_policy_report_only
POLICY_REPORT_ONLY
Expand Down
15 changes: 15 additions & 0 deletions actionpack/test/dispatch/content_security_policy_test.rb
Expand Up @@ -343,6 +343,11 @@ class PolicyController < ActionController::Base

content_security_policy_report_only only: :report_only

content_security_policy only: :api do |p|
p.default_src :none
p.frame_ancestors :none
end

def index
head :ok
end
Expand All @@ -367,6 +372,10 @@ def no_policy
head :ok
end

def api
render json: {}
end

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

Expand Down Expand Up @@ -448,6 +458,11 @@ def test_generates_no_content_security_policy
assert_nil response.headers["Content-Security-Policy-Report-Only"]
end

def test_generates_api_security_policy
get "/api"
assert_policy "default-src 'none'; frame-ancestors 'none'"
end

private

def assert_policy(expected, report_only: false)
Expand Down

0 comments on commit d225311

Please sign in to comment.