【问题标题】:How to check attachment is encrypted or not in Rails Application如何在 Rails 应用程序中检查附件是否加密
【发布时间】:2018-12-23 02:25:05
【问题描述】:

如果用户尝试在 Ruby on Rails 应用程序中上传加密文件,我想给出验证错误消息。我正在使用神社宝石进行附件。我该怎么做 - 有什么想法吗?

我正在使用:Rails 5.1.6,ruby 2.4.2p198,神社 2.9.0。


这是我的初始化器

require 'shrine'

Shrine.plugin :activerecord
Shrine.plugin :cached_attachment_data # for forms
Shrine.plugin :determine_mime_type
Shrine.plugin :backgrounding
Shrine.plugin :delete_promoted

Shrine::Attacher.promote { |data| PromoteJob.perform_async(data) }
Shrine::Attacher.delete { |data| DeleteJob.perform_async(data) }

这个上传者

class DocumentUploader < Shrine
  plugin :validation_helpers
  plugin :pretty_location

  plugin :processing
  plugin :versions

 process(:store) do |io, context|
    original = io.download
    out_file = Tempfile.new(["pdfsigned~", '.pdf'])
    SignPdf.sign_pdf!(original, io.original_filename, out_file, 
    context[:record], context[:record].creator_company, :uploaded, {} , false)
   { original: io, stamped: out_file }
 end

 Attacher.validate do
   validate_mime_type_inclusion ['application/pdf']
end

结束

当我创建文档时。它不检查并接受加密文件

【问题讨论】:

  • 文件是字节流。加密文件是字节流。您需要提出区分两个字节流的标准,因为从技术角度来看,没有区别。作为人类,您如何判断文件是“有效”、加密、损坏还是只是随机垃圾?

标签: ruby-on-rails ruby paperclip ruby-on-rails-5.1 shrine


【解决方案1】:

determine_mime_type Shrine 插件检测到的允许 MIME 类型列入白名单应该会自动拒绝加密文件。加密文件会更改其内容,包括诸如file 命令之类的实用程序用来确定文件的 MIME 类型的“魔术字节”。

因此,如果上传了加密文件,file 命令(在determine_mime_type Shrine 插件中默认使用)应该返回通用的application/octet-stream MIME 类型,并且在白名单中失败。

要实现这一点,首先在初始化程序中加载插件:

Shrine.plugin :determine_mime_type
Shrine.plugin :validation_helpers

然后在你的上传器中添加validate_mime_type_inclusion检查,例如:

# image_uploader.rb
class ImageUploader < Shrine
  Attacher.validate do
    validate_mime_type_inclusion %W[image/jpeg image/png image/webp]
  end
end

# video_uploader.rb
class VideoUploader < Shrine
  Attacher.validate do
    validate_mime_type_inclusion %W[video/mpeg video/mp4]
  end
end

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-14
  • 1970-01-01
  • 2021-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多