通过Shrine从AWS S3下载文件时,如何解密文件(用AWS KMS加密)?

时间:2019-04-23 16:38:47

标签: ruby-on-rails amazon-s3 storage aws-kms shrine

我在Rails应用程序中使用Shrine将文件上传到Amazon S3。一些用户的文件与GDPR合规性相关,因此我需要实现客户端加密([Shrine文档](https://github.com/shrinerb/shrine/blob/v2.16.0/doc/storage/s3.md#encryption))。在Shrine文档中,您可以看到通过AWS KMS进行文件加密的信息,但没有有关解密的信息。

从aws s3下载文件时如何解密文件?

这是我的代码:

config / initializers / shrine.rb-在这里,我为Shrine指定配置。

require 'shrine'
require 'shrine/storage/s3'
require 'shrine/storage/file_system'

class Shrine
  plugin :activerecord

  class << self
    Aws::S3::Encryption::Client.extend Forwardable
    Aws::S3::Encryption::Client.delegate(
        [:head_object, :get_object, :config, :build_request] => :client
    )

    def s3_options_encrypted
      {
          prefix:            'encrypted',
          region:            ENV['AWS_REGION'],
          bucket:            ENV['AWS_BUCKET_NAME'] ,
          endpoint:          ENV['AWS_ENDPOINT'],
          access_key_id:     ENV['AWS_ACCESS_KEY_ID'],
          secret_access_key: ENV['AWS_SECRET_ACCESS_KEY'],
          upload_options:    { acl: 'private' },
          client:            Aws::S3::Encryption::Client.new(kms_key_id: ENV['KMS_KEY_ID'])
      }
    end

    def storages
      {
        cache: Shrine::Storage::FileSystem.new('public', prefix: 'cache_files'),
        encrypted: Shrine::Storage::S3.new(**s3_options_encrypted)
      }
    end
  end
end

models / document.rb-模型

class Document < ApplicationRecord
  include DocumentsUploader::Attachment.new(:file, {store: :encrypted})
end

controllers / downloads_controller.rb-在这里,我正在下载文件,需要解密。

class DownloadsController < ApplicationController
  def documents
    document = Document.find(id) if Document.exists?(id: params[:id])

    if document.nil? || !document&.file
      redirect_to root_path and return
    end

    temp_file = document.file.download
    name      = "#{document.name}.pdf"
    type      = 'application/pdf'

    send_file temp_file, filename: name, type: type, disposition: 'attachment'
  end
end

1 个答案:

答案 0 :(得分:0)

Shrink框架的开发人员帮助我解决了此chat

中的问题

这是代表团中的一个错误。我将UITableView.backgroundView委派给[:head_object, :get_object, :config, :build_request],但我应该委派:client。正确的委派如下所示:

[:head_object, :delete_object, :config, :build_request]

Aws::S3::Encryption::Client.delegate( [:head_object, :delete_object, :config, :build_request] => :client ) 已经实现,它是解密的工作,因此添加Aws::S3::Encryption::Client#get_object委托将使用常规#get_object,它不执行任何解密。

这样,下载内容将自动解密。