AWS SDK for Ruby
Developer Guide

Requiring Encryption on the Server to Upload Amazon S3 Bucket Objects

The following example uses the put_bucket_policy method to require that objects uploaded to an Amazon S3 bucket have Amazon S3 encrypt the object with an AWS KMS key. Attempts to upload an object without specifying that Amazon S3 encrypt the object with an AWS KMS key raise an Aws::S3::Errors::AccessDenied exception.

Avoid using this configuration option if you use default server-side encryption as described in Setting Default Server-Side Encryption for an Amazon S3 Bucket as they could conflict and result in unexpected results.

Choose Copy to save the code locally.

Create the file add_sses3_policy.rb.

Add the required Amazon S3 gem and set the bucket name.

Note

Version 2 of the AWS SDK for Ruby didn't have service-specific gems.

require 'aws-sdk-s3' # In v2: require 'aws-sdk' bucket = 'my_bucket'

Create an Amazon S3 policy that requires server-side KMS encryption on objects uploaded to the bucket.

policy = { 'Version': '2012-10-17', 'Id': 'PutObjPolicy', 'Statement': [ { 'Sid': 'DenyIncorrectEncryptionHeader', 'Effect': 'Deny', 'Principal': '*', 'Action': 's3:PutObject', 'Resource': 'arn:aws:s3:::' + bucket + '/*', 'Condition': { 'StringNotEquals': { 's3:x-amz-server-side-encryption': 'aws:kms' } } }, { 'Sid': 'DenyUnEncryptedObjectUploads', 'Effect': 'Deny', 'Principal': '*', 'Action': 's3:PutObject', 'Resource': 'arn:aws:s3:::' + bucket + '/*', 'Condition': { 'Null': { 's3:x-amz-server-side-encryption': 'true' } } } ] }.to_json

Create the Amazon S3 client, apply the policy to the bucket, and print a success message.

s3 = Aws::S3::Client.new(region: 'us-west-2') # Apply bucket policy s3.put_bucket_policy( bucket: bucket, policy: policy ) puts 'Successfully added policy to bucket ' + bucket

See the complete example on GitHub.