Skip to content

Commit

Permalink
Merge pull request rails#35669 from cpruitt/update-mime-type-regexp
Browse files Browse the repository at this point in the history
Update regular expression for checking valid MIME type
  • Loading branch information
tenderlove authored Mar 19, 2019
2 parents 04ae0b0 + ab38aa4 commit 12a1a66
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
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 @@ -223,7 +223,10 @@ def unregister(symbol)
attr_reader :hash

MIME_NAME = "[a-zA-Z0-9][a-zA-Z0-9#{Regexp.escape('!#$&-^_.+')}]{0,126}"
MIME_REGEXP = /\A(?:\*\/\*|#{MIME_NAME}\/(?:\*|#{MIME_NAME}))\z/
MIME_PARAMETER_KEY = "[a-zA-Z0-9][a-zA-Z0-9#{Regexp.escape('!#$&-^_.+')}]{0,126}"
MIME_PARAMETER_VALUE = "#{Regexp.escape('"')}?[a-zA-Z0-9][a-zA-Z0-9#{Regexp.escape('!#$&-^_.+')}]{0,126}#{Regexp.escape('"')}?"
MIME_PARAMETER = "\s*\;\s+#{MIME_PARAMETER_KEY}(?:\=#{MIME_PARAMETER_VALUE})?"
MIME_REGEXP = /\A(?:\*\/\*|#{MIME_NAME}\/(?:\*|#{MIME_NAME})(?:\s*#{MIME_PARAMETER}\s*)*)\z/

class InvalidMimeType < StandardError; end

Expand Down
15 changes: 15 additions & 0 deletions actionpack/test/dispatch/mime_type_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,13 @@ class MimeTypeTest < ActiveSupport::TestCase
assert_equal "video/*", Mime::Type.new("video/*").to_s
end

test "can be initialized with parameters" do
assert_equal "text/html; parameter", Mime::Type.new("text/html; parameter").to_s
assert_equal "text/html; parameter=abc", Mime::Type.new("text/html; parameter=abc").to_s
assert_equal 'text/html; parameter="abc"', Mime::Type.new('text/html; parameter="abc"').to_s
assert_equal 'text/html; parameter=abc; parameter2="xyz"', Mime::Type.new('text/html; parameter=abc; parameter2="xyz"').to_s
end

test "invalid mime types raise error" do
assert_raises Mime::Type::InvalidMimeType do
Mime::Type.new("too/many/slash")
Expand All @@ -190,6 +197,14 @@ class MimeTypeTest < ActiveSupport::TestCase
Mime::Type.new("missingslash")
end

assert_raises Mime::Type::InvalidMimeType do
Mime::Type.new("improper/semicolon;")
end

assert_raises Mime::Type::InvalidMimeType do
Mime::Type.new('improper/semicolon; parameter=abc; parameter2="xyz";')
end

assert_raises Mime::Type::InvalidMimeType do
Mime::Type.new("text/html, text/plain")
end
Expand Down

0 comments on commit 12a1a66

Please sign in to comment.