123456789_123456789_123456789_123456789_123456789_

Module: Mongoid::Config::Encryption Private

Relationships & Source Files
Extension / Inclusion / Inheritance Descendants
Extended In:
Defined in: lib/mongoid/config/encryption.rb

Overview

This module contains the logic for configuring Client Side Field Level automatic encryption.

Constant Summary

Instance Method Summary

Instance Method Details

#algorithm_for(field) ⇒ String (private)

Get the encryption algorithm to use for the provided field.

Parameters:

  • field (Mongoid::Field) —

    The field to get the algorithm for.

Returns:

[ GitHub ]

  
# File 'lib/mongoid/config/encryption.rb', line 327

def algorithm_for(field)
  case field.deterministic?
  when true
    DETERMINISTIC_ALGORITHM
  when false
    RANDOM_ALGORITHM
  end
end

#bson_type_for(field) ⇒ String (private)

Get the ::BSON type identifier for the provided field according to the https://www.mongodb.com/docs/manual/reference/bson-types/#std-bson-types

Parameters:

  • field (Mongoid::Field) —

    The field to get the ::BSON type identifier for.

Returns:

  • (String) —

    The BSON type identifier.

[ GitHub ]

  
# File 'lib/mongoid/config/encryption.rb', line 318

def bson_type_for(field)
  TYPE_MAPPINGS[field.type]
end

#collect_encrypted_paths(properties, path) ⇒ Array<Array<String>> (private)

Walk the schema properties and collect the path of every encrypted leaf.

Parameters:

  • properties (Hash) —

    The properties to walk.

  • path (Array<String>) —

    The properties the walk is already inside of.

Returns:

[ GitHub ]

  
# File 'lib/mongoid/config/encryption.rb', line 225

def collect_encrypted_paths(properties, path)
  properties.each_with_object([]) do |(name, schema), paths|
    if schema.key?('encrypt')
      paths << (path + [ name ])
    elsif schema['properties']
      paths.concat(collect_encrypted_paths(schema['properties'], path + [ name ]))
    end
  end
end

#encrypted_paths_for(model) ⇒ Array<Array<String>>

Collect the paths of the fields encrypted by the schema generated for a single model.

Parameters:

Returns:

[ GitHub ]

  
# File 'lib/mongoid/config/encryption.rb', line 60

def encrypted_paths_for(model)
  return model.instance_variable_get(:@encrypted_paths_for) if
    model.instance_variable_defined?(:@encrypted_paths_for)

  properties = properties_for(model, [ model ])['properties'] || {}
  model.instance_variable_set(:@encrypted_paths_for, collect_encrypted_paths(properties, []))
end

#encryption_schema_map(default_database, models = ::Mongoid.models) ⇒ Hash

Generate the encryption schema map for the provided models.

Parameters:

  • default_database (String) —

    The default database name.

  • models (Array<Mongoid::Document>) (defaults to: ::Mongoid.models) —

    The models to generate the schema map for. Defaults to all models in the application.

Returns:

  • (Hash) —

    The encryption schema map.

[ GitHub ]

  
# File 'lib/mongoid/config/encryption.rb', line 22

def encryption_schema_map(default_database, models = ::Mongoid.models)
  # Subclasses share their parent's collection but are not registered in
  # Mongoid.models, so they have to be added to the walk explicitly.
  classes = models.flat_map { |model| [ model ] + model.descendants }.uniq

  classes.each_with_object({}) do |model, map|
    next if model.embedded?
    next unless model.requires_encryption_schema?

    database = model.storage_options.fetch(:database) { default_database }
    # A callable database name cannot be resolved here: the documented
    # multi-tenant idiom has no correct value while the client is being
    # built. Interpolating the callable would produce a key that never
    # matches any namespace, so leave the model out of the map. Writes
    # are refused later, by PersistenceContext, rather than silently
    # going out unencrypted.
    next if database.respond_to?(:call)

    key = "#{database}.#{model.collection_name}"
    props = (model).merge(properties_for(model, [ model ], key))
    next if props.empty?

    # The root of a collection schema describes the document, so it is
    # always an object. Saying so matters when a nested schema carries
    # encryptMetadata: mongocryptd rejects the schema otherwise.
    entry = { 'bsonType' => 'object' }.merge(props)
    map[key] = map.key?(key) ? merge_schema_entries(map[key], entry, key) : entry
  end
end

#key_id_for(key_id_base64, key_name_field) ⇒ Array<BSON::Binary> | String | nil (private)

Get the keyId encryption schema field for the base64 encrypted key id.

Parameters:

  • key_id_base64 (String | nil) —

    The base64 encoded key id.

  • key_name_field (String | nil) —

    The name of the key name field.

Returns:

  • (Array<BSON::Binary> | String | nil) —

    The keyId encryption schema field, JSON pointer to the field that contains keyAltName, or nil if both key_id_base64 and key_name_field are nil.

[ GitHub ]

  
# File 'lib/mongoid/config/encryption.rb', line 345

def key_id_for(key_id_base64, key_name_field)
  return nil if key_id_base64.nil? && key_name_field.nil?
  if !key_id_base64.nil? && !key_name_field.nil?
    raise ArgumentError, 'Specifying both key_id and key_name_field is not allowed'
  end

  if key_id_base64.nil?
    "/#{key_name_field}"
  else
    [ BSON::Binary.new(Base64.decode64(key_id_base64), :uuid) ]
  end
end

#merge_encrypt_metadata(left, right, namespace) ⇒ Hash (private)

Merge two encryptMetadata objects.

Parameters:

  • left (Hash) —

    The first encryptMetadata object.

  • right (Hash) —

    The second encryptMetadata object.

  • namespace (String | nil) —

    The namespace the schema belongs to.

Returns:

  • (Hash) —

    The merged encryptMetadata object.

[ GitHub ]

  
# File 'lib/mongoid/config/encryption.rb', line 269

def (left, right, namespace)
  left.merge(right) do |key, left_value, right_value|
    unless left_value == right_value
      raise_invalid_encryption_schema(namespace, "encryptMetadata.#{key}")
    end

    left_value
  end
end

#merge_properties(left, right, namespace) ⇒ Hash (private)

Merge two properties objects.

Parameters:

  • left (Hash) —

    The first properties object.

  • right (Hash) —

    The second properties object.

  • namespace (String | nil) —

    The namespace the schema belongs to.

Returns:

  • (Hash) —

    The merged properties object.

[ GitHub ]

  
# File 'lib/mongoid/config/encryption.rb', line 286

def merge_properties(left, right, namespace)
  left.merge(right) do |name, left_value, right_value|
    if left_value.key?('encrypt') && right_value.key?('encrypt')
      unless left_value['encrypt'] == right_value['encrypt']
        raise_invalid_encryption_schema(namespace, "properties.#{name}")
      end

      left_value
    elsif left_value.key?('encrypt') || right_value.key?('encrypt')
      raise_invalid_encryption_schema(namespace, "properties.#{name}")
    else
      merge_schema_entries(left_value, right_value, namespace)
    end
  end
end

#merge_schema_entries(left, right, namespace = nil) ⇒ Hash (private)

Merge two schema objects covering the same model or namespace.

Every model writing to one namespace contributes an entry to the schema map. Those entries have to agree on everything they have in common, or the schema would silently encrypt a field differently for one model than for another.

Parameters:

  • left (Hash) —

    The first schema.

  • right (Hash) —

    The second schema.

  • namespace (String | nil) (defaults to: nil) —

    The namespace the schema belongs to.

Returns:

  • (Hash) —

    The merged schema.

[ GitHub ]

  
# File 'lib/mongoid/config/encryption.rb', line 247

def merge_schema_entries(left, right, namespace = nil)
  left.merge(right) do |key, left_value, right_value|
    case key
    when 'bsonType'
      left_value
    when 'encryptMetadata'
      (left_value, right_value, namespace)
    when 'properties'
      merge_properties(left_value, right_value, namespace)
    else
      raise_invalid_encryption_schema(namespace, key)
    end
  end
end

#metadata_for(model) ⇒ Hash (private)

Generate the encryptMetadata object for the provided model.

Parameters:

Returns:

  • (Hash) —

    The encryptMetadata object.

[ GitHub ]

  
# File 'lib/mongoid/config/encryption.rb', line 104

def (model)
   = {}.tap do ||
    if (key_id = key_id_for(model.[:key_id], model.[:key_name_field]))
      ['keyId'] = key_id
    end
    if model..key?(:deterministic)
      ['algorithm'] = if model.[:deterministic]
                                DETERMINISTIC_ALGORITHM
                              else
                                RANDOM_ALGORITHM
                              end
    end
  end
  if .empty?
    {}
  else
    {
      'bsonType' => 'object',
      'encryptMetadata' => 
    }
  end
end

#properties_for(model, path, namespace = nil) ⇒ Hash (private)

Generate encryption properties for the provided model.

This method generates the properties for the fields and relations that are marked as encrypted.

Parameters:

  • model (Mongoid::Document) —

    The model to generate the properties for.

  • path (Array<Mongoid::Document>) —

    The models the walk is already inside of, outermost first.

  • namespace (String | nil) (defaults to: nil) —

    The namespace the schema is built for, used for error reporting.

Returns:

  • (Hash) —

    The encryption properties.

[ GitHub ]

  
# File 'lib/mongoid/config/encryption.rb', line 139

def properties_for(model, path, namespace = nil)
  result = properties_for_fields(model).merge(properties_for_relations(model, path, namespace))
  if result.empty?
    {}
  else
    { 'properties' => result }
  end
end

#properties_for_fields(model) ⇒ Hash (private)

Generate encryption properties for the fields of the provided model.

Parameters:

Returns:

  • (Hash) —

    The encryption properties.

[ GitHub ]

  
# File 'lib/mongoid/config/encryption.rb', line 153

def properties_for_fields(model)
  model.fields.each_with_object({}) do |(name, field), props|
    next unless field.is_a?(Mongoid::Fields::Encrypted)

    props[name] = {
      'encrypt' => {
        'bsonType' => bson_type_for(field)
      }
    }
    if (algorithm = algorithm_for(field))
      props[name]['encrypt']['algorithm'] = algorithm
    end
    if (key_id = key_id_for(field.key_id, field.key_name_field))
      props[name]['encrypt']['keyId'] = key_id
    end
  end
end

#properties_for_relations(model, path, namespace = nil) ⇒ Hash (private)

Generate encryption properties for the relations of the provided model.

This method generates the properties for the embedded relations that are configured to be encrypted.

Parameters:

  • model (Mongoid::Document) —

    The model to generate the properties for.

  • path (Array<Mongoid::Document>) —

    The models the walk is already inside of, outermost first.

  • namespace (String | nil) (defaults to: nil) —

    The namespace the schema is built for, used for error reporting.

Returns:

  • (Hash) —

    The encryption properties.

[ GitHub ]

  
# File 'lib/mongoid/config/encryption.rb', line 183

def properties_for_relations(model, path, namespace = nil)
  model.relations.each_with_object({}) do |(name, relation), props|
    # relation_class constantizes, and a polymorphic embedded_in has no
    # class to resolve, so the relation type has to be checked first.
    next unless relation.is_a?(Association::Embedded::EmbedsOne)

    klass = relation.try_relation_class
    # An association target does not have to be a Mongoid document, and
    # the class it names does not have to exist.
    next unless klass.respond_to?(:requires_encryption_schema?)

    # Any subclass of the declared class can be assigned to the
    # association, so its encrypted fields have to be mapped here too.
    properties = ([ klass ] + klass.descendants).uniq.inject({}) do |merged, candidate|
      # Stop at a model the walk is already inside of, or a self-embedding
      # model never terminates. The path covers the current branch only:
      # a model embedded by two parents, or twice by one parent, has to be
      # emitted at every place it appears.
      next merged if path.include?(candidate)
      next merged unless candidate.respond_to?(:requires_encryption_schema?)
      next merged unless candidate.requires_encryption_schema?

      merge_schema_entries(
        merged,
        (candidate).merge(
          properties_for(candidate, path + [ candidate ], namespace)
        ),
        namespace
      )
    end
    props[name] = { 'bsonType' => 'object' }.merge(properties) unless properties.empty?
  end
end

#raise_invalid_encryption_schema(namespace, path) (private)

Raise an error for a schema conflicting with another one.

Parameters:

  • namespace (String | nil) —

    The namespace the schema belongs to.

  • path (String) —

    The conflicting path in the schema.

Raises:

[ GitHub ]

  
# File 'lib/mongoid/config/encryption.rb', line 308

def raise_invalid_encryption_schema(namespace, path)
  raise Errors::InvalidEncryptionSchema.new(namespace, path)
end