mogilvie / EncryptBundle

Encryption bundle
82 stars 27 forks source link

Encrypted value on entity connected through relation is updated at every flush #27

Closed moorscode closed 2 years ago

moorscode commented 2 years ago

We've got the following setup:

Entity A

Entity B

While flushing the entity manager, without any changes on either entity A or entity B; the ORM sees a changed value for the Enc property on Entity A through the relation with Entity B.

This is due to the "oid" of the Entity A relation being different from the "oid" of the "actual?" entity A. This "oid" seems to be a 3 digit number instead of a hexadecimal format.

In short, having a relationship with an entity that has encrypted properties will not work as expected.

On every flush() the value will be rewritten (with a value that can be decrypted, so it's usable) to the database with a transaction, update and commit command.

mogilvie commented 2 years ago

Hi @moorscode

If you're loading entity A and it is a managed entity, then the bundle will re-encrypt the values period during the onFlush event.

The reason the encryption value changes (despite the unencrypted value not intentionally being changed) is because encryption is salted, and the new encrypted value is re-committed to the DB.

However, this does create additional work in the persistance processes.

The oid is a different subject that is not the cause of this behaviour. However, I have updated the oid generation in the event subscriber to match the doctrine method now. So the oid will look the same.

I have also added a cached array of original encryption values and their associated un-encrypted fields. The DoctrineEncryptSubscriber will now compare the onFlush entity fields against this onLoad decrypted cache. If the unencrypted value has not changed between the onLoad and onFlush events, then the subscriber will remove the field from the UoW changedSet.

https://github.com/mogilvie/EncryptBundle/commit/1c1f9432d173b349965ea1b90e0753893761c887

This should address your issue. Please test on your Entity A and Entity B environment and let me know how you get on.

Cheers,