From f080d8f5d0a1a319896f19fc4ed222b37cc44534 Mon Sep 17 00:00:00 2001 From: Earlopain <14981592+Earlopain@users.noreply.github.com> Date: Mon, 4 Mar 2024 09:12:35 +0100 Subject: [PATCH] Fix crash for invalid Content-Type in ShowExceptions middleware --- .../action_dispatch/middleware/show_exceptions.rb | 14 +++++++++++--- .../test/application/middleware/exceptions_test.rb | 13 +++++++++++++ 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/actionpack/lib/action_dispatch/middleware/show_exceptions.rb b/actionpack/lib/action_dispatch/middleware/show_exceptions.rb index 5f7368de56..d07f4003b1 100644 --- a/actionpack/lib/action_dispatch/middleware/show_exceptions.rb +++ b/actionpack/lib/action_dispatch/middleware/show_exceptions.rb @@ -67,9 +67,17 @@ def render_exception(request, wrapper) def fallback_to_html_format_if_invalid_mime_type(request) # If the MIME type for the request is invalid then the @exceptions_app may not # be able to handle it. To make it easier to handle, we switch to HTML. - request.formats - rescue ActionDispatch::Http::MimeNegotiation::InvalidType - request.set_header "HTTP_ACCEPT", "text/html" + begin + request.content_mime_type + rescue ActionDispatch::Http::MimeNegotiation::InvalidType + request.set_header "CONTENT_TYPE", "text/html" + end + + begin + request.formats + rescue ActionDispatch::Http::MimeNegotiation::InvalidType + request.set_header "HTTP_ACCEPT", "text/html" + end end def pass_response(status) diff --git a/railties/test/application/middleware/exceptions_test.rb b/railties/test/application/middleware/exceptions_test.rb index 208c290ac4..c1da558fdf 100644 --- a/railties/test/application/middleware/exceptions_test.rb +++ b/railties/test/application/middleware/exceptions_test.rb @@ -82,6 +82,7 @@ def not_acceptable app_file "config/routes.rb", <<-RUBY Rails.application.routes.draw do get "/foo", to: "foo#index" + post "/foo", to: "foo#index" match "/406", to: "foo#not_acceptable", via: :all end RUBY @@ -93,6 +94,18 @@ def not_acceptable get "/foo", {}, { "HTTP_ACCEPT" => "invalid", "HTTPS" => "on" } assert_equal 406, last_response.status assert_not_equal "rendering index!", last_response.body + + get "/foo", {}, { "CONTENT_TYPE" => "invalid", "HTTPS" => "on" } + assert_equal 406, last_response.status + assert_not_equal "rendering index!", last_response.body + + get "/foo", {}, { "HTTP_ACCEPT" => "invalid", "CONTENT_TYPE" => "invalid", "HTTPS" => "on" } + assert_equal 406, last_response.status + assert_not_equal "rendering index!", last_response.body + + post "/foo", {}, { "HTTP_ACCEPT" => "invalid", "CONTENT_TYPE" => "invalid", "HTTPS" => "on" } + assert_equal 406, last_response.status + assert_not_equal "rendering index!", last_response.body end test "uses custom exceptions app" do