Merge pull request #51019 from jhawthorn/key-provider

Remove memoization to accept `key_provider` overridden by `with_encryption_context`
This commit is contained in:
John Hawthorn 2024-02-13 13:10:38 -08:00 committed by GitHub
commit c730877c49
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 48 additions and 3 deletions

View File

@ -140,11 +140,11 @@ module ActiveRecord
end
def encryption_options
@encryption_options ||= { key_provider: key_provider, cipher_options: { deterministic: deterministic? } }.compact
{ key_provider: key_provider, cipher_options: { deterministic: deterministic? } }.compact
end
def decryption_options
@decryption_options ||= { key_provider: key_provider }.compact
{ key_provider: key_provider }.compact
end
def clean_text_scheme

View File

@ -50,7 +50,7 @@ module ActiveRecord
end
def key_provider
@key_provider ||= @key_provider_param || build_key_provider || default_key_provider
@key_provider_param || build_key_provider || default_key_provider
end
def merge(other_scheme)

View File

@ -33,6 +33,51 @@ class ActiveRecord::Encryption::EncryptableRecordTest < ActiveRecord::Encryption
assert_invalid_key_cant_read_attribute(post, :body)
end
test "swapping key_providers via with_encryption_context" do
key_provider1 = ActiveRecord::Encryption::DerivedSecretKeyProvider.new(SecureRandom.base64(32))
key_provider2 = ActiveRecord::Encryption::DerivedSecretKeyProvider.new(SecureRandom.base64(32))
post1 = post2 = nil
ActiveRecord::Encryption.with_encryption_context key_provider: key_provider1 do
post1 = EncryptedPost.create!(title: "post1!", body: "first post!")
end
ActiveRecord::Encryption.with_encryption_context key_provider: key_provider2 do
post2 = EncryptedPost.create!(title: "post2!", body: "second post!")
end
post1.reload
assert_raises ActiveRecord::Encryption::Errors::Decryption do
post1.title
end
post2.reload
assert_raises ActiveRecord::Encryption::Errors::Decryption do
post2.title
end
ActiveRecord::Encryption.with_encryption_context key_provider: key_provider1 do
post1.reload
assert_equal "post1!", post1.title
post2.reload
assert_raises ActiveRecord::Encryption::Errors::Decryption do
post2.title
end
end
ActiveRecord::Encryption.with_encryption_context key_provider: key_provider2 do
post2.reload
assert_equal "post2!", post2.title
post1.reload
assert_raises ActiveRecord::Encryption::Errors::Decryption do
post1.title
end
end
end
test "ignores nil values" do
assert_nil EncryptedBook.create!(name: nil).name
end