feat: encryption key rotation support #9863
Open
+548
−84
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Description
This PR adds support for encryption key rotation through the new
previousKeysconfig option. When decryption with the current key fails, the system automatically falls back to trying previous keys, allowing seamless key rotation without losing access to data encrypted with old keys.While implementing this feature, I discovered critical state management issues in both
OpenSSLHandlerandSodiumHandler. The handlers were modifying their internal$keyproperty when keys were passed via the$paramsargument toencrypt()anddecrypt()methods. This was actually a bug, as the user guide clearly states that the key passed via$params:And not that it will permanently modify the handler's state (this is aligned with how CI3 worked).
Additionally,
SodiumHandler::encrypt()was callingsodium_memzero($this->key), which destroyed the encryption key after the first use and prevented handler reuse. While this memory-clearing behavior was documented, it created an inconsistency whereSodiumHandlercould not be reused after encryption, butOpenSSLHandlercould, making it impossible to use both handlers reliably in the same way.These issues became particularly problematic with the
previousKeysfallback mechanism, where the handlers needed to try multiple keys without corrupting their state. To fix this, I refactored both handlers to use local variables for keys passed via$params, ensuring the handler's state remains unchanged and aligning the implementation with the documented behavior.This is a BC break because some code may have relied on the buggy behavior where
$paramsmodified the stored key. However, this affects only a small subset of users who passed a key via$paramsonce and expected it to persist for subsequent operations. Most users who either always pass the key via$paramsfor each operation or always configure keys viaConfig\Encryptionare not affected.The proper way to configure encryption keys has always been through
Config\Encryption, and this change enforces that pattern while fixing the underlying state management bugs.Closes #9853
Checklist: