Skip to content

Commit

Permalink
Fix Mime::Type.parse for HTTP Accept with parameters
Browse files Browse the repository at this point in the history
Fixes MIME parsing raising errors on valid parameters #51594.

Mime type lookups were updated to handle custom registered types as part of #48397.

This fix the strips out custom media range parameters before falling back to the default type creation.
  • Loading branch information
notchairmk committed Apr 22, 2024
1 parent d462fb5 commit 5889b86
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 1 deletion.
4 changes: 4 additions & 0 deletions actionpack/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
* Fix `Mime::Type.parse` handling type parameters for HTTP Accept headers.

*Taylor Chaparro*

* Fix the error page that is displayed when a view template is missing to account for nested controller paths in the
suggested correct location for the missing template.

Expand Down
5 changes: 4 additions & 1 deletion actionpack/lib/action_dispatch/http/mime_type.rb
Original file line number Diff line number Diff line change
Expand Up @@ -165,8 +165,11 @@ def register_callback(&block)
end

def lookup(string)
return LOOKUP[string] if LOOKUP.key?(string)

# fallback to the media-type without parameters if it was not found
LOOKUP[string] || LOOKUP[string.split(";", 2)[0]&.rstrip] || Type.new(string)
string = string.split(";", 2)[0]&.rstrip
LOOKUP[string] || Type.new(string)
end

def lookup_by_extension(extension)
Expand Down
12 changes: 12 additions & 0 deletions actionpack/test/dispatch/mime_type_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,12 @@ class MimeTypeTest < ActiveSupport::TestCase
assert_equal expect.map(&:to_s), Mime::Type.parse(accept).map(&:to_s)
end

test "parse with q and media type parameters" do
accept = "text/xml,application/xhtml+xml,text/yaml; q=0.3,application/xml,text/html; q=0.8,image/png,text/plain; q=0.5,application/pdf,*/*; encoding=UTF-8; q=0.2"
expect = [Mime[:html], Mime[:xml], Mime[:png], Mime[:pdf], Mime[:text], Mime[:yaml], "*/*"]
assert_equal expect.map(&:to_s), Mime::Type.parse(accept).map(&:to_s)
end

test "parse single media range with q" do
accept = "text/html;q=0.9"
expect = [Mime[:html]]
Expand All @@ -92,6 +98,12 @@ class MimeTypeTest < ActiveSupport::TestCase
assert_equal expect, Mime::Type.parse(accept)
end

test "parse wildcard with arbitrary media type parameters" do
accept = '*/*; boundary="simple"'
expect = ["*/*"]
assert_equal expect, Mime::Type.parse(accept)
end

# Accept header send with user HTTP_USER_AGENT: Sunrise/0.42j (Windows XP)
test "parse broken acceptlines" do
accept = "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/*,,*/*;q=0.5"
Expand Down

0 comments on commit 5889b86

Please sign in to comment.