123456789_123456789_123456789_123456789_123456789_

Class: Mongo::Crypt::EncryptionIO Private

Relationships & Source Files
Inherits: Object
Defined in: lib/mongo/crypt/encryption_io.rb

Overview

A class that implements I/O methods between the driver and the MongoDB server or mongocryptd.

Constant Summary

Class Method Summary

Instance Method Summary

Constructor Details

.new(key_vault_namespace:, key_vault_client:, metadata_client:, client: nil, mongocryptd_client: nil, mongocryptd_options: {}, kms_connect_callback: nil) ⇒ EncryptionIO

Note:

When being used for auto encryption, all arguments are required. When being used for explicit encryption, only the key_vault_namespace and key_vault_client arguments are required.

Note:

This class expects that the key_vault_client and key_vault_namespace options are not nil and are in the correct format.

Creates a new EncryptionIO object with information about how to connect to the key vault.

Parameters:

  • client (Mongo::Client) —

    The client used to connect to the collection that stores the encrypted documents, defaults to nil.

  • mongocryptd_client (Mongo::Client) —

    The client connected to mongocryptd, defaults to nil.

  • key_vault_client (Mongo::Client) —

    The client connected to the key vault collection.

  • metadata_client (Mongo::Client | nil) —

    The client to be used to obtain collection metadata.

  • key_vault_namespace (String) —

    The key vault namespace in the format db_name.collection_name.

  • mongocryptd_options (Hash) —

    ::Mongo::Options related to mongocryptd.

  • kms_connect_callback (Proc | nil) —

    Optional callable that establishes the TCP connection to a KMS provider. It is invoked with the host, port, and operation timeout in milliseconds (or nil), and must return an IO connected to the host.

Options Hash (mongocryptd_options:):

  • :mongocryptd_bypass_spawn (Boolean)
  • :mongocryptd_spawn_path (String)
  • :mongocryptd_spawn_args (Array<String>)
[ GitHub ]

  
# File 'lib/mongo/crypt/encryption_io.rb', line 58

def initialize(
  key_vault_namespace:, key_vault_client:, metadata_client:, client: nil, mongocryptd_client: nil, mongocryptd_options: {}, kms_connect_callback: nil
)
  validate_key_vault_client!(key_vault_client)
  validate_key_vault_namespace!(key_vault_namespace)
  if kms_connect_callback && !kms_connect_callback.respond_to?(:call)
    raise ArgumentError, 'kms_connect_callback must respond to :call'
  end

  @client = client
  @mongocryptd_client = mongocryptd_client
  @key_vault_db_name, @key_vault_collection_name = key_vault_namespace.split('.')
  @key_vault_client = key_vault_client
  @metadata_client = 
  @options = mongocryptd_options
  @kms_connect_callback = kms_connect_callback
end

Instance Method Details

#add_key_alt_name(id, key_alt_name, timeout_ms: nil)

Adds a key_alt_name to the key_alt_names array of the key document in the key vault collection with the given id.

[ GitHub ]

  
# File 'lib/mongo/crypt/encryption_io.rb', line 205

def add_key_alt_name(id, key_alt_name, timeout_ms: nil)
  key_vault_collection.find_one_and_update(
    { _id: id },
    { '$addToSet' => { keyAltNames: key_alt_name } },
    timeout_ms: timeout_ms
  )
end

#collection_info(db_name, filter, timeout_ms: nil) ⇒ Array<BSON::Document>

Get collection info for a collection matching the provided filter

Parameters:

  • filter (Hash)
  • :timeout_ms (Integer) —

    The operation timeout in milliseconds. Must be a non-negative integer. An explicit value of 0 means infinite. The default value is unset which means the feature is not enabled.

Returns:

  • (Array<BSON::Document>) —

    The collection information documents

[ GitHub ]

  
# File 'lib/mongo/crypt/encryption_io.rb', line 109

