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

How to decrypt file (encrypted with aws KMS) when downloading from aws S3 via 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

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

这是代表团的一个错误。我把[: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

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