Module: Lockbox::Model
- Defined in:
- lib/lockbox/model.rb
Defined Under Namespace
Modules: Attached
Instance Method Summary collapse
Instance Method Details
#encrypts(*attributes, **options) ⇒ Object
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 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 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 |
# File 'lib/lockbox/model.rb', line 3 def encrypts(*attributes, **) # support objects # case options[:type] # when Date # options[:type] = :date # when Time # options[:type] = :datetime # when JSON # options[:type] = :json # when Hash # options[:type] = :hash # when Array # options[:type] = :array # when String # options[:type] = :string # when Integer # options[:type] = :integer # when Float # options[:type] = :float # end custom_type = [:type].respond_to?(:serialize) && [:type].respond_to?(:deserialize) raise ArgumentError, "Unknown type: #{[:type]}" unless custom_type || [nil, :string, :boolean, :date, :datetime, :time, :integer, :float, :binary, :json, :hash, :array].include?([:type]) activerecord = defined?(ActiveRecord::Base) && self < ActiveRecord::Base raise ArgumentError, "Type not supported yet with Mongoid" if [:type] && !activerecord attributes.each do |name| # add default options encrypted_attribute = "#{name}_ciphertext" = .dup # migrating original_name = name.to_sym name = "migrated_#{name}" if [:migrating] name = name.to_sym [:attribute] = name.to_s [:encrypted_attribute] = encrypted_attribute [:encode] = true unless .key?(:encode) encrypt_method_name = "generate_#{encrypted_attribute}" decrypt_method_name = "decrypt_#{encrypted_attribute}" class_eval do @lockbox_attributes ||= {} if @lockbox_attributes.empty? def self.lockbox_attributes parent_attributes = if superclass.respond_to?(:lockbox_attributes) superclass.lockbox_attributes else {} end parent_attributes.merge(@lockbox_attributes || {}) end # use same approach as activerecord serialization def serializable_hash( = nil) = .try(:dup) || {} [:except] = Array([:except]) [:except] += self.class.lockbox_attributes.flat_map { |_, v| [v[:attribute], v[:encrypted_attribute]] } super() end # use same approach as devise def inspect inspection = serializable_hash.map do |k,v| "#{k}: #{respond_to?(:attribute_for_inspect) ? attribute_for_inspect(k) : v.inspect}" end "#<#{self.class} #{inspection.join(", ")}>" end if activerecord # TODO wrap in module? def attributes # load attributes # essentially a no-op if already loaded # an exception is thrown if decryption fails self.class.lockbox_attributes.each do |_, lockbox_attribute| # it is possible that the encrypted attribute is not loaded, eg. # if the record was fetched partially (`User.select(:id).first`). # accessing a not loaded attribute raises an `ActiveModel::MissingAttributeError`. send(lockbox_attribute[:attribute]) if has_attribute?(lockbox_attribute[:encrypted_attribute]) end super end # needed for in-place modifications # assigned attributes are encrypted on assignment # and then again here before_save do self.class.lockbox_attributes.each do |_, lockbox_attribute| attribute = lockbox_attribute[:attribute] if attribute_changed_in_place?(attribute) send("#{attribute}=", send(attribute)) end end end else def reload self.class.lockbox_attributes.each do |_, v| instance_variable_set("@#{v[:attribute]}", nil) end super end end end raise "Duplicate encrypted attribute: #{original_name}" if lockbox_attributes[original_name] @lockbox_attributes[original_name] = if activerecord # preference: # 1. type option # 2. existing virtual attribute # 3. default to string (which can later be overridden) if [:type] attribute_type = case [:type] when :json, :hash, :array :string when :integer ActiveModel::Type::Integer.new(limit: 8) else [:type] end attribute name, attribute_type serialize name, JSON if [:type] == :json serialize name, Hash if [:type] == :hash serialize name, Array if [:type] == :array elsif !attributes_to_define_after_schema_loads.key?(name.to_s) # when migrating it's best to specify the type directly # however, we can try to use the original type if its already defined if attributes_to_define_after_schema_loads.key?(original_name.to_s) attribute name, attributes_to_define_after_schema_loads[original_name.to_s].first elsif [:migrating] # we use the original attribute for serialization in the encrypt and decrypt methods # so we can use a generic value here attribute name, ActiveRecord::Type::Value.new else attribute name, :string end end define_method("#{name}_was") do send(name) # writes attribute when not already set super() end # restore ciphertext as well define_method("restore_#{name}!") do super() send("restore_#{encrypted_attribute}!") end if ActiveRecord::VERSION::STRING >= "5.1" define_method("#{name}_in_database") do send(name) # writes attribute when not already set super() end end else # keep this module dead simple # Mongoid uses changed_attributes to calculate keys to update # so we shouldn't mess with it m = Module.new do define_method("#{name}=") do |val| instance_variable_set("@#{name}", val) end define_method(name) do instance_variable_get("@#{name}") end end include m alias_method "#{name}_changed?", "#{encrypted_attribute}_changed?" define_method "#{name}_was" do ciphertext = send("#{encrypted_attribute}_was") self.class.send(decrypt_method_name, ciphertext, context: self) end define_method "#{name}_change" do ciphertexts = send("#{encrypted_attribute}_change") ciphertexts.map { |v| self.class.send(decrypt_method_name, v, context: self) } if ciphertexts end define_method "reset_#{name}!" do instance_variable_set("@#{name}", nil) send("reset_#{encrypted_attribute}!") send(name) end define_method "reset_#{name}_to_default!" do instance_variable_set("@#{name}", nil) send("reset_#{encrypted_attribute}_to_default!") send(name) end end define_method("#{name}?") do send("#{encrypted_attribute}?") end define_method("#{name}=") do || # decrypt first for dirty tracking # don't raise error if can't decrypt previous begin send(name) rescue Lockbox::DecryptionError # this is expected for hybrid cryptography warn "[lockbox] Decrypting previous value failed" unless [:algorithm] == "hybrid" nil end send("lockbox_direct_#{name}=", ) # warn every time, as this should be addressed # maybe throw an error in the future if ![:migrating] if activerecord if self.class.columns_hash.key?(name.to_s) warn "[lockbox] WARNING: Unencrypted column with same name: #{name}. Set `ignored_columns` or remove it to protect the data." end else if self.class.fields.key?(name.to_s) warn "[lockbox] WARNING: Unencrypted field with same name: #{name}. Remove it to protect the data." end end end super() end # separate method for setting directly # used to skip blind indexes for key rotation define_method("lockbox_direct_#{name}=") do || ciphertext = self.class.send(encrypt_method_name, , context: self) send("#{encrypted_attribute}=", ciphertext) end private :"lockbox_direct_#{name}=" define_method(name) do = super() # possibly keep track of decrypted attributes directly in the future # Hash serializer returns {} when nil, Array serializer returns [] when nil # check for this explicitly as a layer of safety if .nil? || (( == {} || == []) && activerecord && @attributes[name.to_s].value_before_type_cast.nil?) ciphertext = send(encrypted_attribute) = self.class.send(decrypt_method_name, ciphertext, context: self) if activerecord # set previous attribute so changes populate correctly # it's fine if this is set on future decryptions (as is the case when message is nil) # as only the first value is loaded into changes @attributes[name.to_s].instance_variable_set("@value_before_type_cast", ) # cache # decrypt method does type casting if respond_to?(:write_attribute_without_type_cast, true) write_attribute_without_type_cast(name.to_s, ) if !@attributes.frozen? else raw_write_attribute(name, ) if !@attributes.frozen? end else instance_variable_set("@#{name}", ) end end end # for fixtures define_singleton_method encrypt_method_name do |, **opts| table = activerecord ? table_name : collection_name.to_s unless .nil? # TODO use attribute type class in 0.5.0 case [:type] when :boolean = ActiveRecord::Type::Boolean.new.serialize() = nil if == "" # for Active Record < 5.2 = ? "t" : "f" unless .nil? when :date = ActiveRecord::Type::Date.new.serialize() # strftime should be more stable than to_s(:db) = .strftime("%Y-%m-%d") unless .nil? when :datetime = ActiveRecord::Type::DateTime.new.serialize() = nil unless .respond_to?(:iso8601) # for Active Record < 5.2 = .iso8601(9) unless .nil? when :time = ActiveRecord::Type::Time.new.serialize() = nil unless .respond_to?(:strftime) = .strftime("%H:%M:%S.%N") unless .nil? when :integer = ActiveRecord::Type::Integer.new(limit: 8).serialize() = 0 if .nil? # signed 64-bit integer, big endian = [].pack("q>") when :float = ActiveRecord::Type::Float.new.serialize() # double precision, big endian = [].pack("G") unless .nil? when :string, :binary # do nothing # encrypt will convert to binary else # use original name for serialized attributes type = (try(:attribute_types) || {})[original_name.to_s] = type.serialize() if type end end if .nil? || ( == "" && ![:padding]) else Lockbox::Utils.build_box(opts[:context], , table, encrypted_attribute).encrypt() end end define_singleton_method decrypt_method_name do |ciphertext, **opts| = if ciphertext.nil? || (ciphertext == "" && ![:padding]) ciphertext else table = activerecord ? table_name : collection_name.to_s Lockbox::Utils.build_box(opts[:context], , table, encrypted_attribute).decrypt(ciphertext) end unless .nil? # TODO use attribute type class in 0.5.0 case [:type] when :boolean = == "t" when :date = ActiveRecord::Type::Date.new.deserialize() when :datetime = ActiveRecord::Type::DateTime.new.deserialize() when :time = ActiveRecord::Type::Time.new.deserialize() when :integer = ActiveRecord::Type::Integer.new(limit: 8).deserialize(.unpack("q>").first) when :float = ActiveRecord::Type::Float.new.deserialize(.unpack("G").first) when :string .force_encoding(Encoding::UTF_8) when :binary # do nothing # decrypt returns binary string else # use original name for serialized attributes type = (try(:attribute_types) || {})[original_name.to_s] = type.deserialize() if type .force_encoding(Encoding::UTF_8) if !type || type.is_a?(ActiveModel::Type::String) end end end if [:migrating] # TODO reuse module m = Module.new do define_method "#{original_name}=" do |value| result = super(value) send("#{name}=", send(original_name)) result end unless activerecord define_method "reset_#{original_name}!" do result = super() send("#{name}=", send(original_name)) result end end end prepend m end end end end |