def collection_info(db_name, filter, timeout_ms: nil)
  unless @metadata_client
    raise ArgumentError,
          'collection_info requires metadata_client to have been passed to the constructor, but it was not'
  end

  @metadata_client
    .use(db_name)
    .database
    .list_collections(filter: filter, deserialize_as_bson: true, timeout_ms: timeout_ms)
    .to_a
end

#connect_budget(timeout_ms) ⇒ Float (private)

The budget for the connect phase, in seconds: the remaining operation timeout when a CSOT budget is in effect, otherwise the driver's fixed connect timeout. The connect callback and the TLS handshake that follows it share this budget, so neither can run past the deadline.

Parameters:

  • timeout_ms (Integer, nil) —

    The remaining operation timeout in milliseconds, or nil when no budget is set.

Returns:

  • (Float) —

    The connect budget in seconds.

[ GitHub ]

  
# File 'lib/mongo/crypt/encryption_io.rb', line 301

def connect_budget(timeout_ms)
  timeout_ms ? timeout_ms / 1_000.0 : Server::CONNECT_TIMEOUT
end

#delete_key(id, timeout_ms: nil)

Removes the key document with the given id from the key vault collection.

[ GitHub ]

  
# File 'lib/mongo/crypt/encryption_io.rb', line 215

def delete_key(id, timeout_ms: nil)
  key_vault_collection.delete_one(_id: id, timeout_ms: timeout_ms)
end

#feed_kms(kms_context, tls_options, timeout_ms: nil)

Get information about the remote KMS encryption key and feed it to the the KmsContext object

Parameters:

  • kms_context (Mongo::Crypt::KmsContext) —

    A KmsContext object corresponding to one remote KMS data key. Contains information about the endpoint at which to establish a TLS connection and the message to send on that connection.

  • tls_options. (Hash) —

    TLS options to connect to KMS provider. The options are same as for ::Mongo::Client.

  • :timeout_ms (Integer) —

    The operation timeout in milliseconds. Must be a non-negative integer. An explicit value of 0 means infinite. The default value is unset which means the feature is not enabled.

[ GitHub ]

  
# File 'lib/mongo/crypt/encryption_io.rb', line 173

def feed_kms(kms_context, tls_options, timeout_ms: nil)
  # When a budget is in effect the TLS handshake, the request write, and
  # every read chunk share a single deadline, so a slow, chunked response
  # cannot run for a multiple of the budget. Without a budget each phase
  # keeps the fixed SOCKET_TIMEOUT fallback. Timeout.timeout takes
  # seconds, but timeout_ms is in milliseconds.
  deadline = Utils.monotonic_time + (timeout_ms / 1_000.0) if timeout_ms
  # Use the CSOT-appropriate error class when a timeout budget is
  # in effect, otherwise preserve the historical SocketTimeoutError.
  timeout_error = timeout_ms ? Error::TimeoutError : Error::SocketTimeoutError

  with_ssl_socket(kms_context.endpoint, tls_options, timeout_ms: timeout_ms) do |ssl_socket|
    Timeout.timeout(remaining_timeout(deadline), timeout_error,
                    'Socket write operation timed out') do
      ssl_socket.syswrite(kms_context.message)
    end

    bytes_needed = kms_context.bytes_needed
    while bytes_needed > 0
      bytes = Timeout.timeout(remaining_timeout(deadline), timeout_error,
                              'Socket read operation timed out') do
        ssl_socket.sysread(bytes_needed)
      end

      kms_context.feed(bytes)
      bytes_needed = kms_context.bytes_needed
    end
  end
end

#find_keys(filter, timeout_ms: nil) ⇒ Array<BSON::Document>

Query for keys in the key vault collection using the provided filter

Parameters:

  • filter (Hash)
  • :timeout_ms (Integer) —

    The operation timeout in milliseconds. Must be a non-negative integer. An explicit value of 0 means infinite. The default value is unset which means the feature is not enabled.

Returns:

  • (Array<BSON::Document>) —

    The query results

[ GitHub ]

  
# File 'lib/mongo/crypt/encryption_io.rb', line 85

def find_keys(filter, timeout_ms: nil)
  key_vault_collection.find(filter, timeout_ms: timeout_ms).to_a
