W3cubDocs

/Ruby on Rails 7.0

module ActiveRecord::Encryption::Contexts

ActiveRecord::Encryption uses encryption contexts to configure the different entities used to encrypt/decrypt at a given moment in time.

By default, the library uses a default encryption context. This is the Context that gets configured initially via config.active_record.encryption options. Library users can define nested encryption contexts when running blocks of code.

See Context.

Public Instance Methods

context() Show source
# File activerecord/lib/active_record/encryption/contexts.rb, line 62
def context
  self.current_custom_context || self.default_context
end

Returns the current context. By default it will return the current context.

current_custom_context() Show source
# File activerecord/lib/active_record/encryption/contexts.rb, line 66
def current_custom_context
  self.custom_contexts&.last
end
protecting_encrypted_data(&block) Show source
# File activerecord/lib/active_record/encryption/contexts.rb, line 57
def protecting_encrypted_data(&block)
  with_encryption_context encryptor: ActiveRecord::Encryption::EncryptingOnlyEncryptor.new, frozen_encryption: true, &block
end

Runs the provided block in an encryption context where:

  • Reading encrypted content will return its ciphertext.

  • Writing encrypted content will fail.

with_encryption_context(properties) { || ... } Show source
# File activerecord/lib/active_record/encryption/contexts.rb, line 33
def with_encryption_context(properties)
  self.custom_contexts ||= []
  self.custom_contexts << default_context.dup
  properties.each do |key, value|
    self.current_custom_context.send("#{key}=", value)
  end

  yield
ensure
  self.custom_contexts.pop
end

Configures a custom encryption context to use when running the provided block of code.

It supports overriding all the properties defined in Context.

Example:

ActiveRecord::Encryption.with_encryption_context(encryptor: ActiveRecord::Encryption::NullEncryptor.new) do
  ...
end

Encryption contexts can be nested.

without_encryption(&block) Show source
# File activerecord/lib/active_record/encryption/contexts.rb, line 49
def without_encryption(&block)
  with_encryption_context encryptor: ActiveRecord::Encryption::NullEncryptor.new, &block
end

Runs the provided block in an encryption context where encryption is disabled:

  • Reading encrypted content will return its ciphertexts.

  • Writing encrypted content will write its clear text.

© 2004–2021 David Heinemeier Hansson
Licensed under the MIT License.