Skip to content

Commit

Permalink
Merge pull request #2474 from inkstak/master
Browse files Browse the repository at this point in the history
Do not return invalid content type on text files
  • Loading branch information
mshibuya authored Jan 17, 2021
2 parents 39dfdcd + 1872c18 commit 8c6743c
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 2 deletions.
11 changes: 9 additions & 2 deletions lib/carrierwave/sanitized_file.rb
Original file line number Diff line number Diff line change
Expand Up @@ -331,9 +331,16 @@ def existing_content_type

def mime_magic_content_type
if path
File.open(path) do |file|
MimeMagic.by_magic(file).try(:type) || 'invalid/invalid'
type = File.open(path) do |file|
MimeMagic.by_magic(file).try(:type)
end

if type.nil?
type = ::MiniMime.lookup_by_filename(path).try(:content_type)
type = 'invalid/invalid' unless type.nil? || type.start_with?('text/')
end

type
end
rescue Errno::ENOENT
nil
Expand Down
Empty file added spec/fixtures/bork.ABCDE
Empty file.
20 changes: 20 additions & 0 deletions spec/sanitized_file_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,26 @@
expect(sanitized_file.content_type).to eq 'invalid/invalid'
end

it "returns valid content type on text file" do
file = File.open(file_path('bork.txt'))

sanitized_file = CarrierWave::SanitizedFile.new(file)

expect { sanitized_file.content_type }.not_to raise_error

expect(sanitized_file.content_type).to eq 'text/plain'
end

it "returns missing content type with unknown extension" do
file = File.open(file_path('bork.ABCDE'))

sanitized_file = CarrierWave::SanitizedFile.new(file)

expect { sanitized_file.content_type }.not_to raise_error

expect(sanitized_file.content_type).to eq ""
end

it "does not raise an error if the path is not present" do
sanitized_file = CarrierWave::SanitizedFile.new(nil)

Expand Down

0 comments on commit 8c6743c

Please sign in to comment.