end

#get_key(id, timeout_ms: nil)

Finds a single key document with the given id.

[ GitHub ]

  
# File 'lib/mongo/crypt/encryption_io.rb', line 220

def get_key(id, timeout_ms: nil)
  key_vault_collection.find(_id: id, timeout_ms: timeout_ms).first
end

#get_key_by_alt_name(key_alt_name, timeout_ms: nil)

Returns a key document in the key vault collection with the given key_alt_name.

[ GitHub ]

  
# File 'lib/mongo/crypt/encryption_io.rb', line 226

def get_key_by_alt_name(key_alt_name, timeout_ms: nil)
  key_vault_collection.find(keyAltNames: key_alt_name, timeout_ms: timeout_ms).first
end

#get_keys(timeout_ms: nil)

Finds all documents in the key vault collection.

[ GitHub ]

  
# File 'lib/mongo/crypt/encryption_io.rb', line 231

def get_keys(timeout_ms: nil)
  key_vault_collection.find(nil, timeout_ms: timeout_ms)
end

#insert_data_key(document, timeout_ms: nil) ⇒ Mongo::Operation::Insert::Result

Insert a document into the key vault collection

Parameters:

  • document (Hash)
  • :timeout_ms (Integer) —

    The operation timeout in milliseconds. Must be a non-negative integer. An explicit value of 0 means infinite. The default value is unset which means the feature is not enabled.

Returns:

[ GitHub ]

  
# File 'lib/mongo/crypt/encryption_io.rb', line 97

def insert_data_key(document, timeout_ms: nil)
  key_vault_collection.insert_one(document, timeout_ms: timeout_ms)
end

#key_vault_collection (private)

Use the provided key vault client and namespace to construct a ::Mongo::Collection object representing the key vault collection.

[ GitHub ]

  
# File 'lib/mongo/crypt/encryption_io.rb', line 328

def key_vault_collection
  @key_vault_collection ||= @key_vault_client.with(
    database: @key_vault_db_name,
    read_concern: { level: :majority },
    write_concern: { w: :majority }
  )[@key_vault_collection_name]
end

#mark_command(cmd, db_name: nil, timeout_ms: nil) ⇒ Hash

Send the command to mongocryptd to be marked with intent-to-encrypt markings

Parameters:

  • cmd (Hash)
  • :db_name (String | nil) —

    The database against which the command is being run. When provided, the command is sent to mongocryptd using this database so that the namespace in the command matches the namespace in encryptionInformation.

  • :timeout_ms (Integer) —

    The operation timeout in milliseconds. Must be a non-negative integer. An explicit value of 0 means infinite. The default value is unset which means the feature is not enabled.

Returns:

  • (Hash) —

    The marked command

[ GitHub ]

  
# File 'lib/mongo/crypt/encryption_io.rb', line 134

def mark_command(cmd, db_name: nil, timeout_ms: nil)
  unless @mongocryptd_client
    raise ArgumentError,
          'mark_command requires mongocryptd_client to have been passed to the constructor, but it was not'
  end

  # Ensure the response from mongocryptd is deserialized with { mode: :bson }
  # to prevent losing type information in commands
  options = {
    execution_options: { deserialize_as_bson: true },
    timeout_ms: timeout_ms
  }

  mongocryptd = db_name ? @mongocryptd_client.use(db_name) : @mongocryptd_client

  begin
    response = mongocryptd.database.command(cmd, options)
  rescue Error::NoServerAvailable => e
    raise e if @options[:mongocryptd_bypass_spawn]

    spawn_mongocryptd
    response = mongocryptd.database.command(cmd, options)
  end

  response.first
end

#remaining_timeout(deadline) ⇒ Float (private)

The time left, in seconds, before the shared KMS exchange deadline. When no operation budget is in effect there is no deadline, so each phase falls back to the fixed SOCKET_TIMEOUT.

Parameters:

  • deadline (Float, nil) —

    The monotonic time the exchange must finish by, or nil when no budget is set.

