class EventStoreClient::DataEncryptor

Attributes

encrypted_data[R]
encryption_metadata[R]
key_repository[R]

Public Class Methods

new(data:, schema:, repository:) click to toggle source
# File lib/event_store_client/data_encryptor.rb, line 27
def initialize(data:, schema:, repository:)
  @encrypted_data = deep_dup(data).transform_keys!(&:to_s)
  @key_repository = repository
  @encryption_metadata = EncryptionMetadata.new(data: data, schema: schema).call
end

Public Instance Methods

call() click to toggle source
# File lib/event_store_client/data_encryptor.rb, line 5
def call
  return encrypted_data if encryption_metadata.empty?

  key_id = encryption_metadata[:key]
  res = key_repository.find(key_id)
  res = res.failure? ? key_repository.create(key_id) : res
  key = res.value!

  encryption_metadata[:iv] = key.attributes[:iv]
  encrypt_attributes(
    key: key,
    data: encrypted_data,
    attributes: encryption_metadata[:attributes].map(&:to_s)
  )
end

Private Instance Methods

deep_dup(hash) click to toggle source
# File lib/event_store_client/data_encryptor.rb, line 41
def deep_dup(hash)
  dupl = hash.dup
  dupl.each { |k, v| dupl[k] = v.instance_of?(Hash) ? deep_dup(v) : v }
  dupl
end
encrypt_attributes(key:, data:, attributes:) click to toggle source
# File lib/event_store_client/data_encryptor.rb, line 33
def encrypt_attributes(key:, data:, attributes:)
  text = JSON.generate(data.select { |hash_key, _value| attributes.include?(hash_key.to_s) })
  encrypted = key_repository.encrypt(key: key, message: text).value!
  attributes.each { |att| data[att.to_s] = 'es_encrypted' if data.key?(att.to_s) }
  data['es_encrypted'] = encrypted.attributes[:message]
  data
end