Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add new APIs to customize content security policy for non-HTML responses #39398

Open
wants to merge 12 commits into
base: main
Choose a base branch
from
3 changes: 3 additions & 0 deletions actionpack/CHANGELOG.md
@@ -1,3 +1,6 @@
* Allow Content Security Policy DSL to generate for API responses.
*Tim Wade*
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's describe this a bit more. The summary in the pull request is great! We'll now send CSP headers with all responses, not just HTML, to protect API responses that could be loaded in a browser.


* When multiple domains are specified for a cookie, a domain will now be
jeremy marked this conversation as resolved.
Show resolved Hide resolved
chosen only if it is equal to or is a superdomain of the request host.

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 @@ -31,12 +30,6 @@ def call(env)
end

private
def html_response?(headers)
if content_type = headers[CONTENT_TYPE]
/html/.match?(content_type)
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 @@ -377,6 +377,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 Down Expand Up @@ -405,6 +410,10 @@ def no_policy
head :ok
end

def api
render json: {}
end

private
def condition?
params[:condition] == "true"
Expand All @@ -421,6 +430,7 @@ def condition?
get "/script-src", to: "policy#script_src"
get "/style-src", to: "policy#style_src"
get "/no-policy", to: "policy#no_policy"
get "/api", to: "policy#api"
end
end

Expand Down Expand Up @@ -492,6 +502,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)
assert_response :success
Expand Down