Returns:

  • (Float) —

    The number of seconds left before the deadline.

Raises:

[ GitHub ]

  
# File 'lib/mongo/crypt/encryption_io.rb', line 283

def remaining_timeout(deadline)
  return SOCKET_TIMEOUT if deadline.nil?

  remaining = deadline - Utils.monotonic_time
  raise Error::TimeoutError, 'KMS request timed out' if remaining <= 0

  remaining
end

#remove_key_alt_name(id, key_alt_name, timeout_ms: nil)

Removes a key_alt_name from the key_alt_names array of the key document in the key vault collection with the given id.

[ GitHub ]

  
# File 'lib/mongo/crypt/encryption_io.rb', line 237

def remove_key_alt_name(id, key_alt_name, timeout_ms: nil)
  key_vault_collection.find_one_and_update(
    { _id: id },
    [
      {
        '$set' => {
          keyAltNames: {
            '$cond' => [
              { '$eq' => [ '$keyAltNames', [ key_alt_name ] ] },
              '$$REMOVE',
              {
                '$filter' => {
                  input: '$keyAltNames',
                  cond: { '$ne' => [ '$$this', key_alt_name ] }
                }
              }
            ]
          }
        }
      }
    ],
    timeout_ms: timeout_ms
  )
end

#spawn_mongocryptd ⇒ Integer (private)

Note:

To capture the mongocryptd logs, add "--logpath=/path/to/logs" to auto_encryption_options -> extra_options -> mongocrpytd_spawn_args

Spawn a new mongocryptd process using the mongocryptd_spawn_path and mongocryptd_spawn_args passed in through the extra auto encrypt options. Stdout and Stderr of this new process are written to /dev/null.

Returns:

  • (Integer) —

    The process id of the spawned process

Raises:

  • (ArgumentError) —

    Raises an exception if no encryption options have been provided

[ GitHub ]

  
# File 'lib/mongo/crypt/encryption_io.rb', line 348

def spawn_mongocryptd
  mongocryptd_spawn_args = @options[:mongocryptd_spawn_args]
  mongocryptd_spawn_path = @options[:mongocryptd_spawn_path]

  unless mongocryptd_spawn_path
    raise ArgumentError.new(
      'Cannot spawn mongocryptd process when no ' +
      ':mongocryptd_spawn_path option is provided'
    )
  end

  if mongocryptd_spawn_path.nil? ||
     mongocryptd_spawn_args.nil? || mongocryptd_spawn_args.empty?
    raise ArgumentError.new(
      'Cannot spawn mongocryptd process when no :mongocryptd_spawn_args ' +
      'option is provided. To start mongocryptd without arguments, pass ' +
      '"--" for :mongocryptd_spawn_args'
    )
  end

  begin
    Process.spawn(
      mongocryptd_spawn_path,
      *mongocryptd_spawn_args,
      %i[out err] => '/dev/null'
    )
  rescue Errno::ENOENT => e
    raise Error::MongocryptdSpawnError.new(
      "Failed to spawn mongocryptd at the path \"#{mongocryptd_spawn_path}\" " +
      "with arguments #{mongocryptd_spawn_args}. Received error " +
      "#{e.class}: \"#{e.message}\""
    )
  end
end

#update_data_keys(updates, timeout_ms: nil) ⇒ BulkWrite::Result

Apply given requests to the key vault collection using bulk write.

Parameters:

  • requests (Array<Hash>) —

    The bulk write requests.

Returns:

[ GitHub ]

  
# File 'lib/mongo/crypt/encryption_io.rb', line 267

def update_data_keys(updates, timeout_ms: nil)
  key_vault_collection.bulk_write(updates, timeout_ms: timeout_ms)
end

#validate_key_vault_client!(key_vault_client) (private)

Raises:

  • (ArgumentError)
[ GitHub ]

  
# File 'lib/mongo/crypt/encryption_io.rb', line 305

