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

Generate content security policy for non-HTML responses #44635

Merged
merged 2 commits into from Mar 8, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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*
imtayadeway marked this conversation as resolved.
Show resolved Hide resolved

* Fix `authenticate_with_http_basic` to allow for missing password.

Before Rails 7.0 it was possible to handle basic authentication with only a username.
Expand Down
Expand Up @@ -35,7 +35,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 @@ -49,12 +48,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 @@ -403,6 +403,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 @@ -431,6 +436,10 @@ def no_policy
head :ok
end

def api
render json: {}
end

private
def condition?
params[:condition] == "true"
Expand All @@ -447,6 +456,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 @@ -518,6 +528,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