Active Record Encryption: extend_queries silently returns no results for deterministic attributes that also declare normalizes
Steps to reproduce
Run the self-contained script below. It covers two independent situations, each once without
and once with normalizes on the encrypted attribute:
- Scenario A — the documented "encrypt existing unencrypted data" migration
(
support_unencrypted_data: true). - Scenario B — rotating a deterministic key through a
previous:scheme.
# frozen_string_literal: true
require "bundler/inline"
gemfile(true) do
source "https://rubygems.org"
gem "rails", "8.1.3.1"
gem "sqlite3"
end
require "active_record"
require "minitest/autorun"
require "logger"
ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:")
ActiveRecord::Base.logger = Logger.new($stdout) if ENV["VERBOSE"]
ActiveRecord::Encryption.configure(
primary_key: "primary-key-for-this-report",
deterministic_key: "deterministic-key-for-this-report",
key_derivation_salt: "salt-for-this-report"
)
ActiveRecord::Encryption.config.extend_queries = true
# There is no railtie here, so install what `config.active_record.encryption.extend_queries = true`
# installs at boot.
ActiveRecord::Encryption::ExtendedDeterministicQueries.install_support
ActiveRecord::Encryption::ExtendedDeterministicUniquenessValidator.install_support
RETIRED_KEY = "retired-deterministic-key"
ActiveRecord::Schema.define do
create_table(:plain_users, force: true) { |t| t.string :email }
create_table(:normalized_users, force: true) { |t| t.string :email }
create_table(:plain_rotated_users, force: true) { |t| t.string :email }
create_table(:normalized_rotated_users, force: true) { |t| t.string :email }
end
# --- Scenario A: the documented "encrypt existing unencrypted data" migration -----------------
class PlainUser < ActiveRecord::Base
self.table_name = :plain_users
encrypts :email, deterministic: true, support_unencrypted_data: true
end
class NormalizedUser < ActiveRecord::Base
self.table_name = :normalized_users
encrypts :email, deterministic: true, support_unencrypted_data: true
normalizes :email, with: ->(email) { email.downcase.strip }
end
# --- Scenario B: rotating a deterministic key through a previous scheme -----------------------
#
# `fixed: false` is what makes new writes use the current key. With the default `fixed: true`,
# an attribute that has a previous scheme keeps writing with the *oldest* key
# (EncryptedAttributeType#serialize_with_oldest?), which would hide the query behaviour this
# report is about.
class LegacyPlainUser < ActiveRecord::Base
self.table_name = :plain_rotated_users
encrypts :email, deterministic: true, key: RETIRED_KEY
end
class LegacyNormalizedUser < ActiveRecord::Base
self.table_name = :normalized_rotated_users
encrypts :email, deterministic: true, key: RETIRED_KEY
normalizes :email, with: ->(email) { email.downcase.strip }
end
class PlainRotatedUser < ActiveRecord::Base
self.table_name = :plain_rotated_users
encrypts :email, deterministic: { fixed: false }, previous: [{ deterministic: true, key: RETIRED_KEY }]
end
class NormalizedRotatedUser < ActiveRecord::Base
self.table_name = :normalized_rotated_users
encrypts :email, deterministic: { fixed: false }, previous: [{ deterministic: true, key: RETIRED_KEY }]
normalizes :email, with: ->(email) { email.downcase.strip }
end
class ExtendedQueriesWithNormalizesTest < Minitest::Test
EMAIL = "[email protected]"
# Simulates data that predates the encryption. This has to bypass Active Record: insert_all!
# would run the value through the attribute type and encrypt it.
def insert_unencrypted(table)
ActiveRecord::Base.connection.execute("INSERT INTO #{table} (email) VALUES ('#{EMAIL}')")
end
# --- Scenario A ------------------------------------------------------------------------------
def test_a1_finds_unencrypted_row_without_normalizes
insert_unencrypted(:plain_users)
assert PlainUser.find_by(email: EMAIL), "expected the unencrypted row to be found"
end
def test_a2_finds_unencrypted_row_with_normalizes
insert_unencrypted(:normalized_users)
assert NormalizedUser.find_by(email: EMAIL),
"expected the unencrypted row to be found; `normalizes` breaks the query expansion"
end
# --- Scenario B ------------------------------------------------------------------------------
def test_b1_finds_retired_key_row_without_normalizes
LegacyPlainUser.create!(email: EMAIL)
assert PlainRotatedUser.find_by(email: EMAIL), "expected the retired-key row to be found"
end
def test_b2_finds_retired_key_row_with_normalizes
LegacyNormalizedUser.create!(email: EMAIL)
assert NormalizedRotatedUser.find_by(email: EMAIL),
"expected the retired-key row to be found; `normalizes` breaks the query expansion"
end
# --- The mechanism ---------------------------------------------------------------------------
def test_c_additional_value_is_encrypted_a_second_time
legacy = LegacyNormalizedUser.create!(email: EMAIL)
stored = ActiveRecord::Base.connection.select_value(
"SELECT email FROM normalized_rotated_users WHERE id = #{legacy.id}"
)
sql = NormalizedRotatedUser.where(email: EMAIL).to_sql
assert_includes sql, "IN (", "the query is expanded into two values"
assert_includes sql, stored,
"expected the expanded query to contain the ciphertext the row is stored " \
"with. Instead the second value is the encryption of the AdditionalValue's " \
"#inspect output:\n#{sql}"
end
# --- Second site: the uniqueness validator ----------------------------------------------------
#
# ExtendedDeterministicUniquenessValidator takes a different route — it builds no AdditionalValue
# at all, it hands the finished previous-scheme ciphertext to an ordinary query wrapped in
# `without_encryption`. That disables encryption, but not normalization, so the normalizer is
# applied to the ciphertext itself and corrupts it.
#
# The assertion below is on the generated SQL because the runtime consequence depends on the
# database: with a case-sensitive collation the duplicate is not detected at all, while MySQL's
# default case-insensitive collation happens to still match the corrupted value.
def test_d_uniqueness_validator_normalizes_the_ciphertext
retired_ciphertext = NormalizedRotatedUser.type_for_attribute("email").previous_types.first.serialize(EMAIL)
payload = retired_ciphertext[/"p":"([^"]+)"/, 1]
# Exactly what ExtendedDeterministicUniquenessValidator#validate_each does with that value.
sql = ActiveRecord::Encryption.without_encryption do
NormalizedRotatedUser.where(email: retired_ciphertext).to_sql
end
assert_includes sql, payload,
"expected the validator to look for the previous-scheme ciphertext, but the " \
"normalizer was applied to the ciphertext itself and downcased it:\n#{sql}"
end
endResult (summarised; minitest prints its own failure details):
A1 without normalizes, finds the unencrypted row .... PASS
A2 with normalizes, finds the unencrypted row .... FAIL
B1 without normalizes, finds the retired-key row .... PASS
B2 with normalizes, finds the retired-key row .... FAILtest_c and test_d show what the generated SQL looks like in the two affected code paths.
Expected behavior
With config.active_record.encryption.extend_queries = true, find_by/where and the extended
uniqueness validation on a deterministic attribute should match rows written under any of the
attribute's previous schemes, whether or not the attribute also declares normalizes.
Actual behavior
Queries. The query is expanded into IN (…) with two values, but the second one is not a
ciphertext of the searched value under the previous scheme — it is roughly twice the length of a
valid ciphertext. The query therefore matches nothing.
Uniqueness validation. The value the validator searches for comes out normalized, i.e. the normalizer is applied to the ciphertext itself:
value handed to the query: {"p":"ukiFGf5Iwr2YgbAc/xX7eA==","h":{"iv":"il7GkwklCRiuyN6q",…
value that ends up in SQL: {"p":"ukifgf5iwr2ygbac/xx7ea==","h":{"iv":"il7gkwklcriu…Whether that surfaces depends on the database: with a case-sensitive collation the duplicate is
not detected at all, while MySQL's default case-insensitive collation happens to still match the
corrupted value. test_d therefore asserts on the generated SQL rather than on the outcome.
In both cases there is no exception and nothing in the log — the lookups simply stop finding the rows. For an attribute like an e-mail address or an IBAN that means users silently stop being found, duplicate records get created, and uniqueness checks stop protecting anything, for as long as the migration or rotation window lasts.
System configuration
Rails version: 8.1.3.1 — the relevant code in
activerecord/lib/active_record/encryption/extended_deterministic_queries.rb,
activerecord/lib/active_record/encryption/extended_deterministic_uniqueness_validator.rb and
activemodel/lib/active_model/attributes/normalization.rb is unchanged on main.
Ruby version: 3.4.9
Source: rails/rails