The personal finance app for everyone (by everyone)
Ruby
security: close remaining plaintext-storage gaps found while auditing #3142 (#3190)
GFR9d09a48af6ce
diff --git a/app/controllers/api/v1/auth_controller.rb b/app/controllers/api/v1/auth_controller.rbindex b860d07885..c7d768fdbe 100644--- a/app/controllers/api/v1/auth_controller.rb+++ b/app/controllers/api/v1/auth_controller.rb@@ -84,14 +84,14 @@ module Apienddef login- user = User.find_by_email_with_legacy_fallback(params[:email])+ user = User.authenticate_by_email(email: params[:email], password: params[:password])unless local_login_permitted_for?(user)render json: { error: "Local login is disabled. Please use SSO." }, status: :forbiddenreturnend- if user&.authenticate(params[:password])+ if userunless user.active?render json: { error: "This account has been deactivated. Please contact an administrator." }, status: :unauthorizedreturndiff --git a/app/controllers/settings/providers_controller.rb b/app/controllers/settings/providers_controller.rbindex ea29819322..c62b79e6a0 100644--- a/app/controllers/settings/providers_controller.rb+++ b/app/controllers/settings/providers_controller.rb@@ -170,8 +170,11 @@ class Settings::ProvidersController < ApplicationControllerenddef set_encryption_warning_context- @provider_setup_encryption_warning = Rails.configuration.app_mode.self_hosted? &&- !ActiveRecordEncryptionConfig.ready?+ self_hosted = Rails.configuration.app_mode.self_hosted?+ @provider_setup_encryption_warning = self_hosted && !ActiveRecordEncryptionConfig.ready?+ @provider_setup_compromised_secret_warning = self_hosted && !@provider_setup_encryption_warning &&+ !ActiveRecordEncryptionConfig.explicitly_configured? &&+ ActiveRecordEncryptionConfig.using_known_compromised_secret_key_base?end# Reload provider configurations after settings updatediff --git a/app/controllers/settings/securities_controller.rb b/app/controllers/settings/securities_controller.rbindex 5c1f2c5903..2dd280af77 100644--- a/app/controllers/settings/securities_controller.rb+++ b/app/controllers/settings/securities_controller.rb@@ -8,7 +8,10 @@ class Settings::SecuritiesController < ApplicationController]@oidc_identities = Current.user.oidc_identities.order(:provider)@webauthn_credentials = Current.user.webauthn_credentials.order(created_at: :asc)- @encryption_unconfigured = Rails.application.config.app_mode.self_hosted? &&- !ActiveRecordEncryptionConfig.ready?+ self_hosted = Rails.application.config.app_mode.self_hosted?+ @encryption_unconfigured = self_hosted && !ActiveRecordEncryptionConfig.ready?+ @encryption_using_compromised_secret = self_hosted && !@encryption_unconfigured &&+ !ActiveRecordEncryptionConfig.explicitly_configured? &&+ ActiveRecordEncryptionConfig.using_known_compromised_secret_key_base?endenddiff --git a/app/models/setting.rb b/app/models/setting.rbindex 085045cc36..c47812bf51 100644--- a/app/models/setting.rb+++ b/app/models/setting.rb@@ -146,15 +146,51 @@ class Setting < RailsSettings::Baseendend+ # The settings key is derived from SECRET_KEY_BASE alone, so it is not+ # covered by Active Record encryption's `previous` schemes. After a+ # SECRET_KEY_BASE change, stored values only decrypt with the old value;+ # the getters above would then return the ciphertext itself. This moves+ # every value the old key decrypts to the current key. Values neither key+ # decrypts are left alone: they are either plaintext from before+ # encryption (still readable) or need to be re-entered.+ def reencrypt_secrets_from(old_secret_key_base, dry_run: true)+ raise ArgumentError, "old secret_key_base is blank" if old_secret_key_base.blank?++ old_encryptor = build_setting_encryptor(old_secret_key_base)+ stored = where(var: ENCRYPTED_FIELDS.map(&:to_s)).to_h { |row| [ row.var.to_sym, row.value ] }++ transaction do+ ENCRYPTED_FIELDS.index_with do |field_name|+ value = stored[field_name]+ next :not_stored if value.blank?+ next :current unless try_decrypt(setting_encryptor, value).nil?++ plaintext = try_decrypt(old_encryptor, value)+ next :not_decryptable if plaintext.nil?+ next :would_reencrypt if dry_run++ public_send(:"#{field_name}=", plaintext)+ :reencrypted+ end+ end+ end+privatedef setting_encryptor- @setting_encryptor ||= begin- key = ActiveSupport::KeyGenerator.new(- Rails.application.secret_key_base- ).generate_key("setting_encryption", 32)- ActiveSupport::MessageEncryptor.new(key)- end+ @setting_encryptor ||= build_setting_encryptor(Rails.application.secret_key_base)+ end++ def build_setting_encryptor(secret_key_base)+ key = ActiveSupport::KeyGenerator.new(secret_key_base).generate_key("setting_encryption", 32)+ ActiveSupport::MessageEncryptor.new(key)+ end++ def try_decrypt(encryptor, value)+ encryptor.decrypt_and_verify(value)+ rescue ActiveSupport::MessageVerifier::InvalidSignature,+ ActiveSupport::MessageEncryptor::InvalidMessage+ nilenddef encrypt_setting(value)@@ -164,12 +200,10 @@ class Setting < RailsSettings::Basedef decrypt_setting(value)return value if value.blank?- setting_encryptor.decrypt_and_verify(value)- rescue ActiveSupport::MessageVerifier::InvalidSignature,- ActiveSupport::MessageEncryptor::InvalidMessage+# Value was stored before encryption was enabled — return as-is.# It will be re-encrypted on next write.- value+ try_decrypt(setting_encryptor, value) || valueendenddiff --git a/app/models/user.rb b/app/models/user.rbindex 2746d97d8e..32591f79b7 100644--- a/app/models/user.rb+++ b/app/models/user.rb@@ -115,11 +115,20 @@ class User < ApplicationRecord# unknown emails. The legacy lookup runs first on every login (one indexed# query) so that legacy and encrypted rows cost the same single password# check. Nil and empty passwords are rejected up front, as authenticate_by does.+ # A user without a local password (SSO only) still costs one hash, so+ # response time does not reveal such accounts. A non-String password (a+ # JSON number) is checked as text instead of raising.def self.authenticate_by_email(email:, password:)- return nil if password.nil? || password.empty?+ return nil if password.nil? || password.to_s.empty?+ password = password.to_snormalized = email.to_s.strip.downcaselegacy_user = find_by_legacy_plaintext_email(normalized)+ user = legacy_user || find_by(email: normalized)+ if user && user.password_digest.blank?+ new(password: password)+ return nil+ endreturn authenticate_by(email: normalized, password: password) unless legacy_userlegacy_user if legacy_user.authenticate(password)diff --git a/app/views/settings/providers/show.html.erb b/app/views/settings/providers/show.html.erbindex 851f821901..f112d7b608 100644--- a/app/views/settings/providers/show.html.erb+++ b/app/views/settings/providers/show.html.erb@@ -8,6 +8,13 @@message: t("settings.providers.encryption_error.message")) %><% else %>+ <% if @provider_setup_compromised_secret_warning %>+ <%= render DS::Alert.new(+ variant: :warning,+ title: t("settings.securities.show.compromised_secret_warning.title"),+ message: t("settings.securities.show.compromised_secret_warning.intro")+ ) %>+ <% end %><div class="flex items-center justify-between gap-4"><p class="text-secondary"><%= t("settings.providers.bank_sync.lede") %></p><% if @can_sync_all %>diff --git a/app/views/settings/securities/show.html.erb b/app/views/settings/securities/show.html.erbindex 2ec7ee1eb3..04e1fa4848 100644--- a/app/views/settings/securities/show.html.erb+++ b/app/views/settings/securities/show.html.erb@@ -15,6 +15,16 @@</div><% end %>+<% if @encryption_using_compromised_secret %>+ <div class="mb-4">+ <%= render DS::Alert.new(variant: :warning, title: t(".compromised_secret_warning.title")) do %>+ <p><%= t(".compromised_secret_warning.intro") %></p>+ <p><%= t(".compromised_secret_warning.generate") %></p>+ <p><%= t(".compromised_secret_warning.settings_secrets") %></p>+ <% end %>+ </div>+<% end %>+<%= settings_section title: t(".mfa_title"), subtitle: t(".mfa_description") do %><div class="space-y-4"><div class="p-3 shadow-border-xs bg-container rounded-lg md:flex md:justify-between md:items-center">diff --git a/compose.example.ai.yml b/compose.example.ai.ymlindex 15ba92aef4..0085142514 100644--- a/compose.example.ai.yml+++ b/compose.example.ai.yml@@ -74,10 +74,10 @@ x-rails-env: &rails_env# forge session cookies and, since ACTIVE_RECORD_ENCRYPTION_* below are# deterministically derived from it when unset, compute your encryption# keys too. Generate your own with: openssl rand -hex 64- # UPGRADING an existing install that ran on the old built-in default? Put- # that old value in .env first: a new value makes everything already- # encrypted under it unreadable. Rotate it later only as described in- # docs/hosting/docker.md ("Upgrading from the old built-in SECRET_KEY_BASE").+ # Upgrading an existing install? Do NOT generate a new value: keep the one+ # it already runs with (the old default if you never set one), or data+ # already encrypted under keys derived from it becomes unreadable. See+ # "Upgrading an install that is already running" in docs/hosting/docker.md.SECRET_KEY_BASE: "${SECRET_KEY_BASE:?Set SECRET_KEY_BASE in your .env file. Existing install: copy the value from your previous compose.yml, do not generate a new one. New install: openssl rand -hex 64}"# Optional but recommended: set these explicitly instead of relying on the# SECRET_KEY_BASE auto-derivation fallback. Generate with: bin/rails db:encryption:initdiff --git a/compose.example.yml b/compose.example.ymlindex 7fced7da9e..b44f135c65 100644--- a/compose.example.yml+++ b/compose.example.yml@@ -53,10 +53,10 @@ x-rails-env: &rails_env# forge session cookies and, since ACTIVE_RECORD_ENCRYPTION_* below are# deterministically derived from it when unset, compute your encryption# keys too. Generate your own with: openssl rand -hex 64- # UPGRADING an existing install that ran on the old built-in default? Put- # that old value in .env first: a new value makes everything already- # encrypted under it unreadable. Rotate it later only as described in- # docs/hosting/docker.md ("Upgrading from the old built-in SECRET_KEY_BASE").+ # Upgrading an existing install? Do NOT generate a new value: keep the one+ # it already runs with (the old default if you never set one), or data+ # already encrypted under keys derived from it becomes unreadable. See+ # "Upgrading an install that is already running" in docs/hosting/docker.md.SECRET_KEY_BASE: "${SECRET_KEY_BASE:?Set SECRET_KEY_BASE in your .env file. Existing install: copy the value from your previous compose.yml, do not generate a new one. New install: openssl rand -hex 64}"# Optional but recommended: set these explicitly instead of relying on the# SECRET_KEY_BASE auto-derivation fallback. Generate with: bin/rails db:encryption:initdiff --git a/config/initializers/active_record_encryption.rb b/config/initializers/active_record_encryption.rbindex 590098b1bc..42014868b0 100644--- a/config/initializers/active_record_encryption.rb+++ b/config/initializers/active_record_encryption.rb@@ -177,16 +177,14 @@ elsif Rails.application.config.app_mode.self_hosted? && !Rails.application.crede# For self-hosted instances without credentials or env vars, auto-generate keys# Use SECRET_KEY_BASE as the seed for deterministic key generation# This ensures keys are consistent across container restarts- secret_base = Rails.application.secret_key_base-- # Generate deterministic keys from the secret base- primary_key = Digest::SHA256.hexdigest("#{secret_base}:primary_key")[0..63]- deterministic_key = Digest::SHA256.hexdigest("#{secret_base}:deterministic_key")[0..63]- key_derivation_salt = Digest::SHA256.hexdigest("#{secret_base}:key_derivation_salt")[0..63]-- # Configure Active Record encryption- ActiveRecordEncryptionConfig.apply_keys!(- primary_key: primary_key, deterministic_key: deterministic_key, key_derivation_salt: key_derivation_salt- )+ ActiveRecordEncryptionConfig.apply_keys!(**ActiveRecordEncryptionConfig.derived_keys(Rails.application.secret_key_base))end# If none of the above conditions are met, credentials from application.rb will be used++# During a key rotation, data encrypted with the keys derived from an old+# SECRET_KEY_BASE stays readable through a previous scheme. Set on the live+# engine config: the snapshot described above has already fired, and+# `previous=` only appends, so setting the Rails config as well would add+# every scheme twice if the snapshot ran later.+previous_schemes = ActiveRecordEncryptionConfig.previous_schemes+ActiveRecord::Encryption.config.previous = previous_schemes if previous_schemes.any?diff --git a/config/initializers/encryption_warning.rb b/config/initializers/encryption_warning.rbindex 174b1a8946..42a8549878 100644--- a/config/initializers/encryption_warning.rb+++ b/config/initializers/encryption_warning.rb@@ -6,6 +6,16 @@require Rails.root.join("lib/active_record_encryption_config").to_sRails.application.config.after_initialize do+ if ActiveRecordEncryptionConfig.previous_keys_configured?+ Rails.logger.warn(<<~WARN)+ [SECURITY] Previous Active Record encryption keys are set+ (ACTIVE_RECORD_ENCRYPTION_PREVIOUS_*), so they are a previous encryption+ scheme. Set them only for the commands of a key rotation, not for the+ running app: while they are set, Rails writes deterministically+ encrypted values (emails, tokens, API keys) with the old key.+ WARN+ end+app_mode = Rails.application.config.app_mode# Scoped to self-hosted only: these two warnings are about AR encryption@@ -64,10 +74,10 @@ Rails.application.config.after_initialize doexplicitly configured and are NOT derived from SECRET_KEY_BASE, sothey are unaffected by this. Rotate SECRET_KEY_BASE to a uniquevalue regardless. Note this invalidates existing sessions and any- Setting-stored values encrypted under the old one, which will need- to be re-entered - there is currently no automated migration path- for those two, only for ActiveRecord Encryption's own keys (see- bin/rails db:encryption:init).+ Setting-stored values encrypted under the old one. Re-encrypt those+ with bin/rails "security:rotate_setting_secrets[0]", with the old+ value in the OLD_SECRET_KEY_BASE environment variable (see+ docs/hosting/encryption.md; keep it out of your shell history).WARNelseRails.logger.warn(<<~WARN)@@ -84,29 +94,22 @@ Rails.application.config.after_initialize dothe compromised key, the backfill task cannot tell that ciphertextapart from real plaintext, will re-encrypt it under the new key ontop of the old encryption, and the original data becomes- unrecoverable. Rotate safely instead - the full procedure, including- a runner script for step 3, is in docs/hosting/encryption.md:- (1) keep ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY (and friends) derived- from this SECRET_KEY_BASE configured as a `previous` encryption- scheme- (https://guides.rubyonrails.org/active_record_encryption.html#key-rotation)- so existing data still decrypts, and generate new keys with- bin/rails db:encryption:init as the current scheme; (2) re-encrypt- with DRY_RUN=false bin/rails security:backfill_encryption - the task- defaults to a dry run that changes nothing, so run it plain first to- preview; (3) migrate the deterministic attributes explicitly: while- the compromised scheme is still a `previous` scheme, Rails- deliberately re-serializes deterministic ("fixed") attributes -- user emails, otp_secret, provider tokens - under the OLDEST scheme- so equality lookups stay stable, which means the backfill leaves- exactly those columns under the compromised key- (https://github.com/rails/rails/blob/main/activerecord/lib/active_record/encryption/encrypted_attribute_type.rb,- serialize_with_oldest). Do NOT retire the compromised scheme until- those columns have been re-encrypted under the current key and- verified - removing it earlier makes every value still encrypted- under it permanently unreadable. This only migrates ActiveRecord- Encryption - Setting-stored values and existing sessions are not- covered and must be rotated / re-entered separately.+ unrecoverable. Rotate safely instead, with the app stopped (full+ procedure in docs/hosting/encryption.md): generate new keys with+ bin/rails db:encryption:init and set them as+ ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY, ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY+ and ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT, then run+ bin/rails "security:backfill_encryption[100,0]" with this+ SECRET_KEY_BASE in #{ActiveRecordEncryptionConfig::PREVIOUS_SECRET_KEY_BASE_ENV}+ for that command only, so existing data still decrypts and is+ re-encrypted under the new keys, deterministic columns included.+ When every model reports failed_count 0, start the app without that+ variable: while it is set, Rails writes deterministically encrypted+ values (emails, tokens, API keys) with the old key.+ Changing SECRET_KEY_BASE afterwards also changes the key for API keys+ and tokens saved in the settings (not covered by the previous scheme):+ re-encrypt them with bin/rails "security:rotate_setting_secrets[0]",+ with the old value in the OLD_SECRET_KEY_BASE environment variable.WARNendenddiff --git a/config/locales/views/settings/securities/en.yml b/config/locales/views/settings/securities/en.ymlindex 591fea8152..7b383b7e5c 100644--- a/config/locales/views/settings/securities/en.yml+++ b/config/locales/views/settings/securities/en.yml@@ -50,6 +50,11 @@ en:sso_confirm_body: Are you sure you want to disconnect your %{provider} account? You can reconnect it later by signing in with that provider again.sso_confirm_button: Disconnectsso_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.+ 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:code_already_used: That code was already used. Wait for the next code from your authenticator app.default_name: Security keydiff --git a/docs/hosting/docker.md b/docs/hosting/docker.mdindex 51fdff727e..1ccfe88e1e 100644--- a/docs/hosting/docker.md+++ b/docs/hosting/docker.md@@ -53,15 +53,7 @@ At this point, you should have `compose.yml` in your directory. It includes an o`compose.yml` requires a `SECRET_KEY_BASE` you provide yourself — there is no built-in default. This isn't just a Rails formality: `SECRET_KEY_BASE` also seeds the automatic generation of your Active Record encryption keys (used to encrypt provider API tokens/keys and other sensitive data at rest) when you don't set `ACTIVE_RECORD_ENCRYPTION_*` explicitly. A shared or guessable value would mean session cookies can be forged **and** your encryption keys can be computed by anyone. Follow the steps below before starting the app.-#### Upgrading from the old built-in SECRET_KEY_BASE--Earlier versions of `compose.example.yml` shipped a working default for `SECRET_KEY_BASE`. If your existing install ran without setting its own value, do **not** generate a new one when you update `compose.yml`:--1. Copy the `SECRET_KEY_BASE` default from your current `compose.yml` (the `${SECRET_KEY_BASE:-...}` value) into `.env` as `SECRET_KEY_BASE=...` before starting the new version. If you plan to set `ACTIVE_RECORD_ENCRYPTION_*` explicitly, leave them unset for now.-2. Start the app. It keeps reading your data, and the boot log shows a `[SECURITY]` warning because this value is publicly known.-3. Rotate afterwards following that warning: keep the keys derived from the old value as a `previous` [Active Record encryption scheme](https://guides.rubyonrails.org/active_record_encryption.html#key-rotation), set new keys as the current scheme, then run `bin/rails security:backfill_encryption`. Values stored via Settings (AI and market-data provider API keys) and existing sessions are not migrated and have to be re-entered after `SECRET_KEY_BASE` changes.--Setting a fresh `SECRET_KEY_BASE` (or new `ACTIVE_RECORD_ENCRYPTION_*` keys) directly on an install with existing data makes everything already encrypted unreadable: logins and provider syncs fail.+> **Upgrading an existing install?** Keep the `SECRET_KEY_BASE` it already runs with; generating a new one makes already-encrypted data unreadable. See [Upgrading an install that is already running](#upgrading-an-install-that-is-already-running-keep-your-secret_key_base).#### Create your environment file@@ -463,6 +455,55 @@ docker compose pull web worker # Pull the newest image for your tagdocker compose up -d # Restart on the new version; database migrations run automatically```+### Upgrading an install that is already running: keep your `SECRET_KEY_BASE`++Older example compose files shipped a built-in `SECRET_KEY_BASE` default. Current ones don't, so after refreshing `compose.yml` from the example, `docker compose up` stops with "Set SECRET_KEY_BASE in your .env file". **Do not generate a new value for an existing install.** Put the value your install already runs with into `.env` first (if you never set one, it is the `SECRET_KEY_BASE` default in your previous `compose.yml`).++Why: unless `ACTIVE_RECORD_ENCRYPTION_*` are set explicitly, your encryption keys are derived from `SECRET_KEY_BASE`. Changing it makes everything already encrypted under the old keys (provider tokens, API keys in settings, user emails and other encrypted fields) impossible to decrypt, which breaks logins and syncs. It also signs everyone out.++If the value you have been running with is that old public default, the app logs a `[SECURITY]` warning at boot.++If your `.env` already sets `ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY`, `ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY` and `ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT`, your data is encrypted with those keys, not with keys derived from `SECRET_KEY_BASE`. Keep them unchanged and skip steps 1 and 2: change `SECRET_KEY_BASE` and re-encrypt the settings as described below. To rotate explicit keys as well, follow [Encryption key rotation](encryption.md), which keeps the replaced keys readable as a `previous` scheme.++Otherwise, move your data to new encryption keys first, with a backup taken and the app stopped:++1. Generate new keys with `docker compose run --rm web bin/rails db:encryption:init` and put the three values into `.env` as `ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY`, `ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY` and `ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT`. Keep `SECRET_KEY_BASE` unchanged for now.+2. Stop the app and re-encrypt everything under the new keys. `ACTIVE_RECORD_ENCRYPTION_PREVIOUS_SECRET_KEY_BASE` holds the `SECRET_KEY_BASE` your data was encrypted with; it makes the keys derived from it a `previous` scheme ([key rotation](https://guides.rubyonrails.org/active_record_encryption.html#key-rotation)), so existing data still decrypts:++```bash+docker compose stop web worker+read -rs ACTIVE_RECORD_ENCRYPTION_PREVIOUS_SECRET_KEY_BASE && export ACTIVE_RECORD_ENCRYPTION_PREVIOUS_SECRET_KEY_BASE # paste the SECRET_KEY_BASE the data was encrypted with+docker compose run --rm -e ACTIVE_RECORD_ENCRYPTION_PREVIOUS_SECRET_KEY_BASE web bin/rails "security:backfill_encryption[100,1]" # dry run+```++Continue only if the dry run lists every table with `"failed_count":0`. Then write the changes:++```bash+docker compose run --rm -e ACTIVE_RECORD_ENCRYPTION_PREVIOUS_SECRET_KEY_BASE web bin/rails "security:backfill_encryption[100,0]" # writes+unset ACTIVE_RECORD_ENCRYPTION_PREVIOUS_SECRET_KEY_BASE+```++Start the app only if the JSON report on the last line of the write shows `"ok":true` and `"failed_count":0`; otherwise keep it stopped, restore the backup or fix the listed rows and run the write again:++```bash+docker compose up -d+```++Pass the variable only to these commands, never put it into `.env` or `compose.yml`: while it is set, Rails writes deterministically encrypted values (emails, tokens, API keys) with the old key. Only after that is it safe to change `SECRET_KEY_BASE`. Generating a fresh value right away is only safe for a new install.++If you already changed `SECRET_KEY_BASE` and logins or syncs broke, run step 2 with the old value in `ACTIVE_RECORD_ENCRYPTION_PREVIOUS_SECRET_KEY_BASE`, then re-encrypt the settings as described next.++Changing `SECRET_KEY_BASE` also affects settings. API keys and tokens saved on the self-hosting settings page (OpenAI and Anthropic tokens, market data and property valuation keys, and similar) are encrypted with a key derived from `SECRET_KEY_BASE` itself, not with the Active Record keys above, so the `previous` scheme does not cover them. Right after the change those settings no longer decrypt: the app does not show an error, it sends the stored ciphertext as the key and the provider rejects it. Re-encrypt them once, with the old value in `OLD_SECRET_KEY_BASE`:++```bash+read -rs OLD_SECRET_KEY_BASE && export OLD_SECRET_KEY_BASE # paste the previous value; keeps it out of your shell history+docker compose run --rm -e OLD_SECRET_KEY_BASE web bin/rails "security:rotate_setting_secrets[1]" # dry run: lists what would change+docker compose run --rm -e OLD_SECRET_KEY_BASE web bin/rails "security:rotate_setting_secrets[0]" # writes+unset OLD_SECRET_KEY_BASE+```++Check that the dry run's report shows `"dry_run":true`. It marks fields it would move as `would_reencrypt`; after the second command they read `reencrypted`. If nothing decrypts with the value you gave, the task stops with `old_secret_key_base_did_not_match`: check the value. Anything listed under `not_decryptable` was saved under neither value (or as plaintext before settings encryption existed); re-enter those keys on the settings page. If you prefer not to run the task, note the keys before the change and re-enter them afterwards.+### Re-encrypting data after an encryption-related updateIf a release note mentions a fix to Active Record encryption configuration, data written before you updated may still be stored as plaintext. Convert it as described in [Encrypting data stored without encryption](#encrypting-data-stored-without-encryption).@@ -677,10 +718,10 @@ Update Sure to a version that includes this guide first and let it start once, sdocker compose stop web worker```-3. Preview the conversion. This changes nothing, and must list every table with `"failed_count":0` and include a `session_ip_digests` entry:+3. Preview the conversion. The `1` makes it a dry run that changes nothing. Its report must show `"dry_run":true`, list every table with `"failed_count":0` and include a `session_ip_digests` entry:```bash- docker compose run --rm web bin/rails security:backfill_encryption+ docker compose run --rm web bin/rails "security:backfill_encryption[100,1]"```If rows fail, they hold data encrypted with keys the instance no longer has, for example after `SECRET_KEY_BASE` was changed. Don't convert: run `docker compose up -d`, and put the keys or `SECRET_KEY_BASE` that data was encrypted with back in place first.@@ -697,7 +738,7 @@ Update Sure to a version that includes this guide first and let it start once, s### Switching an existing instance to your own keys-Data an instance has already encrypted with the derived keys can't be read with new keys. The steps below first check whether the instance holds any such data. If it doesn't, for example because it was updated straight from a version that stored everything unencrypted, they convert it to your keys directly. If it does, moving that data to new keys is a key rotation, which these steps don't cover.+Data an instance has already encrypted with the derived keys can't be read with new keys. The steps below first check whether the instance holds any such data. If it doesn't, for example because it was updated straight from a version that stored everything unencrypted, they convert it to your keys directly. If it does, step 4 moves it to your keys with the derived keys as previous keys.> [!NOTE]> Already added the keys without these steps? Data encrypted with the old keys then reads back as unreadable text, and provider syncs fail. Remove the three lines from `.env` and run `docker compose up -d`. Keep the three values and use the same ones when you switch: anything the app wrote while they were active is encrypted with them.@@ -718,13 +759,20 @@ Update Sure to a version that includes this guide first and let it start once, s3. Add the three keys to `.env` (and the three lines to `compose.yml` if they are missing; see above).-4. Preview the conversion with the new keys. This changes nothing:+4. Preview the conversion with the new keys. The `1` makes it a dry run that changes nothing; its report must show `"dry_run":true`:++ ```bash+ docker compose run --rm web bin/rails "security:backfill_encryption[100,1]"+ ```++ Continue only if it lists every table with `"failed_count":0` and includes a `session_ip_digests` entry. Failed rows hold data encrypted with the derived keys. Then preview again with the keys derived from your `SECRET_KEY_BASE` as previous keys:```bash- docker compose run --rm web bin/rails security:backfill_encryption+ read -rs ACTIVE_RECORD_ENCRYPTION_PREVIOUS_SECRET_KEY_BASE && export ACTIVE_RECORD_ENCRYPTION_PREVIOUS_SECRET_KEY_BASE # paste the SECRET_KEY_BASE from .env+ docker compose run --rm -e ACTIVE_RECORD_ENCRYPTION_PREVIOUS_SECRET_KEY_BASE web bin/rails "security:backfill_encryption[100,1]"```- Continue only if it lists every table with `"failed_count":0` and includes a `session_ip_digests` entry. Failed rows hold data encrypted with the old keys. In that case, remove the three lines from `.env` again and run `docker compose up -d`. The instance keeps working with the derived keys, and its data stays encrypted with them. The manual rotation in [Encryption key rotation](encryption.md) needs a custom initializer and the old keys inside the containers, which the example compose files don't provide.+ If every table now shows `"failed_count":0`, add the same `-e ACTIVE_RECORD_ENCRYPTION_PREVIOUS_SECRET_KEY_BASE` to the command in step 5, and run `unset ACTIVE_RECORD_ENCRYPTION_PREVIOUS_SECRET_KEY_BASE` after it. Pass the variable only to these commands, never put it into `.env` or `compose.yml`: while it is set, Rails writes deterministically encrypted values (emails, tokens, API keys) with the old keys. If rows still fail, remove the three lines from `.env` again and run `docker compose up -d`. The instance keeps working with the derived keys.5. Convert the data:diff --git a/docs/hosting/encryption.md b/docs/hosting/encryption.mdindex ba4676c178..d28b86b757 100644--- a/docs/hosting/encryption.md+++ b/docs/hosting/encryption.md@@ -3,157 +3,76 @@If your `SECRET_KEY_BASE` was ever shipped as a default in this project'sexample Compose files (the boot log warns about this explicitly), or yourActive Record Encryption keys leaked for any other reason, the keys must be-rotated. Rotation is **not** just "set new keys and run the backfill": data-already encrypted under the old key must stay readable while it migrates,-and one class of columns — the deterministic ones — needs an explicit extra-step. This page is the full procedure the boot warning summarizes.+rotated. Data already encrypted under the old keys has to stay readable+while it moves to the new ones, so the old keys are given to the backfill+task as a `previous` scheme+([Rails key rotation](https://guides.rubyonrails.org/active_record_encryption.html#key-rotation))+for that one command only.-> Automated rotation tooling (one task covering everything below) is tracked-> in [we-promise/sure#3233](https://github.com/we-promise/sure/issues/3233).-> Until it lands, follow the manual steps.+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).-Take a database backup before starting, and expect a short maintenance-window for step 3–4.+## 1. Set new keys-## 1. Configure the new keys alongside the compromised ones--Generate a fresh key set:--```sh-bin/rails db:encryption:init-```--Set the new values as the current keys (via+Generate a fresh key set and configure it as the current keys via`ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY`,`ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY` and-`ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT`), and keep the compromised-set decryptable as a `previous` scheme — see the-[Rails key-rotation guide](https://guides.rubyonrails.org/active_record_encryption.html#key-rotation).-For example, in a temporary initializer that runs after the app's own-encryption initializer:--```ruby-# config/initializers/zz_encryption_rotation.rb (TEMPORARY - deleted in step 4)-Rails.application.config.active_record.encryption.previous_schemes <<- ActiveRecord::Encryption::Scheme.new(- primary_key: ENV.fetch("OLD_ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY"),- deterministic_key: ENV.fetch("OLD_ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY"),- key_derivation_salt: ENV.fetch("OLD_ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT")- )-```--Restart the app. Reads of old ciphertext keep working (Rails tries previous-schemes when decrypting), and new writes of ordinary encrypted attributes-use the new key.--## 2. Backfill — plaintext and ordinary encrypted columns+`ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT`:```sh-bin/rails security:backfill_encryption # dry run: reports what would change-DRY_RUN=false bin/rails security:backfill_encryption # actually re-encrypts+bin/rails db:encryption:init```-The task defaults to a dry run that changes nothing, so the plain command is-a safe preview. The write pass migrates never-encrypted legacy rows and-re-encrypts non-deterministic columns (e.g. `first_name`, `last_name`,-provider `raw_payload`s) under the new key.+Keep `SECRET_KEY_BASE` unchanged for now.-**It does not migrate deterministic columns** — see the next step.+## 2. Re-encrypt under the new keys-## 3. Migrate the deterministic attributes explicitly+Pass the old keys in the environment of the backfill command only:-Rails treats deterministic attributes (`encrypts ..., deterministic: true`-— user emails, `otp_secret`, invitation/invite tokens, provider tokens) as-*fixed*: while any previous scheme is configured, it deliberately-re-serializes them under the **oldest** scheme so that equality lookups-produce stable ciphertext-([`EncryptedAttributeType#serialize_with_oldest`](https://github.com/rails/rails/blob/main/activerecord/lib/active_record/encryption/encrypted_attribute_type.rb)).-Consequence: the step-2 backfill rewrites those columns right back under-the compromised key. They must be re-encrypted under the current key with-an explicit pass **before** the compromised scheme is retired.--List every affected attribute:+- Keys auto-derived from `SECRET_KEY_BASE` (no explicit keys were set):+ put that `SECRET_KEY_BASE` value in+ `ACTIVE_RECORD_ENCRYPTION_PREVIOUS_SECRET_KEY_BASE`.+- Explicitly set keys: put the old values in+ `ACTIVE_RECORD_ENCRYPTION_PREVIOUS_PRIMARY_KEY`,+ `ACTIVE_RECORD_ENCRYPTION_PREVIOUS_DETERMINISTIC_KEY` and+ `ACTIVE_RECORD_ENCRYPTION_PREVIOUS_KEY_DERIVATION_SALT`.```sh-grep -rn "deterministic: true" app/models+read -rs ACTIVE_RECORD_ENCRYPTION_PREVIOUS_SECRET_KEY_BASE && export ACTIVE_RECORD_ENCRYPTION_PREVIOUS_SECRET_KEY_BASE # keeps it out of your shell history+bin/rails "security:backfill_encryption[100,1]" # dry run: reports what would change+bin/rails "security:backfill_encryption[100,0]" # writes+unset ACTIVE_RECORD_ENCRYPTION_PREVIOUS_SECRET_KEY_BASE```-Then, for each model/attribute, decrypt-and-rewrite through a type that-knows only the current scheme. Example for `User#email` (mirror each-attribute's own declaration options — here `downcase: true`):--```ruby-# bin/rails runner rotate_deterministic.rb-new_key_type = ActiveRecord::Encryption::EncryptedAttributeType.new(- scheme: ActiveRecord::Encryption::Scheme.new(deterministic: true, downcase: true),- cast_type: ActiveRecord::Type::Text.new-)--User.find_each do |user|- plain = user.email # decrypts under whichever scheme can read it- next if plain.blank?- user.update_columns(email: new_key_type.serialize(plain))-end-```+The write pass encrypts legacy plaintext rows and re-encrypts every+encrypted column under the new keys, deterministic ones (emails,+`otp_secret`, tokens) included. A value that neither the new nor the old+keys decrypt is not touched and is reported under `failed_samples`. Check+that the task ends with `"ok": true` and `failed_count: 0` for every model;+it exits with status 1 otherwise.-Notes:--- `update_columns` is intentional: it bypasses callbacks/validations and- writes the exact ciphertext produced above.-- Run this while **both** schemes are still configured. Lookups keep- matching throughout: `extend_queries` (enabled by this app) extends- deterministic queries to every configured scheme, so rows on the old key- and rows on the new key are both found during the mixed window.-- Repeat for every attribute from the grep, adjusting `deterministic:` /- `downcase:` / `ignore_case:` to match its `encrypts` declaration.--### Verify before retiring the old key--A ciphertext that still needs the compromised key must not survive this-step. Check every rewritten column decrypts under the **new scheme only**-(`support_unencrypted_data: false` is what makes this check strict — the-app's global setting would otherwise paper over failures by returning the-raw ciphertext):--```ruby-strict_type = ActiveRecord::Encryption::EncryptedAttributeType.new(- scheme: ActiveRecord::Encryption::Scheme.new(- deterministic: true, downcase: true, support_unencrypted_data: false- ),- cast_type: ActiveRecord::Type::Text.new-)--bad = 0-User.find_each do |user|- raw = user.read_attribute_before_type_cast(:email)- next if raw.blank?- begin- strict_type.deserialize(raw)- rescue ActiveRecord::Encryption::Errors::Decryption- bad += 1- end-end-puts "rows not yet on the new key: #{bad}"-```+## 3. Start the app without the old keys-`bad` must be 0 for every deterministic column before moving on. (Legacy-rows that were never encrypted at all also fail this check — run the-step-2 backfill first, or re-run step 3 for those rows.)+Start the app with the `ACTIVE_RECORD_ENCRYPTION_PREVIOUS_*` variables+unset. While they are set, Rails writes deterministically encrypted values+with the old key (it keeps equality lookups stable that way), and the app+logs a warning at boot. Spot-check a login, a provider sync and an MFA+flow.-## 4. Retire the compromised scheme+## 4. Settings and `SECRET_KEY_BASE`-Only after step 3's verification passes for every deterministic attribute:-delete `config/initializers/zz_encryption_rotation.rb` (and the-`OLD_ACTIVE_RECORD_ENCRYPTION_*` variables), restart, and spot-check a-login, a deterministic lookup (`User.find_by(email:)`), a provider sync and-an MFA flow.+`SECRET_KEY_BASE` itself also signs session cookies and is the key source+for values saved on the self-hosting settings page (AI and market-data+provider keys). Once the steps above are done, it is safe to change it.+Existing sessions are signed out. Re-encrypt the settings once, with the+old value in `OLD_SECRET_KEY_BASE`:-## What this does not cover+```sh+read -rs OLD_SECRET_KEY_BASE && export OLD_SECRET_KEY_BASE+bin/rails "security:rotate_setting_secrets[1]" # dry run, check "dry_run":true+bin/rails "security:rotate_setting_secrets[0]" # writes+unset OLD_SECRET_KEY_BASE+```-- **`SECRET_KEY_BASE` itself** still signs session cookies and is the sole- key source for `Setting`-encrypted values (AI/market-data provider keys).- Rotating it invalidates existing sessions and Setting-stored values,- which must be re-entered — there is no automated migration for those two.-- Rotating `SECRET_KEY_BASE` also changes the auto-derived AR encryption- keys on installs that never set them explicitly; that is exactly the- scenario this procedure exists for.+Re-enter any key the task lists under `not_decryptable`.diff --git a/lib/active_record_encryption_config.rb b/lib/active_record_encryption_config.rbindex 1a904b7f18..8ff1483abf 100644--- a/lib/active_record_encryption_config.rb+++ b/lib/active_record_encryption_config.rb@@ -19,6 +19,43 @@ module ActiveRecordEncryptionConfiga7523c3d0ae56415046ad8abae168d71074a79534a7062258f8d1d51ac2f76d3c3bc86d86b6b0b307df30d9a6a90a2066a3fa9e67c5e6f374dbd7dd4e0778e13].freeze+ # Set only for the one-off commands of a key rotation (see the Docker+ # hosting guide): the SECRET_KEY_BASE whose derived keys encrypted the+ # existing data, so it still decrypts while the backfill moves it to the+ # current keys.+ PREVIOUS_SECRET_KEY_BASE_ENV = "ACTIVE_RECORD_ENCRYPTION_PREVIOUS_SECRET_KEY_BASE"++ # The same for old keys that were set explicitly rather than derived.+ PREVIOUS_ENV_KEYS = {+ primary_key: "ACTIVE_RECORD_ENCRYPTION_PREVIOUS_PRIMARY_KEY",+ deterministic_key: "ACTIVE_RECORD_ENCRYPTION_PREVIOUS_DETERMINISTIC_KEY",+ key_derivation_salt: "ACTIVE_RECORD_ENCRYPTION_PREVIOUS_KEY_DERIVATION_SALT"+ }.freeze++ # Previous-scheme key provider for keys derived from an old+ # SECRET_KEY_BASE. Rails derives every scheme's keys with the globally+ # configured salt, so the old salt needs a provider of its own. Keys are+ # derived on first use, once Rails has settled hash_digest_class.+ class DerivedKeyProvider+ def initialize(password, salt)+ @password = password+ @salt = salt+ end++ def encryption_key+ @encryption_key ||= begin+ config = ActiveRecord::Encryption.config+ secret = ActiveSupport::KeyGenerator.new(@password, hash_digest_class: config.hash_digest_class)+ .generate_key(@salt, ActiveRecord::Encryption.cipher.key_length)+ ActiveRecord::Encryption::Key.new(secret)+ end+ end++ def decryption_keys(_encrypted_message)+ [ encryption_key ]+ end+ end+CONFIG_KEYS = %i[primary_keydeterministic_key@@ -54,7 +91,9 @@ module ActiveRecordEncryptionConfig# whenever this changes. Session is deliberately excluded: its backfill# (lib/tasks/security_backfill.rake#backfill_sessions) also hashes# ip_address into ip_address_digest, which isn't a 1:1 encrypted copy of an- # existing field the way every entry below is.+ # existing field the way every entry below is. otp_backup_codes is not+ # listed: it is a PostgreSQL array column, which Active Record encryption+ # does not support.BACKFILL_MANIFEST = {users: [ "User", %i[otp_secret email unconfirmed_email first_name last_name] ],invitations: [ "Invitation", %i[token email] ],@@ -258,6 +297,44 @@ module ActiveRecordEncryptionConfigfalseend+ # The keys config/initializers/active_record_encryption.rb derives from+ # SECRET_KEY_BASE when no explicit keys are configured.+ def derived_keys(secret_key_base)+ CONFIG_KEYS.to_h do |key|+ [ key, Digest::SHA256.hexdigest("#{secret_key_base}:#{key}")[0..63] ]+ end+ end++ # Previous schemes for `config.active_record.encryption.previous`, built+ # from the keys derived from PREVIOUS_SECRET_KEY_BASE_ENV or from the+ # PREVIOUS_ENV_KEYS. Rails applies a global previous scheme only to+ # attributes with the same determinism, so there is one scheme for each kind.+ def previous_schemes(env = ENV)+ keys = previous_keys(env)+ return [] unless keys++ [+ { key_provider: DerivedKeyProvider.new(keys[:primary_key], keys[:key_derivation_salt]) },+ { deterministic: true, key_provider: DerivedKeyProvider.new(keys[:deterministic_key], keys[:key_derivation_salt]) }+ ]+ end++ def previous_keys(env = ENV)+ if env_value_present?(env, PREVIOUS_SECRET_KEY_BASE_ENV)+ derived_keys(env[PREVIOUS_SECRET_KEY_BASE_ENV])+ elsif PREVIOUS_ENV_KEYS.values.any? { |key| env_value_present?(env, key) }+ missing = PREVIOUS_ENV_KEYS.values.reject { |key| env_value_present?(env, key) }+ raise "Previous Active Record encryption keys are partially configured. Missing: #{missing.join(', ')}" if missing.any?++ PREVIOUS_ENV_KEYS.transform_values { |key| env[key] }+ end+ end++ def previous_keys_configured?(env = ENV)+ env_value_present?(env, PREVIOUS_SECRET_KEY_BASE_ENV) ||+ PREVIOUS_ENV_KEYS.values.any? { |key| env_value_present?(env, key) }+ end+def env_value_present?(env, key)env[key].present?enddiff --git a/lib/tasks/security_backfill.rake b/lib/tasks/security_backfill.rakeindex 1501bdd10d..c4762ed6e2 100644--- a/lib/tasks/security_backfill.rake+++ b/lib/tasks/security_backfill.rake@@ -12,11 +12,8 @@ namespace :security do# manual recovery script in issue #2611 first, then re-run this task.## During a key rotation (docs/hosting/encryption.md) the write pass also- # re-encrypts existing ciphertext under the current key - EXCEPT for- # deterministic attributes, which Rails re-serializes under the OLDEST- # configured scheme while any previous scheme exists. This task therefore- # cannot migrate deterministic columns off a compromised key; see step 3- # of the rotation procedure.+ # re-encrypts existing ciphertext under the current key, deterministic+ # attributes included (see current_key_ciphertexts).desc "Backfill encryption for sensitive fields (idempotent). Args: batch_size, dry_run"task :backfill_encryption, [ :batch_size, :dry_run ] => :environment do |_, args|raw_batch = args[:batch_size].presence || ENV["BATCH_SIZE"].presence || "100"@@ -138,14 +135,19 @@ namespace :security doencryptor.send("#{field}=", value)end+ # During a key rotation Rails would write deterministic fields+ # under the oldest key, so those get current-key ciphertext.+ rotated = current_key_ciphertexts(encryptor, plaintext_values.keys)+# Extract the encrypted values from the temporary instanceencrypted_attrs = {}- plaintext_values.keys.each do |field|+ (plaintext_values.keys - rotated.keys).each do |field|encrypted_attrs[field] = encryptor.read_attribute_before_type_cast(field)end# Write directly to database, bypassing callbacks/validations- record.update_columns(encrypted_attrs)+ record.update_columns(encrypted_attrs) if encrypted_attrs.any?+ write_raw_columns(record, rotated) if rotated.any?trueendupdated += 1 if written@@ -166,6 +168,44 @@ namespace :security do}end+ # While `previous` schemes are configured (a key rotation), Rails encrypts+ # deterministic attributes with the OLDEST scheme so equality lookups keep+ # matching. Re-encrypting that way would leave the data under the key+ # being rotated out, so build ciphertext with the current scheme instead,+ # the same way EncryptedAttributeType does when no previous scheme exists.+ def current_key_ciphertexts(instance, fields)+ fields.each_with_object({}) do |field, ciphertexts|+ type = backfill_encrypted_type(instance.class, field)+ next unless type.fixed? && type.previous_schemes.any?++ value = type.cast_type.serialize(instance.read_attribute(field))+ next if value.nil?++ value = value.downcase if type.downcase?+ ciphertexts[field] = type.with_context do+ ActiveRecord::Encryption.encryptor.encrypt(+ value.to_s, **{ key_provider: type.key_provider, cipher_options: { deterministic: true } }.compact+ )+ end+ end+ end++ # `normalizes` wraps the encrypted type, so unwrap to reach it.+ def backfill_encrypted_type(model_class, field)+ type = model_class.type_for_attribute(field)+ type = type.cast_type while !type.is_a?(ActiveRecord::Encryption::EncryptedAttributeType) && type.respond_to?(:cast_type)+ return type if type.is_a?(ActiveRecord::Encryption::EncryptedAttributeType)++ raise ArgumentError, "#{model_class.name}##{field} is not an encrypted attribute"+ end++ # Raw SQL so the attribute type does not encrypt the ciphertext again.+ def write_raw_columns(record, values)+ connection = record.class.connection+ assignments = values.keys.map { |field| "#{connection.quote_column_name(field)} = ?" }.join(", ")+ record.class.where(id: record.id).update_all([ assignments, *values.values ])+ end+# Rails' encryption envelope: {"p": payload, "h": {"iv": ..., "at": ..., ...}}.# Matches the whole shape, since Encryptor#encrypted? accepts any object# with a "p" key and would flag plaintext payloads such as {"p": null}.diff --git a/lib/tasks/security_setting_secrets.rake b/lib/tasks/security_setting_secrets.rakenew file mode 100644index 0000000000..fc3bf97d2a--- /dev/null+++ b/lib/tasks/security_setting_secrets.rake@@ -0,0 +1,54 @@+# frozen_string_literal: true++namespace :security do+ desc "Re-encrypt encrypted settings (API keys, tokens) after a SECRET_KEY_BASE change. " \+ "Reads the previous value from OLD_SECRET_KEY_BASE. Args: dry_run (default 1)"+ task :rotate_setting_secrets, [ :dry_run ] => :environment do |_, args|+ raw_dry = args[:dry_run].presence || ENV["DRY_RUN"].presence+ dry_run = !%w[0 false no n].include?(raw_dry.to_s.strip.downcase)++ old_secret_key_base = ENV["OLD_SECRET_KEY_BASE"].to_s.strip+ if old_secret_key_base.blank?+ puts({+ ok: false,+ error: "old_secret_key_base_missing",+ message: "Set OLD_SECRET_KEY_BASE to the SECRET_KEY_BASE value the settings were saved with."+ }.to_json)+ exit 1+ end++ if old_secret_key_base == Rails.application.secret_key_base+ puts({+ ok: false,+ error: "secret_key_base_unchanged",+ message: "OLD_SECRET_KEY_BASE equals the current SECRET_KEY_BASE. Change SECRET_KEY_BASE first, then run this task."+ }.to_json)+ exit 1+ end++ results = Setting.reencrypt_secrets_from(old_secret_key_base, dry_run: dry_run)+ not_decryptable = results.select { |_, status| status == :not_decryptable }.keys+ moved = results.values.intersect?(%i[reencrypted would_reencrypt])++ # Nothing decrypted with the old value, but some fields need it: the value+ # is most likely mistyped. Report that instead of telling the operator to+ # re-enter every key.+ if not_decryptable.any? && !moved+ puts({+ ok: false,+ error: "old_secret_key_base_did_not_match",+ message: "No setting decrypts with OLD_SECRET_KEY_BASE. Check the value, or re-enter the listed keys if it is correct.",+ results: results,+ not_decryptable: not_decryptable+ }.to_json)+ exit 1+ end++ puts({+ ok: true,+ dry_run: dry_run,+ results: results,+ not_decryptable: not_decryptable+ }.to_json)+ end+enddiff --git a/test/controllers/api/v1/auth_controller_test.rb b/test/controllers/api/v1/auth_controller_test.rbindex 9043e4587a..669cb2b584 100644--- a/test/controllers/api/v1/auth_controller_test.rb+++ b/test/controllers/api/v1/auth_controller_test.rb@@ -541,6 +541,21 @@ class Api::V1::AuthControllerTest < ActionDispatch::IntegrationTestassert_equal "Invalid email or password", response_data["error"]end+ test "login with a non-existent email still hashes the password" do+ # Same cost as a wrong password, so response time does not reveal+ # whether the email is registered.+ digest = BCrypt::Password.create(user_password_test, cost: BCrypt::Engine::MIN_COST)+ BCrypt::Password.expects(:create).once.returns(digest)++ post "/api/v1/auth/login", params: {+ email: "[email protected]",+ password: user_password_test,+ device: @device_info+ }++ assert_response :unauthorized+ end+test "should login even when OAuth application is missing" douser = users(:family_admin)password = user_password_test@@ -872,7 +887,7 @@ class Api::V1::AuthControllerTest < ActionDispatch::IntegrationTesttest "login rejects a user purged between authentication and the reload fast-path" douser = users(:family_admin)- User.stubs(:find_by).with(email: user.email).returns(user)+ User.stubs(:authenticate_by_email).returns(user)user.stubs(:reload).raises(ActiveRecord::RecordNotFound)post "/api/v1/auth/login", params: {diff --git a/test/controllers/oidc_accounts_controller_test.rb b/test/controllers/oidc_accounts_controller_test.rbindex 113da4f7b9..9aa09529af 100644--- a/test/controllers/oidc_accounts_controller_test.rb+++ b/test/controllers/oidc_accounts_controller_test.rb@@ -194,6 +194,32 @@ class OidcAccountsControllerTest < ActionController::TestCaseassert_select "strong", text: new_user_auth["email"]end+ test "link page offers linking, not account creation, for a legacy plaintext-email user" do+ skip "Encryption not configured" unless User.encryption_ready?++ ActiveRecord::Base.connection.execute(+ ActiveRecord::Base.sanitize_sql([ "UPDATE users SET email = ? WHERE id = ?", new_user_auth["email"], @user.id ])+ )+ session[:pending_oidc_auth] = new_user_auth++ get :link+ assert_response :success+ assert_select "p", text: /Create New Account/, count: 0+ end++ test "create_user does not create a duplicate of a legacy plaintext-email user" do+ skip "Encryption not configured" unless User.encryption_ready?++ ActiveRecord::Base.connection.execute(+ ActiveRecord::Base.sanitize_sql([ "UPDATE users SET email = ? WHERE id = ?", new_user_auth["email"], @user.id ])+ )+ session[:pending_oidc_auth] = new_user_auth++ assert_no_difference [ "User.count", "OidcIdentity.count", "Family.count" ] do+ post :create_user+ end+ end+test "does not show create account button when JIT link-only mode" dosession[:pending_oidc_auth] = new_user_authdiff --git a/test/controllers/sessions_controller_test.rb b/test/controllers/sessions_controller_test.rbindex 575d399eab..97d94e73c6 100644--- a/test/controllers/sessions_controller_test.rb+++ b/test/controllers/sessions_controller_test.rb@@ -193,7 +193,7 @@ class SessionsControllerTest < ActionDispatch::IntegrationTesttest "does not issue a session when user is deleted before row locking" do@user.stubs(:with_lock).raises(ActiveRecord::RecordNotFound)- User.stubs(:authenticate_by).returns(@user)+ User.stubs(:authenticate_by_email).returns(@user)assert_no_difference("Session.count") dopost sessions_url, params: { email: @user.email, password: user_password_test }diff --git a/test/controllers/settings/providers_controller_test.rb b/test/controllers/settings/providers_controller_test.rbindex 87aba748c0..9db9a1950b 100644--- a/test/controllers/settings/providers_controller_test.rb+++ b/test/controllers/settings/providers_controller_test.rb@@ -713,6 +713,55 @@ class Settings::ProvidersControllerTest < ActionDispatch::IntegrationTestSetting["plaid_secret"] = nilend+ test "GET show warns when encryption keys are auto-derived from a known compromised secret" do+ Rails.configuration.stubs(:app_mode).returns("self_hosted".inquiry)+ ActiveRecordEncryptionConfig.stubs(:ready?).returns(true)+ ActiveRecordEncryptionConfig.stubs(:explicitly_configured?).returns(false)+ ActiveRecordEncryptionConfig.stubs(:using_known_compromised_secret_key_base?).returns(true)++ get settings_providers_url++ assert_response :success+ assert_includes response.body, I18n.t("settings.securities.show.compromised_secret_warning.title")+ end++ # Explicit keys are not derived from SECRET_KEY_BASE, so the banner's+ # "encryption keys are not actually secret" does not apply to them.+ test "GET show hides compromised secret warning when encryption keys are set explicitly" do+ Rails.configuration.stubs(:app_mode).returns("self_hosted".inquiry)+ ActiveRecordEncryptionConfig.stubs(:ready?).returns(true)+ ActiveRecordEncryptionConfig.stubs(:explicitly_configured?).returns(true)+ ActiveRecordEncryptionConfig.stubs(:using_known_compromised_secret_key_base?).returns(true)++ get settings_providers_url++ assert_response :success+ refute_includes response.body, I18n.t("settings.securities.show.compromised_secret_warning.title")+ end++ test "GET show hides compromised secret warning when encryption keys are not explicitly configured" do+ # The "not configured at all" warning takes priority; don't show both.+ Rails.configuration.stubs(:app_mode).returns("self_hosted".inquiry)+ ActiveRecordEncryptionConfig.stubs(:ready?).returns(false)+ ActiveRecordEncryptionConfig.stubs(:using_known_compromised_secret_key_base?).returns(true)++ get settings_providers_url++ assert_response :success+ refute_includes response.body, I18n.t("settings.securities.show.compromised_secret_warning.title")+ end++ test "GET show hides compromised secret warning in managed mode" do+ Rails.configuration.stubs(:app_mode).returns("managed".inquiry)+ ActiveRecordEncryptionConfig.stubs(:ready?).returns(true)+ ActiveRecordEncryptionConfig.stubs(:using_known_compromised_secret_key_base?).returns(true)++ get settings_providers_url++ assert_response :success+ refute_includes response.body, I18n.t("settings.securities.show.compromised_secret_warning.title")+ end+test "GET connect_form renders Interactive Brokers panel" doget connect_form_settings_providers_path(provider_key: "ibkr")diff --git a/test/controllers/settings/securities_controller_test.rb b/test/controllers/settings/securities_controller_test.rbindex 929066e15c..8770f2e3ee 100644--- a/test/controllers/settings/securities_controller_test.rb+++ b/test/controllers/settings/securities_controller_test.rb@@ -55,6 +55,66 @@ class Settings::SecuritiesControllerTest < ActionDispatch::IntegrationTestcount: 0end+ test "warns when encryption keys are auto-derived from a known compromised secret" do+ Rails.configuration.stubs(:app_mode).returns("self_hosted".inquiry)+ ActiveRecordEncryptionConfig.stubs(:ready?).returns(true)+ ActiveRecordEncryptionConfig.stubs(:explicitly_configured?).returns(false)+ ActiveRecordEncryptionConfig.stubs(:using_known_compromised_secret_key_base?).returns(true)++ get settings_security_url++ assert_response :success+ assert_includes response.body, I18n.t("settings.securities.show.compromised_secret_warning.title")+ assert_includes response.body, "security:rotate_setting_secrets"+ end++ # Explicit keys are not derived from SECRET_KEY_BASE, so the banner's+ # "encryption keys are not actually secret" does not apply to them.+ test "hides compromised secret warning when encryption keys are set explicitly" do+ Rails.configuration.stubs(:app_mode).returns("self_hosted".inquiry)+ ActiveRecordEncryptionConfig.stubs(:ready?).returns(true)+ ActiveRecordEncryptionConfig.stubs(:explicitly_configured?).returns(true)+ ActiveRecordEncryptionConfig.stubs(:using_known_compromised_secret_key_base?).returns(true)++ get settings_security_url++ assert_response :success+ assert_not_includes response.body, I18n.t("settings.securities.show.compromised_secret_warning.title")+ end++ test "hides compromised secret warning when encryption is not configured at all" do+ # The "not configured" warning takes priority; don't show both.+ Rails.configuration.stubs(:app_mode).returns("self_hosted".inquiry)+ ActiveRecordEncryptionConfig.stubs(:ready?).returns(false)+ ActiveRecordEncryptionConfig.stubs(:using_known_compromised_secret_key_base?).returns(true)++ get settings_security_url++ assert_response :success+ assert_not_includes response.body, I18n.t("settings.securities.show.compromised_secret_warning.title")+ end++ test "hides compromised secret warning when keys are not derived from the known value" do+ Rails.configuration.stubs(:app_mode).returns("self_hosted".inquiry)+ ActiveRecordEncryptionConfig.stubs(:ready?).returns(true)+ ActiveRecordEncryptionConfig.stubs(:using_known_compromised_secret_key_base?).returns(false)++ get settings_security_url++ assert_response :success+ assert_not_includes response.body, I18n.t("settings.securities.show.compromised_secret_warning.title")+ end++ test "does not show compromised secret warning in managed mode" do+ Rails.configuration.stubs(:app_mode).returns("managed".inquiry)+ ActiveRecordEncryptionConfig.stubs(:using_known_compromised_secret_key_base?).returns(true)++ get settings_security_url++ assert_response :success+ assert_not_includes response.body, I18n.t("settings.securities.show.compromised_secret_warning.title")+ end+test "the disable-MFA control asks for the password" douser = users(:family_admin)user.setup_mfa!diff --git a/test/initializers/active_record_encryption_test.rb b/test/initializers/active_record_encryption_test.rbindex b3e86cc437..1b7dffce76 100644--- a/test/initializers/active_record_encryption_test.rb+++ b/test/initializers/active_record_encryption_test.rb@@ -84,6 +84,125 @@ class ActiveRecordEncryptionInitializerTest < ActiveSupport::TestCaseassert_equal "[email protected]", user.reload.emailend+ test "User.find_by_email_with_legacy_fallback works around the known limitation for legacy plaintext rows" do+ skip "Encryption not configured" unless User.encryption_ready?++ user = users(:family_admin)+ ActiveRecord::Base.connection.execute(+ ActiveRecord::Base.sanitize_sql([ "UPDATE users SET email = ? WHERE id = ?", "[email protected]", user.id ])+ )++ assert_equal user, User.find_by_email_with_legacy_fallback("[email protected]")+ # Also matches with surrounding whitespace/mixed case, like a raw form param.+ assert_equal user, User.find_by_email_with_legacy_fallback(" [email protected] ")+ end++ test "User.authenticate_by_email works around the known limitation for legacy plaintext rows" do+ skip "Encryption not configured" unless User.encryption_ready?++ user = users(:family_admin)+ user.update!(password: "correct-horse-battery-staple")+ ActiveRecord::Base.connection.execute(+ ActiveRecord::Base.sanitize_sql([ "UPDATE users SET email = ? WHERE id = ?", "[email protected]", user.id ])+ )++ assert_equal user, User.authenticate_by_email(email: "[email protected]", password: "correct-horse-battery-staple")+ assert_nil User.authenticate_by_email(email: "[email protected]", password: "wrong-password")+ end++ test "User.authenticate_by_email runs exactly one password check for an already-encrypted user" do+ skip "Encryption not configured" unless User.encryption_ready?++ user = users(:family_admin)+ user.update!(password: "correct-horse-battery-staple")++ BCrypt::Password.expects(:create).never+ BCrypt::Password.any_instance.expects(:is_password?).twice.returns(true, false)++ assert_equal user, User.authenticate_by_email(email: user.email, password: "correct-horse-battery-staple")+ assert_nil User.authenticate_by_email(email: user.email, password: "wrong-password")+ end++ test "User.authenticate_by_email still hashes the password for an SSO-only user" do+ skip "Encryption not configured" unless User.encryption_ready?++ user = users(:family_admin)+ user.update_column(:password_digest, nil)++ digest = BCrypt::Password.create("whatever", cost: BCrypt::Engine::MIN_COST)+ BCrypt::Password.expects(:create).once.returns(digest)++ assert_nil User.authenticate_by_email(email: user.email, password: "whatever")+ end++ test "User.authenticate_by_email rejects a blank or non-String password without raising" do+ skip "Encryption not configured" unless User.encryption_ready?++ user = users(:family_admin)++ BCrypt::Password.expects(:create).never+ assert_nil User.authenticate_by_email(email: user.email, password: "")+ assert_nil User.authenticate_by_email(email: user.email, password: nil)+ assert_nil User.authenticate_by_email(email: "[email protected]", password: "")++ BCrypt::Password.unstub(:create)+ assert_nil User.authenticate_by_email(email: user.email, password: 123456)+ end++ test "User.authenticate_by_email returns nil for an email that matches no user, plaintext or encrypted" do+ skip "Encryption not configured" unless User.encryption_ready?++ assert_nil User.authenticate_by_email(email: "[email protected]", password: "whatever")+ end++ test "User.authenticate_by_email still hashes the password for an email that matches no user" do+ skip "Encryption not configured" unless User.encryption_ready?++ # A miss must cost one bcrypt digest, like a hit, so response time does+ # not reveal whether an email is registered.+ digest = BCrypt::Password.create("whatever", cost: BCrypt::Engine::MIN_COST)+ BCrypt::Password.expects(:create).once.returns(digest)++ assert_nil User.authenticate_by_email(email: "[email protected]", password: "whatever")+ end++ test "email uniqueness also catches a legacy plaintext row" do+ skip "Encryption not configured" unless User.encryption_ready?++ # Unlike find_by(email:), the uniqueness validator's query is extended to+ # plaintext rows, so an SSO signup or email change cannot duplicate a+ # not-yet-backfilled user.++ user = users(:family_admin)+ ActiveRecord::Base.connection.execute(+ ActiveRecord::Base.sanitize_sql([ "UPDATE users SET email = ? WHERE id = ?", "[email protected]", user.id ])+ )++ duplicate = User.new(email: "[email protected]", family: Family.new, skip_password_validation: true)+ assert_not duplicate.valid?+ assert duplicate.errors.of_kind?(:email, :taken)++ # The legacy user itself can still be saved.+ user.reload.first_name = "Renamed"+ assert user.valid?, user.errors.full_messages.to_sentence+ end++ test "deterministic find_by matches a legacy plaintext row for downcase attributes without a model-level normalizes declaration" do+ skip "Encryption not configured" unless Invitation.encryption_ready? && InviteCode.encryption_ready?++ invitation = invitations(:one)+ ActiveRecord::Base.connection.execute(+ ActiveRecord::Base.sanitize_sql([ "UPDATE invitations SET email = ? WHERE id = ?", "[email protected]", invitation.id ])+ )+ assert_equal invitation, Invitation.find_by(email: "[email protected]")++ invite_code = InviteCode.create!+ ActiveRecord::Base.connection.execute(+ ActiveRecord::Base.sanitize_sql([ "UPDATE invite_codes SET token = ? WHERE id = ?", "legacy-token-xyz", invite_code.id ])+ )+ assert_equal invite_code, InviteCode.find_by(token: "legacy-token-xyz")+ end+test "reads a legacy plaintext jsonb value as its original Hash, not a String" doskip "Encryption not configured" unless SnaptradeAccount.encryption_ready?diff --git a/test/lib/active_record_encryption_config_test.rb b/test/lib/active_record_encryption_config_test.rbindex 1302ed9888..a55c076682 100644--- a/test/lib/active_record_encryption_config_test.rb+++ b/test/lib/active_record_encryption_config_test.rb@@ -1,6 +1,7 @@# frozen_string_literal: truerequire "test_helper"+require "open3"class ActiveRecordEncryptionConfigTest < ActiveSupport::TestCasetest "detects complete encryption environment" do@@ -246,4 +247,100 @@ class ActiveRecordEncryptionConfigTest < ActiveSupport::TestCase)refute ActiveRecordEncryptionConfig.reject_partial_credentials?({}, OpenStruct.new(active_record_encryption: nil))end++ test "derived_keys returns the keys derived from SECRET_KEY_BASE" do+ keys = ActiveRecordEncryptionConfig.derived_keys("old-base")++ assert_equal Digest::SHA256.hexdigest("old-base:primary_key")[0..63], keys[:primary_key]+ assert_equal Digest::SHA256.hexdigest("old-base:deterministic_key")[0..63], keys[:deterministic_key]+ assert_equal Digest::SHA256.hexdigest("old-base:key_derivation_salt")[0..63], keys[:key_derivation_salt]+ end++ test "previous_schemes is empty without a previous SECRET_KEY_BASE" do+ assert_empty ActiveRecordEncryptionConfig.previous_schemes({})+ assert_empty ActiveRecordEncryptionConfig.previous_schemes(ActiveRecordEncryptionConfig::PREVIOUS_SECRET_KEY_BASE_ENV => "")+ end++ test "previous_schemes uses explicitly set old keys" do+ env = {+ "ACTIVE_RECORD_ENCRYPTION_PREVIOUS_PRIMARY_KEY" => "old-primary",+ "ACTIVE_RECORD_ENCRYPTION_PREVIOUS_DETERMINISTIC_KEY" => "old-deterministic",+ "ACTIVE_RECORD_ENCRYPTION_PREVIOUS_KEY_DERIVATION_SALT" => "old-salt"+ }++ assert_equal({ primary_key: "old-primary", deterministic_key: "old-deterministic", key_derivation_salt: "old-salt" },+ ActiveRecordEncryptionConfig.previous_keys(env))+ assert_equal 2, ActiveRecordEncryptionConfig.previous_schemes(env).size+ assert ActiveRecordEncryptionConfig.previous_keys_configured?(env)+ end++ test "previous_keys rejects a partial set of old keys" do+ env = { "ACTIVE_RECORD_ENCRYPTION_PREVIOUS_PRIMARY_KEY" => "old-primary" }++ error = assert_raises(RuntimeError) { ActiveRecordEncryptionConfig.previous_keys(env) }+ assert_includes error.message, "ACTIVE_RECORD_ENCRYPTION_PREVIOUS_KEY_DERIVATION_SALT"+ refute ActiveRecordEncryptionConfig.previous_keys_configured?({})+ end++ # The old salt differs from the configured one, which Rails' own key+ # providers would use.+ test "previous_schemes decrypt data encrypted with keys derived from an old SECRET_KEY_BASE" do+ old_base = SecureRandom.hex(64)+ texts = encrypt_as_derived_from(old_base, "nd-secret", "det-secret")++ schemes = ActiveRecordEncryptionConfig.previous_schemes(ActiveRecordEncryptionConfig::PREVIOUS_SECRET_KEY_BASE_ENV => old_base)+ non_deterministic = schemes.find { |scheme| !scheme[:deterministic] }+ deterministic = schemes.find { |scheme| scheme[:deterministic] }+ encryptor = ActiveRecord::Encryption.encryptor++ assert_equal "nd-secret", encryptor.decrypt(texts[:non_deterministic], key_provider: non_deterministic[:key_provider])+ assert_equal "det-secret", encryptor.decrypt(texts[:deterministic], key_provider: deterministic[:key_provider])+ end++ # Boots the app the way an operator's one-off command does, so the+ # initializer wiring and Rails' merge of global previous schemes into each+ # encrypted attribute are covered.+ test "an old SECRET_KEY_BASE in the environment makes old data readable through the models" do+ old_base = SecureRandom.hex(64)+ texts = encrypt_as_derived_from(old_base, "Ada", "[email protected]")+ script = <<~RUBY+ puts User.type_for_attribute(:first_name).deserialize(ENV.fetch("PROBE_ND"))+ puts User.type_for_attribute(:email).deserialize(ENV.fetch("PROBE_DET"))+ RUBY+ env = {+ ActiveRecordEncryptionConfig::PREVIOUS_SECRET_KEY_BASE_ENV => old_base,+ "PROBE_ND" => texts[:non_deterministic],+ "PROBE_DET" => texts[:deterministic]+ }++ output, status = Open3.capture2e(env, Rails.root.join("bin/rails").to_s, "runner", script, chdir: Rails.root.to_s)++ assert status.success?, output+ assert_equal [ "Ada", "[email protected]" ], output.lines.last(2).map(&:strip)+ end++ private++ # Encrypts like an install whose keys were derived from old_base: Rails'+ # key providers with that install's salt as the configured one. A fresh+ # KeyGenerator reads the salt on first use; the shared one has it cached.+ def encrypt_as_derived_from(old_base, non_deterministic_text, deterministic_text)+ keys = ActiveRecordEncryptionConfig.derived_keys(old_base)+ config = ActiveRecord::Encryption.config+ original_salt = config.key_derivation_salt+ config.key_derivation_salt = keys[:key_derivation_salt]+ non_deterministic = ActiveRecord::Encryption::DerivedSecretKeyProvider.new(+ keys[:primary_key], key_generator: ActiveRecord::Encryption::KeyGenerator.new)+ deterministic = ActiveRecord::Encryption::DerivedSecretKeyProvider.new(+ keys[:deterministic_key], key_generator: ActiveRecord::Encryption::KeyGenerator.new)+ config.key_derivation_salt = original_salt++ encryptor = ActiveRecord::Encryption.encryptor+ {+ non_deterministic: encryptor.encrypt(non_deterministic_text, key_provider: non_deterministic),+ deterministic: encryptor.encrypt(deterministic_text, key_provider: deterministic, cipher_options: { deterministic: true })+ }+ ensure+ config.key_derivation_salt = original_salt+ endenddiff --git a/test/lib/tasks/security_backfill_test.rb b/test/lib/tasks/security_backfill_test.rbindex 1d3280c803..c196619589 100644--- a/test/lib/tasks/security_backfill_test.rb+++ b/test/lib/tasks/security_backfill_test.rb@@ -454,6 +454,36 @@ class SecurityBackfillTest < ActiveSupport::TestCaseendend+ # Rails encrypts deterministic attributes with the oldest configured scheme+ # while `previous` schemes exist. A rotation away from a compromised key+ # must still move them to the current key.+ test "backfill re-encrypts deterministic values under the current key during a rotation" do+ old_key_provider = ActiveRecord::Encryption::DeterministicKeyProvider.new(SecureRandom.hex(32))+ probe_class = Class.new(ApplicationRecord) do+ self.table_name = "invite_codes"+ def self.name = "InviteCodeRotationProbe"+ encrypts :token, deterministic: true, previous: [ { deterministic: true, key_provider: old_key_provider } ]+ end+ current_key_provider = probe_class.type_for_attribute(:token).key_provider+ encryptor = ActiveRecord::Encryption.encryptor++ record = probe_class.create!(token: "rotation-probe-token")+ old_ciphertext = record.read_attribute_before_type_cast(:token)+ assert_equal "rotation-probe-token", encryptor.decrypt(old_ciphertext, key_provider: old_key_provider)+ assert_raises(ActiveRecord::Encryption::Errors::Decryption) do+ encryptor.decrypt(old_ciphertext, key_provider: current_key_provider)+ end++ backfill_model(probe_class.where(id: record.id), %i[token], 500, false)++ new_ciphertext = probe_class.connection.select_value(+ probe_class.where(id: record.id).select(:token).to_sql)+ assert_equal "rotation-probe-token", encryptor.decrypt(new_ciphertext, key_provider: current_key_provider)+ assert_raises(ActiveRecord::Encryption::Errors::Decryption) do+ encryptor.decrypt(new_ciphertext, key_provider: old_key_provider)+ end+ end+privatedef encrypted_models_for_backfilldiff --git a/test/lib/tasks/security_setting_secrets_test.rb b/test/lib/tasks/security_setting_secrets_test.rbnew file mode 100644index 0000000000..8a59051a0a--- /dev/null+++ b/test/lib/tasks/security_setting_secrets_test.rb@@ -0,0 +1,92 @@+# frozen_string_literal: true++require "test_helper"+require "rake"++class SecuritySettingSecretsTaskTest < ActiveSupport::TestCase+ OLD_SECRET_KEY_BASE = "old-secret-key-base-#{"e" * 64}"++ setup do+ Rails.application.load_tasks unless Rake::Task.task_defined?("security:rotate_setting_secrets")+ @task = Rake::Task["security:rotate_setting_secrets"]+ @task.reenable+ end++ teardown do+ Setting.openai_access_token = nil+ end++ test "re-encrypts settings saved under the old SECRET_KEY_BASE" do+ store_with_old_key("openai_access_token", "sk-old-key")++ output = with_env_overrides("OLD_SECRET_KEY_BASE" => OLD_SECRET_KEY_BASE) do+ capture_io { @task.invoke("0") }.first+ end++ result = JSON.parse(output.lines.last)+ assert result["ok"]+ assert_equal false, result["dry_run"]+ assert_equal "reencrypted", result["results"]["openai_access_token"]+ assert_equal "sk-old-key", Setting.openai_access_token+ end++ test "defaults to a dry run" do+ store_with_old_key("openai_access_token", "sk-old-key")++ output = with_env_overrides("OLD_SECRET_KEY_BASE" => OLD_SECRET_KEY_BASE) do+ capture_io { @task.invoke }.first+ end++ result = JSON.parse(output.lines.last)+ assert result["dry_run"]+ assert_equal "would_reencrypt", result["results"]["openai_access_token"]+ assert_not_equal "sk-old-key", Setting.openai_access_token+ end++ test "refuses to run without OLD_SECRET_KEY_BASE" do+ output = with_env_overrides("OLD_SECRET_KEY_BASE" => nil) do+ capture_io { assert_raises(SystemExit) { @task.invoke("0") } }.first+ end++ assert_equal "old_secret_key_base_missing", JSON.parse(output.lines.last)["error"]+ end++ test "refuses to run while SECRET_KEY_BASE is unchanged" do+ output = with_env_overrides("OLD_SECRET_KEY_BASE" => Rails.application.secret_key_base) do+ capture_io { assert_raises(SystemExit) { @task.invoke("0") } }.first+ end++ assert_equal "secret_key_base_unchanged", JSON.parse(output.lines.last)["error"]+ end++ test "fails when nothing decrypts with OLD_SECRET_KEY_BASE" do+ store_with_old_key("openai_access_token", "sk-old-key")++ output = with_env_overrides("OLD_SECRET_KEY_BASE" => "mistyped-#{OLD_SECRET_KEY_BASE}") do+ capture_io { assert_raises(SystemExit) { @task.invoke("0") } }.first+ end++ result = JSON.parse(output.lines.last)+ assert_equal "old_secret_key_base_did_not_match", result["error"]+ assert_equal [ "openai_access_token" ], result["not_decryptable"]+ end++ test "ignores surrounding whitespace in OLD_SECRET_KEY_BASE" do+ store_with_old_key("openai_access_token", "sk-old-key")++ with_env_overrides("OLD_SECRET_KEY_BASE" => " #{OLD_SECRET_KEY_BASE}\n") do+ capture_io { @task.invoke("0") }+ end++ assert_equal "sk-old-key", Setting.openai_access_token+ end++ private++ def store_with_old_key(var, plaintext)+ key = ActiveSupport::KeyGenerator.new(OLD_SECRET_KEY_BASE).generate_key("setting_encryption", 32)+ ciphertext = ActiveSupport::MessageEncryptor.new(key).encrypt_and_sign(plaintext)+ Setting.find_or_initialize_by(var: var).update!(value: ciphertext)+ Setting.clear_cache+ end+enddiff --git a/test/models/binance_item_test.rb b/test/models/binance_item_test.rbindex e4dc031669..3195a27fbf 100644--- a/test/models/binance_item_test.rb+++ b/test/models/binance_item_test.rb@@ -112,7 +112,7 @@ class BinanceItemTest < ActiveSupport::TestCasetest "declares credentials and raw payload as encrypted" doskip "Encryption not configured" unless BinanceItem.encryption_ready?- encrypted = BinanceItem.encrypted_attributes.map(&:to_s)+ encrypted = Array(BinanceItem.encrypted_attributes).map(&:to_s)assert_includes encrypted, "api_key"assert_includes encrypted, "api_secret"assert_includes encrypted, "raw_payload"diff --git a/test/models/brex_account_test.rb b/test/models/brex_account_test.rbindex 6d0d60769a..4dca4c784e 100644--- a/test/models/brex_account_test.rb+++ b/test/models/brex_account_test.rb@@ -47,7 +47,7 @@ class BrexAccountTest < ActiveSupport::TestCasetest "declares raw Brex payloads as encrypted" doskip "Encryption not configured" unless BrexAccount.encryption_ready?- encrypted_attributes = BrexAccount.encrypted_attributes.map(&:to_s)+ encrypted_attributes = Array(BrexAccount.encrypted_attributes).map(&:to_s)assert_includes encrypted_attributes, "raw_payload"assert_includes encrypted_attributes, "raw_transactions_payload"diff --git a/test/models/brex_item_test.rb b/test/models/brex_item_test.rbindex cc850d1fe6..22c2656393 100644--- a/test/models/brex_item_test.rb+++ b/test/models/brex_item_test.rb@@ -104,7 +104,7 @@ class BrexItemTest < ActiveSupport::TestCasetest "declares Brex token and raw payload as encrypted" doskip "Encryption not configured" unless BrexItem.encryption_ready?- encrypted = BrexItem.encrypted_attributes.map(&:to_s)+ encrypted = Array(BrexItem.encrypted_attributes).map(&:to_s)assert_includes encrypted, "token"assert_includes encrypted, "raw_payload"assert_includes encrypted, "raw_institution_payload"diff --git a/test/models/coinbase_item_test.rb b/test/models/coinbase_item_test.rbindex 83bbd3eb42..a2343bfdbd 100644--- a/test/models/coinbase_item_test.rb+++ b/test/models/coinbase_item_test.rb@@ -228,7 +228,7 @@ class CoinbaseItemTest < ActiveSupport::TestCasetest "declares credentials and raw payloads as encrypted" doskip "Encryption not configured" unless CoinbaseItem.encryption_ready?- encrypted = CoinbaseItem.encrypted_attributes.map(&:to_s)+ encrypted = Array(CoinbaseItem.encrypted_attributes).map(&:to_s)assert_includes encrypted, "api_key"assert_includes encrypted, "api_secret"assert_includes encrypted, "raw_payload"diff --git a/test/models/coinstats_item_test.rb b/test/models/coinstats_item_test.rbindex 502e7fe162..95a24c9e20 100644--- a/test/models/coinstats_item_test.rb+++ b/test/models/coinstats_item_test.rb@@ -232,7 +232,7 @@ class CoinstatsItemTest < ActiveSupport::TestCasetest "declares api_key and raw payloads as encrypted" doskip "Encryption not configured" unless CoinstatsItem.encryption_ready?- encrypted = CoinstatsItem.encrypted_attributes.map(&:to_s)+ encrypted = Array(CoinstatsItem.encrypted_attributes).map(&:to_s)assert_includes encrypted, "api_key"assert_includes encrypted, "raw_payload"assert_includes encrypted, "raw_institution_payload"diff --git a/test/models/indexa_capital_account_test.rb b/test/models/indexa_capital_account_test.rbindex ac8bcf60bc..3b5684cfa2 100644--- a/test/models/indexa_capital_account_test.rb+++ b/test/models/indexa_capital_account_test.rb@@ -127,7 +127,7 @@ class IndexaCapitalAccountTest < ActiveSupport::TestCasetest "declares raw payloads as encrypted" doskip "Encryption not configured" unless IndexaCapitalAccount.encryption_ready?- encrypted = IndexaCapitalAccount.encrypted_attributes.map(&:to_s)+ encrypted = Array(IndexaCapitalAccount.encrypted_attributes).map(&:to_s)assert_includes encrypted, "raw_payload"assert_includes encrypted, "raw_holdings_payload"assert_includes encrypted, "raw_activities_payload"diff --git a/test/models/indexa_capital_item_test.rb b/test/models/indexa_capital_item_test.rbindex b075e4f135..39cb0f7ba7 100644--- a/test/models/indexa_capital_item_test.rb+++ b/test/models/indexa_capital_item_test.rb@@ -144,7 +144,7 @@ class IndexaCapitalItemTest < ActiveSupport::TestCasetest "declares credentials and raw payloads as encrypted" doskip "Encryption not configured" unless IndexaCapitalItem.encryption_ready?- encrypted = IndexaCapitalItem.encrypted_attributes.map(&:to_s)+ encrypted = Array(IndexaCapitalItem.encrypted_attributes).map(&:to_s)assert_includes encrypted, "password"assert_includes encrypted, "api_token"assert_includes encrypted, "username"diff --git a/test/models/mercury_item_test.rb b/test/models/mercury_item_test.rbindex 728b7b54b6..494e95dac8 100644--- a/test/models/mercury_item_test.rb+++ b/test/models/mercury_item_test.rb@@ -91,7 +91,7 @@ class MercuryItemTest < ActiveSupport::TestCasetest "declares token and raw payloads as encrypted" doskip "Encryption not configured" unless MercuryItem.encryption_ready?- encrypted = MercuryItem.encrypted_attributes.map(&:to_s)+ encrypted = Array(MercuryItem.encrypted_attributes).map(&:to_s)assert_includes encrypted, "token"assert_includes encrypted, "raw_payload"assert_includes encrypted, "raw_institution_payload"diff --git a/test/models/onchain_wallet_account_test.rb b/test/models/onchain_wallet_account_test.rbindex db5c54fedf..562de5ea54 100644--- a/test/models/onchain_wallet_account_test.rb+++ b/test/models/onchain_wallet_account_test.rb@@ -224,7 +224,7 @@ class OnchainWalletAccountTest < ActiveSupport::TestCasetest "declares raw payloads as encrypted" doskip "Encryption not configured" unless OnchainWalletAccount.encryption_ready?- encrypted = OnchainWalletAccount.encrypted_attributes.map(&:to_s)+ encrypted = Array(OnchainWalletAccount.encrypted_attributes).map(&:to_s)assert_includes encrypted, "raw_payload"assert_includes encrypted, "raw_movements_payload"enddiff --git a/test/models/setting_test.rb b/test/models/setting_test.rbindex aa29496a02..c329d8c903 100644--- a/test/models/setting_test.rb+++ b/test/models/setting_test.rb@@ -205,4 +205,66 @@ class SettingTest < ActiveSupport::TestCaseSetting.securities_providers = original_providers.presence || ""Setting.securities_provider = original_provider.presence || "twelve_data"end++ test "reencrypt_secrets_from moves values from the old key to the current key" do+ old_secret_key_base = "old-secret-key-base-" + "a" * 64+ store_raw_setting("openai_access_token", old_setting_encryptor(old_secret_key_base).encrypt_and_sign("sk-old-key"))++ assert_not_equal "sk-old-key", Setting.openai_access_token++ results = Setting.reencrypt_secrets_from(old_secret_key_base, dry_run: false)++ assert_equal :reencrypted, results[:openai_access_token]+ assert_equal "sk-old-key", Setting.openai_access_token+ assert_not_equal "sk-old-key", Setting.find_by(var: "openai_access_token").value+ ensure+ Setting.openai_access_token = nil+ end++ test "reencrypt_secrets_from dry run reports without writing" do+ old_secret_key_base = "old-secret-key-base-" + "b" * 64+ ciphertext = old_setting_encryptor(old_secret_key_base).encrypt_and_sign("sk-old-key")+ store_raw_setting("openai_access_token", ciphertext)++ results = Setting.reencrypt_secrets_from(old_secret_key_base)++ assert_equal :would_reencrypt, results[:openai_access_token]+ assert_equal ciphertext, Setting.find_by(var: "openai_access_token").value+ ensure+ Setting.openai_access_token = nil+ end++ test "reencrypt_secrets_from leaves current and undecryptable values alone" do+ Setting.where(var: "twelve_data_api_key").delete_all+ Setting.openai_access_token = "sk-current"+ other_ciphertext = old_setting_encryptor("unrelated-" + "c" * 64).encrypt_and_sign("sk-lost")+ store_raw_setting("anthropic_access_token", other_ciphertext)++ results = Setting.reencrypt_secrets_from("old-secret-key-base-" + "d" * 64, dry_run: false)++ assert_equal :current, results[:openai_access_token]+ assert_equal :not_decryptable, results[:anthropic_access_token]+ assert_equal "sk-current", Setting.openai_access_token+ assert_equal other_ciphertext, Setting.find_by(var: "anthropic_access_token").value+ assert_equal :not_stored, results[:twelve_data_api_key]+ ensure+ Setting.openai_access_token = nil+ Setting.anthropic_access_token = nil+ end++ test "reencrypt_secrets_from rejects a blank old key" do+ assert_raises(ArgumentError) { Setting.reencrypt_secrets_from("") }+ end++ private++ def old_setting_encryptor(secret_key_base)+ key = ActiveSupport::KeyGenerator.new(secret_key_base).generate_key("setting_encryption", 32)+ ActiveSupport::MessageEncryptor.new(key)+ end++ def store_raw_setting(var, value)+ Setting.find_or_initialize_by(var: var).update!(value: value)+ Setting.clear_cache+ endenddiff --git a/test/models/snaptrade_item_test.rb b/test/models/snaptrade_item_test.rbindex 6eff0d0a3f..6f39ec2008 100644--- a/test/models/snaptrade_item_test.rb+++ b/test/models/snaptrade_item_test.rb@@ -65,7 +65,7 @@ class SnaptradeItemTest < ActiveSupport::TestCasetest "declares OAuth credential fields as encrypted" doskip "Encryption not configured" unless SnaptradeItem.encryption_ready?- encrypted = SnaptradeItem.encrypted_attributes.map(&:to_s)+ encrypted = Array(SnaptradeItem.encrypted_attributes).map(&:to_s)assert_includes encrypted, "client_id"assert_includes encrypted, "consumer_key"assert_includes encrypted, "snaptrade_user_secret"diff --git a/test/models/sophtron_account_test.rb b/test/models/sophtron_account_test.rbindex 2a49832f63..87822314bd 100644--- a/test/models/sophtron_account_test.rb+++ b/test/models/sophtron_account_test.rb@@ -27,7 +27,7 @@ class SophtronAccountTest < ActiveSupport::TestCasetest "declares raw payloads as encrypted" doskip "Encryption not configured" unless SophtronAccount.encryption_ready?- encrypted = SophtronAccount.encrypted_attributes.map(&:to_s)+ encrypted = Array(SophtronAccount.encrypted_attributes).map(&:to_s)assert_includes encrypted, "raw_payload"assert_includes encrypted, "raw_transactions_payload"enddiff --git a/test/models/sophtron_item_test.rb b/test/models/sophtron_item_test.rbindex de0114e1e8..e42ddb95ca 100644--- a/test/models/sophtron_item_test.rb+++ b/test/models/sophtron_item_test.rb@@ -219,7 +219,7 @@ class SophtronItemTest < ActiveSupport::TestCasetest "declares credentials and raw payloads as encrypted" doskip "Encryption not configured" unless SophtronItem.encryption_ready?- encrypted = SophtronItem.encrypted_attributes.map(&:to_s)+ encrypted = Array(SophtronItem.encrypted_attributes).map(&:to_s)assert_includes encrypted, "user_id"assert_includes encrypted, "access_key"assert_includes encrypted, "raw_payload"