skip to content

After a suspected key leak, how do you rotate Active Record Encryption keys in Rails 8.1, and why is a deterministic national-ID column harder?

level: seniorimportance: should knowfreq 26%

answer

  1. primary_key can be a list
  2. last key encrypts, all keys decrypt
  3. store_key_references skips trial decryption
  4. deterministic_key: one value only
  5. previous: with deterministic: { fixed: false }

basics

~20 s

List the new primary_key after the old one: Rails encrypts with the last key and tries all keys to decrypt. Re-encrypt rows with record.encrypt, then drop the old key. deterministic_key takes one value, so it needs a previous: scheme.

solid answer

~50 s

In credentials, `active_record_encryption.primary_key` may be an array: the **last** key encrypts new data and every key is tried on decryption (or only the referenced one if `store_key_references` is on). So rotation is: append the new key, deploy, re-encrypt existing rows with `record.encrypt` in batches so they use the new key, then remove the leaked key. A deterministic attribute cannot do this: `deterministic_key` must be a single value, and `DeterministicKeyProvider` raises `Deterministic encryption keys can't be rotated` for a list. To move one, declare the old key as a previous scheme, enable `extend_queries` so lookups try both ciphertexts, and use `deterministic: { fixed: false }`, because by default a deterministic attribute with previous schemes keeps encrypting with the **oldest** one. Then re-encrypt and drop the previous scheme. Rotating also does nothing for copies the leaked key already decrypted.

code

yaml · 7 lines
yaml
# bin/rails credentials:edit -e production
active_record_encryption:
  primary_key:
    - EGY8WhulUOXixybod7ZWwMIL68R9o5kC   # old: decrypts only
    - aPA5XyALhf75NNnMzaspW7akTfZp0lPY   # new: encrypts
  deterministic_key: 9Ql2Xx0uWiGWNBi3j5Hb3yHHm3MHt0yF
  key_derivation_salt: xEY0dt6TZcAMg52K7O84wYzkjvbA62Hz

go deeper

for a junior

Recall that primary_key can hold several keys and that old data must be re-encrypted before the old key is removed.

for a middle

Explain which key encrypts, how decryption tries keys, and what store_key_references changes.

for a senior

Run a rotation after a leak, including the deterministic case with previous:, extend_queries and fixed: false, and account for backups.

for a principal

Set a rotation policy that balances re-encryption cost, incident response and the leakage already in backups and replicas.

## How Active Record Encryption finds keys The default key provider is built from `primary_key`. Rails derives a 256-bit key from each password with PBKDF2 and `key_derivation_salt`. A `KeyProvider` then answers two questions: - **Which key encrypts?** The **last** one in the list. - **Which keys may decrypt?** All of them, tried in turn, unless the message carries a key reference. `config.active_record.encryption.store_key_references = true` writes the id of the key used into each message's headers, so decryption picks the right key directly instead of trying each. The trade-off is a slightly larger payload. ## Rotating the non-deterministic key For a hospital app whose `primary_key` may have leaked: 1. **Add the new key last** in the credentials of every affected environment: ```yaml active_record_encryption: primary_key: - <old key> # still decrypts existing rows - <new key> # encrypts everything written from now on deterministic_key: <unchanged> key_derivation_salt: <unchanged> ``` 2. **Deploy.** Reads work for old and new rows; writes use the new key. 3. **Re-encrypt** existing rows so they stop depending on the old key: `Patient.find_each(&:encrypt)` rewrites every encrypted attribute with `update_columns` (no validations, callbacks or timestamp changes). 4. **Remove the old key** once no row needs it. Any row you missed will then fail to decrypt, so verify first. Keep the list short; every extra key costs a trial decryption on rows without references. ## Why the deterministic column is different Deterministic attributes use `deterministic_key` through `DeterministicKeyProvider`, which accepts exactly one value and raises `ActiveRecord::Encryption::Errors::Configuration` with the message `Deterministic encryption keys can't be rotated` if you give it a list. The reason is structural: a lookup encrypts the search value with one key and compares ciphertexts. With two keys there would be two possible ciphertexts per value, and a plain list gives the query no way to know which to try. The supported route is **previous encryption schemes**: - **`previous:`** on `encrypts` (or `config.active_record.encryption.previous` globally) lists older schemes, for example one built with the old key. Reads that fail with the current scheme retry with each previous one. - **`extend_queries = true`** makes lookups on deterministic attributes include the ciphertexts of previous schemes, so `find_by(national_id:)` matches rows under either key. - **`deterministic: { fixed: false }`** matters here. By default a deterministic attribute with previous schemes keeps **encrypting new data with the oldest scheme**, so ciphertexts stay stable for unique indexes. During a key change that would keep writing with the leaked key; `fixed: false` makes it use the newest scheme. Then re-encrypt with `encrypt`, confirm no row still needs the old scheme, remove `previous:`, and switch `extend_queries` off. A unique index on the column must tolerate the transition, because the same value can briefly exist under two ciphertexts. ## What rotation does not fix | Concern | Does rotation help? | |---|---| | Future writes under a leaked key | yes, once the new key encrypts | | Existing rows encrypted with the leaked key | only after re-encryption | | Backups and replicas taken before re-encryption | no; they still hold old ciphertext readable with the leaked key | | Plaintext already decrypted by whoever had the key | no | So a real incident also means treating older backups as exposed. ## Changing other properties The same `previous:` mechanism covers turning a deterministic attribute non-deterministic, changing compression or switching key providers. Add the old properties as a previous scheme, re-encrypt, then remove it. ## What interviewers check - That you know the last key encrypts and all keys decrypt. - That you re-encrypt before removing the old key. - That deterministic keys need previous schemes, `extend_queries` and `fixed: false`, and why.

  • What does store_key_references change about rotation?
    With `store_key_references` on, each message records the id of the key that encrypted it, and decryption uses that key directly instead of trying every key in the list. That keeps reads fast with several keys and makes it easy to find rows still tied to an old key, at the cost of a slightly larger payload.
  • Why does a deterministic attribute with previous: keep encrypting with the oldest scheme by default?
    Deterministic encryption exists for lookups and unique indexes, which need one stable ciphertext per value. If new writes switched to the newest scheme, the same value could be stored under two ciphertexts and a unique index would admit duplicates. `deterministic: { fixed: false }` opts out when you deliberately want to move to the new scheme.

  • Rails encrypts new data with the first key in the primary_key list.
  • Removing the old key right after adding the new one is safe.
  • You can rotate deterministic_key by listing two values.
  • Once the key is rotated, old backups are protected too.
  • previous: alone makes deterministic lookups find rows under the old key.