The personal finance app for everyone (by everyone)
Ruby
Keep SSO identity blocks across a SECRET_KEY_BASE change and finish the rotation guide (#5225)
GFR7033725a4306
diff --git a/app/models/sso_identity_block.rb b/app/models/sso_identity_block.rbindex c78b66a69f..8d9c834b83 100644--- a/app/models/sso_identity_block.rb+++ b/app/models/sso_identity_block.rb@@ -5,49 +5,108 @@ class SsoIdentityBlock < ApplicationRecordclass BlockedIdentity < StandardError; end- encrypts :identity_label if encryption_ready?+ # Salt of the HMAC key derived from SECRET_KEY_BASE. Only used for blocks+ # stored as a digest: those from before the uid was encrypted, and new ones+ # while Active Record encryption is not configured.+ LEGACY_DIGEST_SALT = "sso_identity_block_uid"++ if encryption_ready?+ encrypts :identity_label+ # Encrypted (not hashed with a key of our own) so a key rotation re-encrypts+ # it with every other column instead of silently lifting the block.+ encrypts :uid, deterministic: true+ # The HMAC key a legacy uid_digest was made with, so the digest still+ # matches after SECRET_KEY_BASE changes.+ encrypts :legacy_digest_key+ endbefore_validation :redact_identity_label_unless_encrypted- validates :provider, :uid_digest, :identity_label, presence: true- validates :uid_digest, uniqueness: { scope: :provider }+ validates :provider, :identity_label, presence: true+ validates :uid, uniqueness: { scope: :provider }, allow_nil: true+ validates :uid_digest, uniqueness: { scope: :provider }, allow_nil: true+ validate :uid_or_digest_presentclass << self+ # Fails closed: while a stored legacy key cannot be read, the legacy+ # blocks it covers cannot be checked, so the identity counts as blocked.def blocked?(provider:, uid:)- exists?(provider: provider, uid_digest: digest(uid))+ block, legacy_check_unavailable = lookup(provider: provider, uid: uid)+ block.present? || legacy_check_unavailable+ end++ def find_block(provider:, uid:)+ lookup(provider: provider, uid: uid).firstenddef block_all!(identities, identity_label:)identities.find_each do |identity|with_identity_lock(provider: identity.provider, uid: identity.uid) do- find_or_create_by!(- provider: identity.provider,- uid_digest: digest(identity.uid)- ) { |block| block.identity_label = identity_label }+ next if find_block(provider: identity.provider, uid: identity.uid)++ create!(provider: identity.provider, identity_label: identity_label, **uid_attributes(identity.uid))endendenddef with_identity_lock(provider:, uid:)transaction do- lock_key = advisory_lock_key(provider: provider, uid: uid)+ lock_key = OpenSSL::HMAC.digest("SHA256", derived_digest_key, "#{provider}\0#{uid}").unpack1("q>")connection.execute(sanitize_sql_array([ "SELECT pg_advisory_xact_lock(?)", lock_key ]))yieldendend- def digest(uid)- OpenSSL::HMAC.hexdigest("SHA256", digest_key, uid.to_s)+ def digest(uid, key: derived_digest_key)+ OpenSSL::HMAC.hexdigest("SHA256", key, uid.to_s)endprivate- def digest_key- Rails.application.key_generator.generate_key("sso_identity_block_uid", 32)+ # The digest is still written next to the encrypted uid so that the+ # previous release (an image rollback, or old processes during a+ # rolling deploy) keeps seeing new blocks. Drop it in a later release.+ def uid_attributes(uid)+ attributes = { uid_digest: digest(uid) }+ attributes[:uid] = uid.to_s if encryption_ready?+ attributes+ end++ # Returns the matching block and whether some legacy rows could not be+ # checked because their stored key is unreadable.+ def lookup(provider:, uid:)+ uid = uid.to_s+ if encryption_ready? && (block = find_by(provider: provider, uid: uid))+ return [ block, false ]+ end++ digested = where(provider: provider).where.not(uid_digest: nil)+ stored_keys, unreadable = stored_legacy_digest_keys(digested)+ stored_keys.each do |stored_key|+ block = digested.where.not(legacy_digest_key: nil).find_by(uid_digest: digest(uid, key: stored_key))+ return [ block, false ] if block+ end++ block = digested.find_by(legacy_digest_key: nil, uid_digest: digest(uid))+ [ block, block.nil? && unreadable ]+ end++ # Each row is read on its own, so one unreadable key (a row the rotation+ # backfill reported as failed) does not hide the readable ones.+ def stored_legacy_digest_keys(scope)+ unreadable = false+ keys = scope.where.not(legacy_digest_key: nil).select(:id, :legacy_digest_key).find_each.filter_map do |row|+ Base64.strict_decode64(row.legacy_digest_key)+ rescue ActiveRecord::Encryption::Errors::Base, ArgumentError => e+ Rails.logger.error("[SsoIdentityBlock] Stored legacy digest key of block #{row.id} is unreadable (#{e.class}); treating unmatched SSO logins for this provider as blocked")+ unreadable = true+ nil+ end+ [ keys.uniq, unreadable ]end- def advisory_lock_key(provider:, uid:)- OpenSSL::HMAC.digest("SHA256", digest_key, "#{provider}\0#{uid}").unpack1("q>")+ def derived_digest_key+ Rails.application.key_generator.generate_key(LEGACY_DIGEST_SALT, 32)endend@@ -58,4 +117,8 @@ class SsoIdentityBlock < ApplicationRecordself.identity_label = "Removed identity #{uid_digest.to_s.first(12)}"end++ def uid_or_digest_present+ errors.add(:uid, :blank) if uid.blank? && uid_digest.blank?+ endenddiff --git a/config/initializers/encryption_warning.rb b/config/initializers/encryption_warning.rbindex 42a8549878..98e74ee418 100644--- a/config/initializers/encryption_warning.rb+++ b/config/initializers/encryption_warning.rb@@ -64,9 +64,9 @@ Rails.application.config.after_initialize doif ActiveRecordEncryptionConfig.using_known_compromised_secret_key_base?if ActiveRecordEncryptionConfig.explicitly_configured?Rails.logger.warn(<<~WARN)- [SECURITY] SECRET_KEY_BASE is set to a value that was previously- shipped as a working default in this project's example Docker- Compose files. Anyone who knows that value can forge or decrypt+ [SECURITY] SECRET_KEY_BASE is set to a publicly known value: a+ default or placeholder from this project's example files or hosting+ guides. Anyone who knows that value can forge or decryptRails session cookies, and can decrypt any value stored via Setting(AI/market-data provider API keys, etc.), which derives its ownencryption key directly from SECRET_KEY_BASE - independently of@@ -82,8 +82,8 @@ Rails.application.config.after_initialize doelseRails.logger.warn(<<~WARN)[SECURITY] ActiveRecord Encryption keys were auto-derived from a- SECRET_KEY_BASE value that was previously shipped as a working- default in this project's example Docker Compose files. Anyone who+ publicly known SECRET_KEY_BASE value: a default or placeholder from+ this project's example files or hosting guides. Anyone whoknows that value can compute the same encryption keys, so thisinstallation's "encrypted" data is not actually protected. The samevalue also signs/encrypts Rails session cookies and Setting's owndiff --git a/config/locales/views/settings/securities/en.yml b/config/locales/views/settings/securities/en.ymlindex 7b383b7e5c..b18c2b7b4a 100644--- a/config/locales/views/settings/securities/en.yml+++ b/config/locales/views/settings/securities/en.yml@@ -52,7 +52,7 @@ en:sso_warning_message: This is your only login method. You should set a password in your security settings before disconnecting, otherwise you may be locked out of your account.compromised_secret_warning:title: Encryption keys are not actually secret- intro: This install's encryption keys were auto-derived from a SECRET_KEY_BASE value that was previously shipped as a working default in this project's example Docker Compose files. Anyone who knows that value can compute the same encryption keys, so this data is not actually protected.+ intro: This install's encryption keys were auto-derived from a publicly known SECRET_KEY_BASE value (a default or placeholder from this project's example files or hosting guides). Anyone who knows that value can compute the same encryption keys, so this data is not actually protected.generate: 'Do NOT simply set a new SECRET_KEY_BASE and run the backfill task: if any data was already encrypted under the compromised key, the backfill cannot tell that ciphertext apart from real plaintext and will re-encrypt it on top, making it unrecoverable. Rotate safely instead, with the app stopped: generate new keys with bin/rails db:encryption:init and set them as the ACTIVE_RECORD_ENCRYPTION_* variables, then run bin/rails "security:backfill_encryption[100,0]" with this SECRET_KEY_BASE in the ACTIVE_RECORD_ENCRYPTION_PREVIOUS_SECRET_KEY_BASE environment variable for that command only, so existing data still decrypts and moves to the new keys. See the Docker hosting guide.'settings_secrets: 'API keys and tokens saved in the settings are encrypted with a key derived from SECRET_KEY_BASE itself, which the previous scheme does not cover. After changing SECRET_KEY_BASE, re-encrypt them with bin/rails "security:rotate_setting_secrets[0]", passing the old value in the OLD_SECRET_KEY_BASE environment variable (see the Docker hosting guide). Re-enter any key it reports as not decryptable.'webauthn_credentials:diff --git a/config/locales/views/settings/securities/id.yml b/config/locales/views/settings/securities/id.ymlindex 2876e31f98..49d300d92e 100644--- a/config/locales/views/settings/securities/id.yml+++ b/config/locales/views/settings/securities/id.yml@@ -52,7 +52,7 @@ id:sso_warning_message: "Ini adalah satu-satunya metode masuk Anda. Sebaiknya atur kata sandi di pengaturan keamanan sebelum memutuskan koneksi, jika tidak Anda dapat terkunci dari akun Anda."compromised_secret_warning:title: "Kunci enkripsi sebenarnya tidak rahasia"- intro: "Kunci enkripsi instalasi ini diturunkan secara otomatis dari nilai SECRET_KEY_BASE yang sebelumnya dikirimkan sebagai default yang berfungsi di file contoh Docker Compose proyek ini. Siapa pun yang mengetahui nilai tersebut dapat menghitung kunci enkripsi yang sama, sehingga data ini sebenarnya tidak terlindungi."+ intro: "Kunci enkripsi instalasi ini diturunkan secara otomatis dari nilai SECRET_KEY_BASE yang diketahui publik (nilai default atau placeholder dari file contoh atau panduan hosting proyek ini). Siapa pun yang mengetahui nilai tersebut dapat menghitung kunci enkripsi yang sama, sehingga data ini sebenarnya tidak terlindungi."generate: "JANGAN hanya mengatur SECRET_KEY_BASE baru dan menjalankan tugas backfill: jika ada data yang sudah dienkripsi dengan kunci yang bocor, backfill tidak dapat membedakan ciphertext tersebut dari plaintext asli dan akan mengenkripsi ulang di atasnya, sehingga data tidak dapat dipulihkan. Lakukan rotasi dengan aman saat aplikasi dihentikan: buat kunci baru dengan bin/rails db:encryption:init dan atur sebagai variabel ACTIVE_RECORD_ENCRYPTION_*, lalu jalankan bin/rails \"security:backfill_encryption[100,0]\" dengan SECRET_KEY_BASE ini di variabel lingkungan ACTIVE_RECORD_ENCRYPTION_PREVIOUS_SECRET_KEY_BASE hanya untuk perintah tersebut, agar data yang ada tetap dapat didekripsi dan dipindahkan ke kunci baru. Lihat panduan hosting Docker."settings_secrets: "Kunci API dan token yang disimpan di pengaturan dienkripsi dengan kunci yang diturunkan dari SECRET_KEY_BASE itu sendiri, yang tidak dicakup oleh skema sebelumnya. Setelah mengubah SECRET_KEY_BASE, enkripsi ulang dengan bin/rails \"security:rotate_setting_secrets[0]\", dengan meneruskan nilai lama di variabel lingkungan OLD_SECRET_KEY_BASE (lihat panduan hosting Docker). Masukkan kembali kunci apa pun yang dilaporkan tidak dapat didekripsi."webauthn_credentials:diff --git a/config/locales/views/settings/securities/zh-CN.yml b/config/locales/views/settings/securities/zh-CN.ymlindex bfa24e9f87..524f9989de 100644--- a/config/locales/views/settings/securities/zh-CN.yml+++ b/config/locales/views/settings/securities/zh-CN.yml@@ -12,7 +12,7 @@ zh-CN:mfa_enabled_description: 你的账户受到额外安全层保护。compromised_secret_warning:title: 加密密钥实际上并不保密- intro: 此实例的加密密钥是从一个此前曾作为本项目示例 Docker Compose 文件默认工作值的 SECRET_KEY_BASE 自动派生的。任何知道该值的人都能计算出相同的加密密钥,因此这些数据实际上并未受到保护。+ intro: 此实例的加密密钥是从一个公开已知的 SECRET_KEY_BASE(本项目示例文件或托管指南中的默认值或占位符)自动派生的。任何知道该值的人都能计算出相同的加密密钥,因此这些数据实际上并未受到保护。generate: 请勿直接设置新的 SECRET_KEY_BASE 并运行回填任务:如果已有数据使用该已泄露密钥加密,回填任务无法区分密文与真实明文,会再次在其上进行加密,导致数据无法恢复。请改为在停止应用后安全轮换:使用 bin/rails db:encryption:init 生成新密钥并设为 ACTIVE_RECORD_ENCRYPTION_* 变量,然后仅在执行该命令时将该 SECRET_KEY_BASE 放入 ACTIVE_RECORD_ENCRYPTION_PREVIOUS_SECRET_KEY_BASE 环境变量中,运行 bin/rails "security:backfill_encryption[100,0]",使现有数据仍可解密并迁移至新密钥。请参阅 Docker 部署指南。settings_secrets: 保存在设置中的 API 密钥和令牌使用由 SECRET_KEY_BASE 本身派生的密钥加密,上述方案不会涵盖这部分数据。更改 SECRET_KEY_BASE 后,请将旧值放入 OLD_SECRET_KEY_BASE 环境变量中并运行 bin/rails "security:rotate_setting_secrets[0]" 重新加密(请参阅 Docker 部署指南)。对于报告为无法解密的任何密钥,请重新输入。mfa_disabled_status_html: 双重认证已<span class="font-medium text-red-600">禁用</span>diff --git a/db/migrate/20261117090000_move_sso_identity_blocks_to_active_record_encryption.rb b/db/migrate/20261117090000_move_sso_identity_blocks_to_active_record_encryption.rbnew file mode 100644index 0000000000..f089145d98--- /dev/null+++ b/db/migrate/20261117090000_move_sso_identity_blocks_to_active_record_encryption.rb@@ -0,0 +1,81 @@+class MoveSsoIdentityBlocksToActiveRecordEncryption < ActiveRecord::Migration[8.1]+ # Salt of the HMAC key the existing uid digests were made with. That key is+ # derived from SECRET_KEY_BASE, so it is stored with each existing block+ # here: changing SECRET_KEY_BASE later must not lift the block.+ LEGACY_DIGEST_SALT = "sso_identity_block_uid"++ class MigrationBlock < ActiveRecord::Base+ self.table_name = "sso_identity_blocks"+ end++ def up+ add_column :sso_identity_blocks, :uid, :string+ add_column :sso_identity_blocks, :legacy_digest_key, :text+ change_column_null :sso_identity_blocks, :uid_digest, true+ add_index :sso_identity_blocks, [ :provider, :uid ], unique: true, where: "uid IS NOT NULL"++ return unless ActiveRecordEncryptionConfig.ready?++ block_model = encrypted_block_model+ key = Base64.strict_encode64(Rails.application.key_generator.generate_key(LEGACY_DIGEST_SALT, 32))+ block_model.where(legacy_digest_key: nil).where.not(uid_digest: nil).find_each do |block|+ block.legacy_digest_key = key+ block.save!(validate: false, touch: false)+ end+ end++ def down+ derived_key = Rails.application.key_generator.generate_key(LEGACY_DIGEST_SALT, 32)+ ensure_reversible!(derived_key)++ block_model = ActiveRecordEncryptionConfig.ready? ? encrypted_block_model : MigrationBlock+ begin+ # Recomputed for every encrypted row: a digest written next to the uid+ # is stale once SECRET_KEY_BASE has changed.+ block_model.where.not(uid: nil).find_each do |block|+ block.update_columns(uid_digest: OpenSSL::HMAC.hexdigest("SHA256", derived_key, block.uid.to_s))+ end+ rescue ActiveRecord::Encryption::Errors::Base => e+ raise ActiveRecord::IrreversibleMigration,+ "An SSO identity block does not decrypt with the configured keys (#{e.class}); rolling back would lose it."+ end++ remove_index :sso_identity_blocks, [ :provider, :uid ]+ change_column_null :sso_identity_blocks, :uid_digest, false+ remove_column :sso_identity_blocks, :legacy_digest_key+ remove_column :sso_identity_blocks, :uid+ end++ private++ # The schema before this migration can only check digests made with the+ # current SECRET_KEY_BASE. Rolling back past a SECRET_KEY_BASE change, or+ # without the keys that decrypt the stored uids, would silently lift blocks.+ def ensure_reversible!(derived_key)+ return unless MigrationBlock.where.not(uid: nil).or(MigrationBlock.where.not(legacy_digest_key: nil)).exists?++ unless ActiveRecordEncryptionConfig.ready?+ raise ActiveRecord::IrreversibleMigration, "Active Record encryption keys are needed to roll back encrypted SSO identity blocks."+ end++ stored_keys = encrypted_block_model.where.not(legacy_digest_key: nil).pluck(:legacy_digest_key).uniq+ return if stored_keys.all? { |key| Base64.strict_decode64(key) == derived_key }++ raise ActiveRecord::IrreversibleMigration,+ "SECRET_KEY_BASE changed since this migration ran; rolling back would lift SSO identity blocks made before the change."+ rescue ActiveRecord::Encryption::Errors::Base => e+ raise ActiveRecord::IrreversibleMigration,+ "A stored SSO identity block key does not decrypt with the configured keys (#{e.class}); rolling back would lift blocks."+ end++ def encrypted_block_model+ MigrationBlock.reset_column_information+ Class.new(MigrationBlock) do+ def self.name = "SsoIdentityBlockMigrationRecord"+ # Strict reads: a value the keys do not decrypt must stop the+ # migration instead of being hashed or copied as if it were plaintext.+ encrypts :uid, deterministic: true, support_unencrypted_data: false+ encrypts :legacy_digest_key, support_unencrypted_data: false+ end+ end+enddiff --git a/db/schema.rb b/db/schema.rbindex e3d7883521..0b51adc2d3 100644--- a/db/schema.rb+++ b/db/schema.rb@@ -2672,9 +2672,12 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_19_120000) docreate_table "sso_identity_blocks", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|t.datetime "created_at", null: falset.text "identity_label", null: false+ t.text "legacy_digest_key"t.string "provider", null: false- t.string "uid_digest", null: false+ t.string "uid"+ t.string "uid_digest"t.datetime "updated_at", null: false+ t.index ["provider", "uid"], name: "index_sso_identity_blocks_on_provider_and_uid", unique: true, where: "(uid IS NOT NULL)"t.index ["provider", "uid_digest"], name: "index_sso_identity_blocks_on_provider_and_uid_digest", unique: trueenddiff --git a/docs/hosting/docker.md b/docs/hosting/docker.mdindex 5ed21f546b..e8057de1c0 100644--- a/docs/hosting/docker.md+++ b/docs/hosting/docker.md@@ -689,7 +689,7 @@ Sure encrypts sensitive fields in the database, such as bank and provider creden> [!WARNING]> Encrypted data can only be read with the keys it was encrypted with. On an instance with data, don't change the three keys or `SECRET_KEY_BASE` except as described below, and keep `config/.env` (which backups include) private.-Your own keys are recommended, because they don't depend on `SECRET_KEY_BASE`. If the boot log warns that `SECRET_KEY_BASE` is a value from an example compose file, the derived keys are public; see [Encryption key rotation](encryption.md).+Your own keys are recommended, because they don't depend on `SECRET_KEY_BASE`. If the boot log warns that `SECRET_KEY_BASE` is a publicly known value, the derived keys are public; see [Encryption key rotation](encryption.md).### Generate the keysdiff --git a/docs/hosting/encryption.md b/docs/hosting/encryption.mdindex d28b86b757..11da955c82 100644--- a/docs/hosting/encryption.md+++ b/docs/hosting/encryption.md@@ -1,9 +1,9 @@# Encryption key rotation (self-hosted)-If your `SECRET_KEY_BASE` was ever shipped as a default in this project's-example Compose files (the boot log warns about this explicitly), or your-Active Record Encryption keys leaked for any other reason, the keys must be-rotated. Data already encrypted under the old keys has to stay readable+If your `SECRET_KEY_BASE` is a publicly known value (a default or+placeholder from this project's example files or hosting guides; the boot+log warns about this explicitly), or your Active Record Encryption keys+leaked for any other reason, the keys must be rotated. Data already encrypted under the old keys has to stay readablewhile it moves to the new ones, so the old keys are given to the backfilltask as a `previous` scheme([Rails key rotation](https://guides.rubyonrails.org/active_record_encryption.html#key-rotation))@@ -13,6 +13,29 @@ Take a database backup before starting and stop the app (web and worker)for the duration. Docker users: the same steps with `docker compose`commands are in the [Docker guide](docker.md#upgrading-an-install-that-is-already-running-keep-your-secret_key_base).+## Before you start: find the values in use++You need the `SECRET_KEY_BASE` your data was encrypted with, and the three+Active Record encryption keys if you set them. They are in your `.env`+(`SECRET_KEY_BASE`, `ACTIVE_RECORD_ENCRYPTION_*`), in your Rails+credentials if you configured them there (Rails uses the top-level+`secret_key_base` when the environment variable is not set, and the keys+in the `active_record_encryption` block), or, for an install that never+set `SECRET_KEY_BASE`, in the default of the `compose.yml` it was started+with. If that file was already+replaced, read the value from the old container instead. This works without+a Compose file and also while the container is stopped:++```sh+docker ps -a --filter "name=web" --format "{{.Names}}" # find the web container+read -r WEB_CONTAINER # paste its name+docker inspect --format '{{range .Config.Env}}{{println .}}{{end}}' "$WEB_CONTAINER" | grep '^SECRET_KEY_BASE='+```++`docker compose exec web printenv SECRET_KEY_BASE` does not help here: it+reads the new `compose.yml` first and stops with the same "Set+SECRET_KEY_BASE" error.+## 1. Set new keysGenerate a fresh key set and configure it as the current keys via@@ -65,6 +88,9 @@ flow.`SECRET_KEY_BASE` itself also signs session cookies and is the key sourcefor values saved on the self-hosting settings page (AI and market-dataprovider keys). Once the steps above are done, it is safe to change it.+Stop the app again and take a fresh database backup first: the app has+been running since step 3, and a later rollback to the first backup would+lose what was written in between.Existing sessions are signed out. Re-encrypt the settings once, with theold value in `OLD_SECRET_KEY_BASE`:@@ -75,4 +101,54 @@ bin/rails "security:rotate_setting_secrets[0]" # writesunset OLD_SECRET_KEY_BASE```-Re-enter any key the task lists under `not_decryptable`.+Re-enter any key the task lists under `not_decryptable`. Then start the+app (web and worker) and check a login and a provider sync.++Re-encrypting does not revoke anything. If the old key was publicly known+or leaked in any other way, and someone else may have had a copy of the+database or a backup, they can+decrypt what was stored with it. In that case also issue new provider API+keys and tokens at each provider (the keys on the self-hosting settings+page and those of connected accounts), even if the tasks above decrypted+them without errors, and revoke the old ones.++## What a new `SECRET_KEY_BASE` invalidates++Data in the database is covered by the steps above, including blocked SSO+identities of removed users. One exception: blocks created while the+install had no Active Record encryption keys at all are stored only as a+digest keyed by `SECRET_KEY_BASE`, and they stop matching once it changes.+Before changing it, note the entries under removed SSO identities on the+instance users page; a removed user who signs in again via SSO afterwards+has to be removed again.++These signed values are not stored and simply stop working:++- Every session: everyone has to sign in again.+- Password reset and email confirmation links that were already sent.+- Subscribed bill calendar links. Copy the link again from the bills+ calendar page and update the subscription.+- Connection flows that were in progress, such as a pending Wise login.++## Rolling back++If a step fails and you cannot fix the listed rows, go back to the state+before the rotation:++1. Stop the app (web and worker).+2. Restore the latest backup taken before the failing step: the one from+ before step 1, or the one from before step 4. Everything written after+ that backup is lost, so roll back as early as possible.+3. Put back the keys that match that backup, and unset every+ `ACTIVE_RECORD_ENCRYPTION_PREVIOUS_*` variable and `OLD_SECRET_KEY_BASE`:+ - Backup from before step 1: the old `SECRET_KEY_BASE`, and the old+ `ACTIVE_RECORD_ENCRYPTION_*` values if you had set any (remove the new+ ones otherwise).+ - Backup from before step 4: the old `SECRET_KEY_BASE` only. Keep the+ new `ACTIVE_RECORD_ENCRYPTION_*` values: the data in this backup is+ already encrypted with them.+4. Start the app and check a login and a provider sync.++Do not roll back by only putting the old keys back without the backup: rows+the write pass already moved are encrypted with the new keys and would no+longer decrypt.diff --git a/lib/active_record_encryption_config.rb b/lib/active_record_encryption_config.rbindex da0b5b5989..ff145e4c97 100644--- a/lib/active_record_encryption_config.rb+++ b/lib/active_record_encryption_config.rb@@ -7,16 +7,23 @@ module ActiveRecordEncryptionConfigACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT].freeze- # SECRET_KEY_BASE values ever shipped as a working default in- # compose.example.yml / compose.example.ai.yml. Self-hosted installs that- # deployed from one of those files without overriding it are running with- # a publicly known secret. Since the auto-derived encryption keys+ # Publicly known SECRET_KEY_BASE values: the working default once shipped in+ # compose.example.yml / compose.example.ai.yml, the .env.example value, the+ # placeholders in the Docker, PetHost and Helm guides, and the literal+ # `$(openssl rand -hex 64)` the Hetzner guide has users write into .env+ # (Compose does not run it). Installs that kept one of these are running+ # with a secret anyone can look up. Since the auto-derived encryption keys# (config/initializers/active_record_encryption.rb) are a deterministic# function of SECRET_KEY_BASE, anyone with this value can compute the same# encryption keys, so `ready?` alone is not a meaningful signal of safety# for these installs even though it makes `runtime_configured?` true.- KNOWN_COMPROMISED_SECRET_KEY_BASES = %w[- a7523c3d0ae56415046ad8abae168d71074a79534a7062258f8d1d51ac2f76d3c3bc86d86b6b0b307df30d9a6a90a2066a3fa9e67c5e6f374dbd7dd4e0778e13+ KNOWN_COMPROMISED_SECRET_KEY_BASES = [+ "a7523c3d0ae56415046ad8abae168d71074a79534a7062258f8d1d51ac2f76d3c3bc86d86b6b0b307df30d9a6a90a2066a3fa9e67c5e6f374dbd7dd4e0778e13",+ "secret-value",+ "$(openssl rand -hex 64)",+ "replacemewiththegeneratedstringfromthepriorstep",+ "replacemewiththegeneratedstring",+ "__SET_SECRET__"].freeze# Set only for the one-off commands of a key rotation (see the Docker@@ -70,7 +77,7 @@ module ActiveRecordEncryptionConfig# older, narrower version back into "not complete" until they re-run the# task - otherwise the legacy-plaintext fallback would get disabled for# models the install's last backfill never actually covered.- CURRENT_BACKFILL_VERSION = 12+ CURRENT_BACKFILL_VERSION = 13# Single source of truth for which models/fields security:backfill_encryption# covers, keyed by the same symbol the task's `results` hash uses. Model@@ -156,7 +163,7 @@ module ActiveRecordEncryptionConfigwise_accounts: [ "WiseAccount", %i[raw_payload raw_transactions_payload] ],api_keys: [ "ApiKey", %i[display_key] ],sso_providers: [ "SsoProvider", %i[client_secret] ],- sso_identity_blocks: [ "SsoIdentityBlock", %i[identity_label] ],+ sso_identity_blocks: [ "SsoIdentityBlock", %i[identity_label uid legacy_digest_key] ],security_audit_logs: [ "SecurityAuditLog", %i[user_email ip_address user_agent] ]}.freezediff --git a/test/lib/active_record_encryption_config_test.rb b/test/lib/active_record_encryption_config_test.rbindex a55c076682..51c8917688 100644--- a/test/lib/active_record_encryption_config_test.rb+++ b/test/lib/active_record_encryption_config_test.rb@@ -125,6 +125,18 @@ class ActiveRecordEncryptionConfigTest < ActiveSupport::TestCaserefute ActiveRecordEncryptionConfig.using_known_compromised_secret_key_base?("a-real-generated-secret")end+ test "detects the placeholders and the old .env.example value as publicly known" do+ [+ "secret-value",+ "$(openssl rand -hex 64)",+ "replacemewiththegeneratedstringfromthepriorstep",+ "replacemewiththegeneratedstring",+ "__SET_SECRET__"+ ].each do |public_value|+ assert ActiveRecordEncryptionConfig.using_known_compromised_secret_key_base?(public_value), public_value+ end+ end+test "using_known_compromised_secret_key_base? defaults to the app's own secret_key_base" doRails.application.stubs(:secret_key_base).returns(ActiveRecordEncryptionConfig::KNOWN_COMPROMISED_SECRET_KEY_BASES.first)assert ActiveRecordEncryptionConfig.using_known_compromised_secret_key_base?diff --git a/test/lib/tasks/security_backfill_test.rb b/test/lib/tasks/security_backfill_test.rbindex 47bc808d41..ae95acd057 100644--- a/test/lib/tasks/security_backfill_test.rb+++ b/test/lib/tasks/security_backfill_test.rb@@ -385,7 +385,8 @@ class SecurityBackfillTest < ActiveSupport::TestCase9 => "9f814939a5125a6903d9ba4e96392056ffafe9f6110b10b5c1cae0d87a564ac7",10 => "0bcaa72ed675acde5d5ae2ce72305bf73375c0faa5580fe80e3985e88aa4f9e4",11 => "e706a4aba7b25ef1ec3d9dacbd6ca489e4abe577b54875ac377a48138890b450",- 12 => "4122d5a8520c242fb5bad505511319806da13ed45996b47df2cb2ee34a4c041f"+ 12 => "4122d5a8520c242fb5bad505511319806da13ed45996b47df2cb2ee34a4c041f",+ 13 => "72593348d2ae17c23317f826de2e65b983356766c09fa3bcf92af01c26d54aa0"}.freezetest "backfill manifest changes come with a CURRENT_BACKFILL_VERSION bump" dodiff --git a/test/migrations/move_sso_identity_blocks_to_active_record_encryption_migration_test.rb b/test/migrations/move_sso_identity_blocks_to_active_record_encryption_migration_test.rbnew file mode 100644index 0000000000..d93ee6b79e--- /dev/null+++ b/test/migrations/move_sso_identity_blocks_to_active_record_encryption_migration_test.rb@@ -0,0 +1,84 @@+# frozen_string_literal: true++require "test_helper"+require Rails.root.join("db/migrate/20261117090000_move_sso_identity_blocks_to_active_record_encryption")++class MoveSsoIdentityBlocksToActiveRecordEncryptionMigrationTest < ActiveSupport::TestCase+ include SecretKeyBaseRotationHelper++ teardown { SsoIdentityBlock.reset_column_information }++ test "existing digest blocks keep matching after a SECRET_KEY_BASE change" do+ migrate(:down)+ insert_digest_block("legacy-subject")++ migrate(:up)++ assert SsoIdentityBlock.last.legacy_digest_key.present?+ with_rotated_secret_key_base do+ assert SsoIdentityBlock.blocked?(provider: "openid_connect", uid: "legacy-subject")+ end+ end++ test "down keeps blocks stored with an encrypted subject identifier" do+ SsoIdentityBlock.create!(provider: "openid_connect", uid: "new-subject", identity_label: "[email protected]")++ migrate(:down)++ assert_equal 1, connection.select_value(+ ActiveRecord::Base.sanitize_sql_array([ "SELECT COUNT(*) FROM sso_identity_blocks WHERE uid_digest = ?", SsoIdentityBlock.digest("new-subject") ])+ )+ migrate(:up)+ assert SsoIdentityBlock.blocked?(provider: "openid_connect", uid: "new-subject")+ end++ test "down refuses to lift blocks after a SECRET_KEY_BASE change" do+ migrate(:down)+ insert_digest_block("legacy-subject")+ migrate(:up)++ with_rotated_secret_key_base do+ assert_raises(ActiveRecord::IrreversibleMigration) { migrate(:down) }+ end+ end++ test "down refuses a block whose subject identifier does not decrypt" do+ block = SsoIdentityBlock.create!(provider: "openid_connect", uid: "new-subject", identity_label: "[email protected]")+ connection.execute(ActiveRecord::Base.sanitize_sql_array([ "UPDATE sso_identity_blocks SET uid = 'not-a-ciphertext' WHERE id = ?", block.id ]))++ assert_raises(ActiveRecord::IrreversibleMigration) { migrate(:down) }+ end++ test "down then up restores the columns and indexes" do+ before = shape++ migrate(:down)+ assert_not connection.column_exists?(:sso_identity_blocks, :uid)+ migrate(:up)++ assert_equal before, shape+ end++ private++ def connection = ActiveRecord::Base.connection++ def migrate(direction)+ ActiveRecord::Migration.suppress_messages { MoveSsoIdentityBlocksToActiveRecordEncryption.new.migrate(direction) }+ SsoIdentityBlock.reset_column_information+ end++ def insert_digest_block(uid)+ connection.execute(ActiveRecord::Base.sanitize_sql_array([ <<~SQL, SsoIdentityBlock.digest(uid) ]))+ INSERT INTO sso_identity_blocks (id, provider, uid_digest, identity_label, created_at, updated_at)+ VALUES (gen_random_uuid(), 'openid_connect', ?, 'Removed identity', NOW(), NOW())+ SQL+ end++ def shape+ [+ connection.columns(:sso_identity_blocks).map { |column| [ column.name, column.sql_type, column.null ] }.sort,+ connection.indexes(:sso_identity_blocks).map { |index| [ index.name, index.columns, index.unique, index.where ] }.sort+ ]+ end+enddiff --git a/test/models/sso_identity_block_test.rb b/test/models/sso_identity_block_test.rbindex 63bb485812..c4d9e36ba0 100644--- a/test/models/sso_identity_block_test.rb+++ b/test/models/sso_identity_block_test.rb@@ -1,13 +1,19 @@require "test_helper"class SsoIdentityBlockTest < ActiveSupport::TestCase- test "blocks an identity without storing its raw subject identifier" do+ include SecretKeyBaseRotationHelper++ test "blocks an identity with its subject identifier encrypted" doidentity = oidc_identities(:bob_google)SsoIdentityBlock.block_all!(OidcIdentity.where(id: identity.id), identity_label: identity.user.email)+ block = SsoIdentityBlock.lastassert SsoIdentityBlock.blocked?(provider: identity.provider, uid: identity.uid)- assert_not_equal identity.uid, SsoIdentityBlock.last.uid_digest+ assert_equal identity.uid, block.uid+ assert_equal SsoIdentityBlock.digest(identity.uid), block.uid_digest,+ "the previous release only checks the digest"+ assert_not_includes block.read_attribute_before_type_cast(:uid).to_s, identity.uidendtest "blocking the same identity is idempotent" do@@ -18,6 +24,81 @@ class SsoIdentityBlockTest < ActiveSupport::TestCaseendend+ test "a block survives a SECRET_KEY_BASE change" do+ identity = oidc_identities(:bob_google)+ SsoIdentityBlock.block_all!(OidcIdentity.where(id: identity.id), identity_label: identity.user.email)++ with_rotated_secret_key_base do+ assert SsoIdentityBlock.blocked?(provider: identity.provider, uid: identity.uid)+ end+ end++ test "a legacy digest block with its stored key survives a SECRET_KEY_BASE change" do+ key = Rails.application.key_generator.generate_key(SsoIdentityBlock::LEGACY_DIGEST_SALT, 32)+ SsoIdentityBlock.create!(+ provider: "openid_connect",+ uid_digest: SsoIdentityBlock.digest("legacy-subject", key: key),+ legacy_digest_key: Base64.strict_encode64(key),+ identity_label: "[email protected]"+ )++ with_rotated_secret_key_base do+ assert SsoIdentityBlock.blocked?(provider: "openid_connect", uid: "legacy-subject")+ assert_not SsoIdentityBlock.blocked?(provider: "openid_connect", uid: "other-subject")+ assert_not SsoIdentityBlock.blocked?(provider: "google_oauth2", uid: "legacy-subject")+ end+ end++ test "a legacy digest block without a stored key matches with the current key" do+ SsoIdentityBlock.create!(+ provider: "openid_connect",+ uid_digest: SsoIdentityBlock.digest("legacy-subject"),+ identity_label: "[email protected]"+ )++ assert SsoIdentityBlock.blocked?(provider: "openid_connect", uid: "legacy-subject")+ assert_not SsoIdentityBlock.blocked?(provider: "openid_connect", uid: "other-subject")+ end++ test "blocking an identity that a legacy digest already blocks adds no second block" do+ identity = oidc_identities(:bob_google)+ SsoIdentityBlock.create!(+ provider: identity.provider,+ uid_digest: SsoIdentityBlock.digest(identity.uid),+ identity_label: identity.user.email+ )++ assert_no_difference -> { SsoIdentityBlock.count } do+ SsoIdentityBlock.block_all!(OidcIdentity.where(id: identity.id), identity_label: identity.user.email)+ end+ end++ test "an unreadable stored key does not hide readable legacy keys and fails closed" do+ key = Rails.application.key_generator.generate_key(SsoIdentityBlock::LEGACY_DIGEST_SALT, 32)+ SsoIdentityBlock.create!(+ provider: "openid_connect",+ uid_digest: SsoIdentityBlock.digest("corrupt-subject", key: key),+ legacy_digest_key: "not base64 !",+ identity_label: "[email protected]"+ )+ SsoIdentityBlock.create!(+ provider: "openid_connect",+ uid_digest: SsoIdentityBlock.digest("legacy-subject", key: key),+ legacy_digest_key: Base64.strict_encode64(key),+ identity_label: "[email protected]"+ )+ SsoIdentityBlock.create!(provider: "openid_connect", uid: "new-subject", identity_label: "[email protected]")++ with_rotated_secret_key_base do+ assert SsoIdentityBlock.blocked?(provider: "openid_connect", uid: "legacy-subject")+ assert SsoIdentityBlock.blocked?(provider: "openid_connect", uid: "new-subject")+ assert SsoIdentityBlock.blocked?(provider: "openid_connect", uid: "someone-else"),+ "an identity the unreadable rows might cover must not pass"+ assert_nil SsoIdentityBlock.find_block(provider: "openid_connect", uid: "someone-else")+ assert_not SsoIdentityBlock.blocked?(provider: "google_oauth2", uid: "someone-else")+ end+ end+test "uses a keyed digest instead of a plain subject hash" douid = "predictable-subject"@@ -25,6 +106,13 @@ class SsoIdentityBlockTest < ActiveSupport::TestCaseassert_not_equal Digest::SHA256.hexdigest(uid), SsoIdentityBlock.digest(uid)end+ test "requires a subject identifier or a digest" do+ block = SsoIdentityBlock.new(provider: "openid_connect", identity_label: "[email protected]")++ assert_not block.valid?+ assert block.errors.added?(:uid, :blank)+ end+test "does not store the identity label in plaintext without encryption" doSsoIdentityBlock.stubs(:encryption_ready?).returns(false)raw_label = "[email protected]"@@ -38,4 +126,16 @@ class SsoIdentityBlockTest < ActiveSupport::TestCaseassert_not_equal raw_label, block.identity_labelassert_match(/Removed identity/, block.identity_label)end++ test "stores a digest instead of the subject identifier without encryption" do+ SsoIdentityBlock.stubs(:encryption_ready?).returns(false)+ identity = oidc_identities(:bob_google)++ SsoIdentityBlock.block_all!(OidcIdentity.where(id: identity.id), identity_label: identity.user.email)++ block = SsoIdentityBlock.last+ assert_nil block.read_attribute_before_type_cast(:uid)+ assert_equal SsoIdentityBlock.digest(identity.uid), block.uid_digest+ assert SsoIdentityBlock.blocked?(provider: identity.provider, uid: identity.uid)+ endenddiff --git a/test/support/secret_key_base_rotation_helper.rb b/test/support/secret_key_base_rotation_helper.rbnew file mode 100644index 0000000000..b62fc782bc--- /dev/null+++ b/test/support/secret_key_base_rotation_helper.rb@@ -0,0 +1,13 @@+module SecretKeyBaseRotationHelper+ # Simulates a changed SECRET_KEY_BASE for everything that derives keys+ # through Rails.application.key_generator.+ def with_rotated_secret_key_base+ rotated = ActiveSupport::CachingKeyGenerator.new(+ ActiveSupport::KeyGenerator.new(SecureRandom.hex(64), iterations: 1000, hash_digest_class: OpenSSL::Digest::SHA256)+ )+ Rails.application.stubs(:key_generator).returns(rotated)+ yield+ ensure+ Rails.application.unstub(:key_generator)+ end+enddiff --git a/test/test_helper.rb b/test/test_helper.rbindex c6e122df0c..f719aa3428 100644--- a/test/test_helper.rb+++ b/test/test_helper.rb@@ -29,6 +29,7 @@ require "uri"require Rails.root.join("test/support/sql_query_capture").to_srequire Rails.root.join("test/support/rake_task_test_helper").to_srequire Rails.root.join("test/support/family_lock_test_helper").to_s+require Rails.root.join("test/support/secret_key_base_rotation_helper").to_srequire Rails.root.join("test/support/ai_test_helper").to_srequire Rails.root.join("test/support/ai_legacy_setups").to_s