reidmorrison / symmetric-encryption

Symmetric Encryption for Ruby Projects using OpenSSL
https://logger.rocketjob.github.io/
Apache License 2.0
475 stars 92 forks source link

Setting attribute to empty string changes it to null #77

Closed airblade closed 7 years ago

airblade commented 7 years ago

I have a Rails 5 app with a model which has an encrypted attribute.

class User < ApplicationRecord
  attr_encrypted :foo, random_iv: true
end

When I set foo to an empty string and save, the system tries to update foo in the database with a nil value. I would expect it to send an empty string to the database, not nil.

>> u = User.last
>> u.foo = 'bar'    # this works as expected
>> u.save
=> UPDATE "users" SET "encrypted_foo" = $1, "updated_at" = $2 WHERE "users"."id" = $3  [["encrypted_foo", "QEVuQwBAEAC8lTgA/00QFleREee9wARnATR8ZA78uN/MxVogSDjftA=="], ["updated_at", 2017-05-16 15:32:45 UTC], ["id", 1]]

>> u.foo = ''    # this does not work as expected
>> u.save
=> UPDATE "users" SET "encrypted_foo" = $1, "updated_at" = $2 WHERE "users"."id" = $3  [["encrypted_foo", nil], ["updated_at", 2017-05-16 15:32:45 UTC], ["id", 1]]

I'm using symmetric-encryption 3.9.0, rails 5.0.1.

airblade commented 7 years ago

The generator coerces the empty string:

# Here value is "" and type is "string"
v = SymmetricEncryption::Coerce.coerce(value, :#{type})

– and the coercion turns the empty string into nil:

return if blank?(value)

Shouldn't "coercing" a :string attribute to a string leave it untouched? And, in this case, leave an empty string as an empty string?

dpneumo commented 7 years ago

Have noticed the same behavior and agree the appropriate behavior is to leave an empty string as an empty string after coercion.

reidmorrison commented 7 years ago

Agreed, looked at briefly but looks like it is deep in the Coerce code somewhere.

Definitely want this to be fixed though as converting nil to '' is not expected behavior.

airblade commented 7 years ago

Thanks!

dpneumo commented 7 years ago

Thanks.

On Mon, Jul 24, 2017 at 3:48 AM, Andy Stewart notifications@github.com wrote:

Thanks!

— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/rocketjob/symmetric-encryption/issues/77#issuecomment-317358653, or mute the thread https://github.com/notifications/unsubscribe-auth/ABKr1ay8fQC2_iLqSBZ-PKHX9Ecorfuyks5sRFpagaJpZM4NcsJw .