From 1872c18e16842097e97a3c7f72f41664ae62e609 Mon Sep 17 00:00:00 2001 From: Sebastien Savater Date: Thu, 23 Apr 2020 10:21:03 +0200 Subject: [PATCH] Do not returns invalid content type on text files --- lib/carrierwave/sanitized_file.rb | 11 +++++++++-- spec/fixtures/bork.ABCDE | 0 spec/sanitized_file_spec.rb | 20 ++++++++++++++++++++ 3 files changed, 29 insertions(+), 2 deletions(-) create mode 100644 spec/fixtures/bork.ABCDE diff --git a/lib/carrierwave/sanitized_file.rb b/lib/carrierwave/sanitized_file.rb index fd5d3a378..734c00d54 100644 --- a/lib/carrierwave/sanitized_file.rb +++ b/lib/carrierwave/sanitized_file.rb @@ -330,9 +330,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 diff --git a/spec/fixtures/bork.ABCDE b/spec/fixtures/bork.ABCDE new file mode 100644 index 000000000..e69de29bb diff --git a/spec/sanitized_file_spec.rb b/spec/sanitized_file_spec.rb index 70298776d..306830c38 100644 --- a/spec/sanitized_file_spec.rb +++ b/spec/sanitized_file_spec.rb @@ -221,6 +221,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)