Rails 请教 Carrierwave content_type ImageMagick 问题

charlie_hsieh · 2021年09月12日 · 180 次阅读

请问有人发现,carrierwave content_type default 是使用 filename extension 来的? 我尝试 mv test.pdf test.jpg 没想到 test.jpg (pdf file) 居然可以 upload, 即使我有如下的设定

def content_type_allowlist
  [/image\/(jpg|jpeg|gif|png)+/]
end

原始 carrierwave/lib/carrierwave/sanitized_file.rb 取得 content_type 的顺序,有点奇怪

def content_type
  @content_type ||=
    existing_content_type ||
    marcel_magic_by_mime_type ||
    marcel_magic_by_path
end

最终解法,有点丑陋.. 但至少,可以有效防止 ImgeTragick

class ImageUploader < CarrierWave::Uploader::Base
  include CarrierWave::MiniMagick
  before :process, :check_file_type_whitelist

  def content_type_allowlist
    [/image\/(jpg|jpeg|gif|png)+/]
  end

  private
  def check_file_type_whitelist(new_file)
       return unless content_type_allowlist

      content_type = Marcel::MimeType.for Pathname.new new_file.path
      if !whitelisted_content_type?(content_type)
        raise CarrierWave::IntegrityError, I18n.translate(:"errors.messages.content_type_whitelist_error", content_type: content_type,
  allowed_types: Array(content_type_allowlist).join(", "), default: :"errors.messages.content_type_allowlist_error")
      end
    end
end

以上不知道,我有没有哪里理解错误?

暂无回复。
需要 登录 后方可回复, 如果你还没有账号请 注册新账号