0

我在 Rails 应用程序中使用 Shrine 将文件上传到 Amazon S3。一些与 GDPR 合规性相关的用户文件,我需要实施客户端加密([Shrine 文档](https://github.com/shrinerb/shrine/blob/v2.16.0/doc/storage/s3.md#加密))。在 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

模型/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
4

1 回答 1

0

Shrink 框架的开发者帮我解决了这个聊天中的问题

这是代表团的错误。我委托[: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的常规。Aws::S3::Client#get_object

有了这个,下载会自动解密。

于 2019-04-25T09:51:39.230 回答