Skip to content

Commit 08b49f1

Browse files
authored
Merge pull request rails#51247 from Earlopain/fix-51228
Fix crash for invalid Content-Type in ShowExceptions middleware
2 parents d514a31 + f080d8f commit 08b49f1

File tree

2 files changed

+24
-3
lines changed

2 files changed

+24
-3
lines changed

actionpack/lib/action_dispatch/middleware/show_exceptions.rb

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -67,9 +67,17 @@ def render_exception(request, wrapper)
6767
def fallback_to_html_format_if_invalid_mime_type(request)
6868
# If the MIME type for the request is invalid then the @exceptions_app may not
6969
# be able to handle it. To make it easier to handle, we switch to HTML.
70-
request.formats
71-
rescue ActionDispatch::Http::MimeNegotiation::InvalidType
72-
request.set_header "HTTP_ACCEPT", "text/html"
70+
begin
71+
request.content_mime_type
72+
rescue ActionDispatch::Http::MimeNegotiation::InvalidType
73+
request.set_header "CONTENT_TYPE", "text/html"
74+
end
75+
76+
begin
77+
request.formats
78+
rescue ActionDispatch::Http::MimeNegotiation::InvalidType
79+
request.set_header "HTTP_ACCEPT", "text/html"
80+
end
7381
end
7482

7583
def pass_response(status)

railties/test/application/middleware/exceptions_test.rb

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,7 @@ def not_acceptable
8282
app_file "config/routes.rb", <<-RUBY
8383
Rails.application.routes.draw do
8484
get "/foo", to: "foo#index"
85+
post "/foo", to: "foo#index"
8586
match "/406", to: "foo#not_acceptable", via: :all
8687
end
8788
RUBY
@@ -93,6 +94,18 @@ def not_acceptable
9394
get "/foo", {}, { "HTTP_ACCEPT" => "invalid", "HTTPS" => "on" }
9495
assert_equal 406, last_response.status
9596
assert_not_equal "rendering index!", last_response.body
97+
98+
get "/foo", {}, { "CONTENT_TYPE" => "invalid", "HTTPS" => "on" }
99+
assert_equal 406, last_response.status
100+
assert_not_equal "rendering index!", last_response.body
101+
102+
get "/foo", {}, { "HTTP_ACCEPT" => "invalid", "CONTENT_TYPE" => "invalid", "HTTPS" => "on" }
103+
assert_equal 406, last_response.status
104+
assert_not_equal "rendering index!", last_response.body
105+
106+
post "/foo", {}, { "HTTP_ACCEPT" => "invalid", "CONTENT_TYPE" => "invalid", "HTTPS" => "on" }
107+
assert_equal 406, last_response.status
108+
assert_not_equal "rendering index!", last_response.body
96109
end
97110

98111
test "uses custom exceptions app" do

0 commit comments

Comments
 (0)