def validate_key_vault_client!(key_vault_client)
  raise ArgumentError.new('The :key_vault_client option cannot be nil') unless key_vault_client

  return if key_vault_client.is_a?(Client)

  raise ArgumentError.new(
    'The :key_vault_client option must be an instance of Mongo::Client'
  )
end

#validate_key_vault_namespace!(key_vault_namespace) (private)

Raises:

  • (ArgumentError)
[ GitHub ]

  
# File 'lib/mongo/crypt/encryption_io.rb', line 315

def validate_key_vault_namespace!(key_vault_namespace)
  raise ArgumentError.new('The :key_vault_namespace option cannot be nil') unless key_vault_namespace

  return if key_vault_namespace.split('.').length == 2

  raise ArgumentError.new(
    "#{key_vault_namespace} is an invalid key vault namespace." +
    'The :key_vault_namespace option must be in the format database.collection'
  )
end

#with_ssl_socket(endpoint, tls_options, timeout_ms: nil) {|ssl_socket| ... } (private)

Note:

The socket is always closed when the provided block has finished executing

Provide a TLS socket to be used for KMS calls in a block API

Parameters:

  • endpoint (String) —

    The URI at which to connect the TLS socket.

  • tls_options. (Hash) —

    TLS options to connect to KMS provider. The options are same as for ::Mongo::Client.

Yield Parameters:

  • ssl_socket (OpenSSL::SSL::SSLSocket) —

    Yields a TLS socket connected to the specified endpoint.

Raises:

[ GitHub ]

  
# File 'lib/mongo/crypt/encryption_io.rb', line 396

def with_ssl_socket(endpoint, tls_options, timeout_ms: nil)
  csot = !timeout_ms.nil?
  host, port = endpoint.split(':')
  port = (port || 443).to_i

  mongo_socket =
    if @kms_connect_callback
      # The callback runs before any socket exists, so it cannot inherit
      # the connect timeout the socket gets below; bound it explicitly by
      # the connect budget so a callback that blocks cannot outlive the
      # operation deadline. A well-behaved callback should still honor
      # timeout_ms itself, so it can fail cleanly and close its socket.
      connect_budget_sec = connect_budget(timeout_ms)
      connect_deadline = Utils.monotonic_time + connect_budget_sec
      connect_error = csot ? Error::TimeoutError : Error::SocketTimeoutError
      connected_socket =
        Timeout.timeout(connect_budget_sec, connect_error,
                        'KMS connect callback timed out') do
          @kms_connect_callback.call(host, port, timeout_ms)
        end
      unless connected_socket.is_a?(IO)
        raise Error::KmsError.new(
          'kms_connect_callback must return an IO connected to the KMS provider ' +
          "at #{host}:#{port}, but it returned #{connected_socket.inspect}"
        )
      end

      # The callback and the handshake share one connect budget: give the
      # handshake only the time the callback left, so together they cannot
      # run past the deadline.
      remaining_connect = connect_deadline - Utils.monotonic_time
      raise connect_error, 'KMS connect timed out' if remaining_connect <= 0

      socket_options = { ssl: true, csot: csot, connected_socket: connected_socket }
      socket_options[:connect_timeout] = remaining_connect
      Mongo::Socket::SSL.new(
        host, port, host, SOCKET_TIMEOUT, ::Socket::AF_UNSPEC,
        tls_options.merge(socket_options)
      )
    else
      address = Address.new([ host, port ].join(':'))
      socket_options = { ssl: true, csot: csot }.tap do |opts|
        opts[:connect_timeout] = (timeout_ms / 1_000.0) if csot
      end
      address.socket(SOCKET_TIMEOUT, tls_options.merge(socket_options))
    end

  yield(mongo_socket.socket)
rescue Error::KmsError
  raise
rescue StandardError => e
  # A timeout is not a transient network failure: retrying it only spends
  # more of the operation budget, and under CSOT the deadline has already
  # passed, so let it surface instead of letting feed_kms retry.
  raise Error::KmsError.new("Error when connecting to KMS provider: #{e.class}: #{e.message}",
                            network_error: !e.is_a?(Error::TimeoutError))
ensure
  mongo_socket&.close
end