class DynamoSecret::Kms

Public Class Methods

new(config) click to toggle source
# File lib/dynamo_secret/kms.rb, line 6
def initialize(config)
  @key_name = config[:key_name] || key_name
  @region = config.fetch(:region, region)
end

Public Instance Methods

create_key() click to toggle source
# File lib/dynamo_secret/kms.rb, line 11
def create_key
  return $stdout.puts "KMS alias #{@key_name} already exists" if key
  id = client.create_key(tags: [{ tag_key: 'Owner', tag_value: user_id }]).key_metadata.key_id
  client.create_alias(alias_name: "alias/#{@key_name}", target_key_id: id)
end
decrypt(data) click to toggle source
# File lib/dynamo_secret/kms.rb, line 17
def decrypt(data)
  client.decrypt(ciphertext_blob: data).plaintext
rescue Aws::KMS::Errors::InvalidCiphertextException
  $stderr.puts 'Key was found but KMS decrypt failed - skipping'
  data
end
encrypt(data) click to toggle source
# File lib/dynamo_secret/kms.rb, line 24
def encrypt(data)
  client.encrypt(key_id: key, plaintext: data).ciphertext_blob
end
key() click to toggle source
# File lib/dynamo_secret/kms.rb, line 28
def key
  @key ||= client.list_aliases.aliases.map do |kms_alias|
    kms_alias.target_key_id if kms_alias.alias_name == "alias/#{@key_name}"
  end.compact.first
end

Private Instance Methods

client() click to toggle source
# File lib/dynamo_secret/kms.rb, line 36
def client
  @client ||= Aws::KMS::Client.new(region: @region)
end
key_name() click to toggle source
# File lib/dynamo_secret/kms.rb, line 40
def key_name
  "dynamo_secret_#{user_id}"
end
region() click to toggle source
# File lib/dynamo_secret/kms.rb, line 44
def region
  ENV.fetch('AWS_REGION', 'us-west-2')
end
user_id() click to toggle source
# File lib/dynamo_secret/kms.rb, line 48
def user_id
  @user_id ||= IAM.new.user_id
end