diff --git a/lib/carrierwave/sanitized_file.rb b/lib/carrierwave/sanitized_file.rb index dd914ca7e..7b18c25ed 100644 --- a/lib/carrierwave/sanitized_file.rb +++ b/lib/carrierwave/sanitized_file.rb @@ -341,7 +341,7 @@ def existing_content_type end def mime_magic_content_type - MimeMagic.by_magic(File.open(path)).try(:type) if path + MimeMagic.by_magic(File.open(path)).try(:type) || 'invalid/invalid' if path rescue Errno::ENOENT nil end diff --git a/spec/fixtures/spoof.png b/spec/fixtures/spoof.png new file mode 100644 index 000000000..3d8c915a9 --- /dev/null +++ b/spec/fixtures/spoof.png @@ -0,0 +1,4 @@ +push graphic-context +viewbox 0 0 640 480 +fill 'url(https://example.com/image.jpg";|ls "-la)' +pop graphic-context diff --git a/spec/sanitized_file_spec.rb b/spec/sanitized_file_spec.rb index e9b05f1a1..f02469563 100644 --- a/spec/sanitized_file_spec.rb +++ b/spec/sanitized_file_spec.rb @@ -230,6 +230,7 @@ it "handles Mime::Type object" do file = File.open(file_path('sponsored.doc')) + file.stub(:content_type) { 'application/msword' } sanitized_file = CarrierWave::SanitizedFile.new(file) allow(sanitized_file).to receive(:file).and_return(file) @@ -253,6 +254,17 @@ expect(sanitized_file.content_type).to eq("application/zip") end + it "does not allow spoofing of the mime type if the mime type is not detectable" do + file = File.open(file_path('spoof.png')) + + sanitized_file = CarrierWave::SanitizedFile.new(file) + + lambda { sanitized_file.content_type }.should_not raise_error + + sanitized_file.content_type.should_not == 'image/png' + sanitized_file.content_type.should == 'invalid/invalid' + end + it "does not raise an error if the path is not present" do sanitized_file = CarrierWave::SanitizedFile.new(nil) diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index cc32da588..a144bc122 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -66,7 +66,9 @@ def stub_stringio(filename, mime_type=nil, fake_name=nil) end def stub_file(filename, mime_type=nil, fake_name=nil) - File.open(file_path(filename)) + f = File.open(file_path(filename)) + f.stub(:content_type) { mime_type } if mime_type + return f end end diff --git a/spec/uploader/proxy_spec.rb b/spec/uploader/proxy_spec.rb index c8ceb041b..e3448e896 100644 --- a/spec/uploader/proxy_spec.rb +++ b/spec/uploader/proxy_spec.rb @@ -65,6 +65,7 @@ end context "when the file has been cached" do + let(:test_file_name) { 'landscape.jpg' } before { uploader.cache!(test_file) } it { is_expected.to eq('image/jpeg') }