Ruby on rails 如何避免在ActiveStorage中接受损坏的图像?
我目前正在将一个Rails应用程序(驱动screenshots.debian.net)从曲别针迁移到ActiveStorage。它允许用户上传PNG图像,然后显示给所有用户 TL;DR:上传表单接受损坏的图像。Imagemagick“接受”它们。ActiveStorage不会立即验证这一点。我最终在磁盘上找到了损坏的文件 这是图像的模型。我正在使用“活动存储验证”gem:Ruby on rails 如何避免在ActiveStorage中接受损坏的图像?,ruby-on-rails,paperclip,rails-activestorage,Ruby On Rails,Paperclip,Rails Activestorage,我目前正在将一个Rails应用程序(驱动screenshots.debian.net)从曲别针迁移到ActiveStorage。它允许用户上传PNG图像,然后显示给所有用户 TL;DR:上传表单接受损坏的图像。Imagemagick“接受”它们。ActiveStorage不会立即验证这一点。我最终在磁盘上找到了损坏的文件 这是图像的模型。我正在使用“活动存储验证”gem: class Screenshot < ApplicationRecord has_one_attached :im
class Screenshot < ApplicationRecord
has_one_attached :image
validates :image, attached: true, content_type: [:png]
def medium_image
if self.image.attached?
self.image.variant(
resize_to_limit: [670, 600]
).processed
end
end
end
这很有效。接受PNG文件。JPG文件被拒绝。很好
然而,当我上传一个故意破坏的文件时,我遇到了麻烦。我创建了一个名为“breake.png”的文件,它由5 KB的零字节组成。ActiveStorage接受该文件,因此我最终得到一个无效文件
上传完成后,应该马上显示图像。调用Screenshot.medium_image方法,尝试创建变体。ImageMagick尝试转换并调整损坏图像的大小,但失败:
convert /tmp/ActiveStorage-21670-… failed with error:
convert-im6.q16: improper image header `/tmp/ActiveStorage-21670-…' @ error/png.c/ReadPNGImage/4092.
convert-im6.q16: no images defined `/tmp/image_processing….png' @ error/convert.c/ConvertImageCommand/3258.
因此,一旦上传了这样一个损坏的图像,应用程序每次试图显示它时都会失败。很容易拒绝服务
我的理解是:
[ActiveJob]将ActiveStorage::AnalyzeJob(作业ID:91055878-f516-4f2f-98ff-e39573980b45)排入队列,并使用参数进行异步(活动存储分析)
if new\u屏幕截图.valid?
行对文件运行验证,并发现文件已损坏convert /tmp/ActiveStorage-21670-… failed with error:
convert-im6.q16: improper image header `/tmp/ActiveStorage-21670-…' @ error/png.c/ReadPNGImage/4092.
convert-im6.q16: no images defined `/tmp/image_processing….png' @ error/convert.c/ConvertImageCommand/3258.