Skip to content

Commit

Permalink
Feat: support base64 encoded keys with more entropy than just printab…
Browse files Browse the repository at this point in the history
…le chararacters
  • Loading branch information
zealot128 committed Nov 13, 2023
1 parent d128498 commit 5c019c8
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 6 deletions.
8 changes: 6 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,12 @@ encrypted_amazon:
secret_access_key: <%= Rails.application.secrets.dig(:aws, :secret_access_key) %>
region: <%= Rails.application.secrets.dig(:aws, :region) %>
bucket: <%= Rails.application.secrets.dig(:aws, :bucket) %>
# Static Encryption Key: 32 bytes
encryption_key: <%= Rails.application.secret_key_base[0..31] %>

# Static Encryption Key: 32 bytes - must be 32 bytes = 256bit length.
# mark as base64 to encode all ascii characters
# generate with: Base64.strict_encode64(OpenSSL::Cipher.new("AES-256-ECB").random_key)
encryption_key: "base64:vbMnOv+ZjD0kp/DEEw1gCTjmleCWZafjENNwvIzq6DQ="
# encryption_key: "<%= Base64.strict_encode64(Rails.application.secret_key_base[0..31]) %>"
```

### tell direct upload to use `encrypted_amazon` service
Expand Down
11 changes: 7 additions & 4 deletions lib/active_storage/service/encrypted_s3_service.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,15 @@ class Service::EncryptedS3Service < Service::S3Service

def initialize(bucket:, upload: {}, **options)
# https://docs.aws.amazon.com/sdk-for-ruby/v3/api/Aws/S3/Encryption.html
super_options = options.except(:kms_key_id, :encryption_key, :encryption_key)
super_options = options.except(:kms_key_id, :encryption_key)
super(bucket: bucket, upload: upload, **super_options)

# TODO: different Key Formats? Pub/Private?
if options[:encryption_key].to_s[/base64:(.*)/]
options[:encryption_key] = Base64.decode64($1)
end
if options[:encryption_key].length > 32
# TODO: different Key Formats? Pub/Private?
options[:encryption_key] = options[:encryption_key][0..31]
raise ArgumentError, "Encryption Key must be 32 bytes"
end
@encryption_client = Aws::S3::EncryptionV2::Client.new(
options.merge(
Expand Down Expand Up @@ -90,7 +93,7 @@ def url_for(blob, expires_in:)
private

def current_host
ActiveStorage::Current.host || Rails.application.config.action_mailer.default_url_options[:host]
(ActiveStorage::Current.url_options || Rails.application.config.action_mailer.default_url_options)[:host]
end

def private_url(key, expires_in:, filename:, content_type:, disposition:, **)
Expand Down

0 comments on commit 5c019c8

Please sign in to comment.