Class: Lockbox

Inherits:
Object
  • Object
show all
Defined in:
lib/lockbox/active_storage_extensions.rb,
lib/lockbox.rb,
lib/lockbox/box.rb,
lib/lockbox/model.rb,
lib/lockbox/utils.rb,
lib/lockbox/aes_gcm.rb,
lib/lockbox/railtie.rb,
lib/lockbox/version.rb,
lib/lockbox/encryptor.rb,
lib/lockbox/key_generator.rb,
lib/lockbox/carrier_wave_extensions.rb

Overview

ideally encrypt and decrypt would happen at the blob/service level however, there isn’t really a great place to define encryption settings there instead, we encrypt and decrypt at the attachment level, and we define encryption settings at the model level

Defined Under Namespace

Modules: ActiveStorageExtensions, CarrierWaveExtensions, Model Classes: AES_GCM, Box, DecryptionError, Encryptor, Error, KeyGenerator, Railtie, Utils

Constant Summary collapse

VERSION =
"0.2.0"

Class Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(**options) ⇒ Lockbox

Returns a new instance of Lockbox.



72
73
74
75
76
77
78
79
# File 'lib/lockbox.rb', line 72

def initialize(**options)
  options = self.class.default_options.merge(options)
  previous_versions = options.delete(:previous_versions)

  @boxes =
    [Box.new(options)] +
    Array(previous_versions).map { |v| Box.new(v) }
end

Class Attribute Details

.default_optionsObject

Returns the value of attribute default_options.



27
28
29
# File 'lib/lockbox.rb', line 27

def default_options
  @default_options
end

.master_keyObject



32
33
34
# File 'lib/lockbox.rb', line 32

def self.master_key
  @master_key ||= ENV["LOCKBOX_MASTER_KEY"]
end

Class Method Details

.attribute_key(table:, attribute:, master_key: nil, encode: true) ⇒ Object

Raises:

  • (ArgumentError)


129
130
131
132
133
134
135
136
# File 'lib/lockbox.rb', line 129

def self.attribute_key(table:, attribute:, master_key: nil, encode: true)
  master_key ||= Lockbox.master_key
  raise ArgumentError, "Missing master key" unless master_key

  key = Lockbox::KeyGenerator.new(master_key).attribute_key(table: table, attribute: attribute)
  key = to_hex(key) if encode
  key
end

.generate_keyObject



111
112
113
# File 'lib/lockbox.rb', line 111

def self.generate_key
  SecureRandom.hex(32)
end

.generate_key_pairObject



115
116
117
118
119
120
121
122
123
124
125
126
127
# File 'lib/lockbox.rb', line 115

def self.generate_key_pair
  require "rbnacl"
  # encryption and decryption servers exchange public keys
  # this produces smaller ciphertext than sealed box
  alice = RbNaCl::PrivateKey.generate
  bob = RbNaCl::PrivateKey.generate
  # alice is sending message to bob
  # use bob first in both cases to prevent keys being swappable
  {
    encryption_key: to_hex(bob.public_key.to_bytes + alice.to_bytes),
    decryption_key: to_hex(bob.to_bytes + alice.public_key.to_bytes)
  }
end

.migrate(model, restart: false) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/lockbox.rb', line 36

def self.migrate(model, restart: false)
  # get fields
  fields = model.lockbox_attributes.select { |k, v| v[:migrating] }

  # get blind indexes
  blind_indexes = model.respond_to?(:blind_indexes) ? model.blind_indexes.select { |k, v| v[:migrating] } : {}

  # build relation
  relation = model.unscoped

  unless restart
    attributes = fields.map { |_, v| v[:encrypted_attribute] }
    attributes += blind_indexes.map { |_, v| v[:bidx_attribute] }

    attributes.each_with_index do |attribute, i|
      relation =
        if i == 0
          relation.where(attribute => nil)
        else
          relation.or(model.where(attribute => nil))
        end
    end
  end

  # migrate
  relation.find_each do |record|
    fields.each do |k, v|
      record.send("#{v[:attribute]}=", record.send(k)) if restart || !record.send(v[:encrypted_attribute])
    end
    blind_indexes.each do |k, v|
      record.send("compute_#{k}_bidx") if restart || !record.send(v[:bidx_attribute])
    end
    record.save(validate: false) if record.changed?
  end
end

.to_hex(str) ⇒ Object



138
139
140
# File 'lib/lockbox.rb', line 138

def self.to_hex(str)
  str.unpack("H*").first
end

Instance Method Details

#decrypt(ciphertext, **options) ⇒ Object



86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
# File 'lib/lockbox.rb', line 86

def decrypt(ciphertext, **options)
  ciphertext = check_string(ciphertext, "ciphertext")

  # ensure binary
  if ciphertext.encoding != Encoding::BINARY
    # dup to prevent mutation
    ciphertext = ciphertext.dup.force_encoding(Encoding::BINARY)
  end

  @boxes.each_with_index do |box, i|
    begin
      return box.decrypt(ciphertext, **options)
    rescue => e
      error_classes = [DecryptionError]
      error_classes << RbNaCl::LengthError if defined?(RbNaCl::LengthError)
      error_classes << RbNaCl::CryptoError if defined?(RbNaCl::CryptoError)
      if error_classes.any? { |ec| e.is_a?(ec) }
        raise DecryptionError, "Decryption failed" if i == @boxes.size - 1
      else
        raise e
      end
    end
  end
end

#encrypt(message, **options) ⇒ Object



81
82
83
84
# File 'lib/lockbox.rb', line 81

def encrypt(message, **options)
  message = check_string(message, "message")
  @boxes.first.encrypt(message, **options)
end