The personal finance app for everyone (by everyone)
Ruby
fix(security): use ready? instead of explicitly_configured? for encryption gating (#3189)
GFRce7e26a3debd
diff --git a/app/controllers/api/v1/auth_controller.rb b/app/controllers/api/v1/auth_controller.rbindex 997ed1c03a..b860d07885 100644--- a/app/controllers/api/v1/auth_controller.rb+++ b/app/controllers/api/v1/auth_controller.rb@@ -84,7 +84,7 @@ module Apienddef login- user = User.find_by(email: params[:email])+ user = User.find_by_email_with_legacy_fallback(params[:email])unless local_login_permitted_for?(user)render json: { error: "Local login is disabled. Please use SSO." }, status: :forbidden@@ -213,7 +213,7 @@ module Apicached = validate_linking_code(linking_code)return unless cached- user = User.authenticate_by(email: params[:email], password: params[:password])+ user = User.authenticate_by_email(email: params[:email], password: params[:password])unless userrender json: { error: "Invalid email or password" }, status: :unauthorizeddiff --git a/app/controllers/mcp_controller.rb b/app/controllers/mcp_controller.rbindex 4591a6a9ca..e89dd7f276 100644--- a/app/controllers/mcp_controller.rb+++ b/app/controllers/mcp_controller.rb@@ -154,7 +154,7 @@ class McpController < ApplicationControllerOpenSSL::Digest::SHA256.hexdigest(expected))- user = User.find_by(email: ENV["MCP_USER_EMAIL"])+ user = User.find_by_email_with_legacy_fallback(ENV["MCP_USER_EMAIL"])unless userRails.logger.warn "[MCP] MCP_USER_EMAIL does not match any user — check environment configuration"diff --git a/app/controllers/oidc_accounts_controller.rb b/app/controllers/oidc_accounts_controller.rbindex 33edcce15c..ca5c784308 100644--- a/app/controllers/oidc_accounts_controller.rb+++ b/app/controllers/oidc_accounts_controller.rb@@ -14,7 +14,7 @@ class OidcAccountsController < ApplicationControllerend@email = @pending_auth["email"]- @user_exists = User.exists?(email: @email) if @email.present?+ @user_exists = User.find_by_email_with_legacy_fallback(@email).present? if @email.present?# Check for a pending invitation for this email@pending_invitation = Invitation.pending.find_by(email: @email) if @email.present?@@ -33,7 +33,7 @@ class OidcAccountsController < ApplicationControllerend# Verify user's password to confirm identity- user = User.authenticate_by(email: params[:email], password: params[:password])+ user = User.authenticate_by_email(email: params[:email], password: params[:password])if user&.active?linked = user.transaction do@@ -72,7 +72,7 @@ class OidcAccountsController < ApplicationControllerendelse@email = params[:email]- @user_exists = User.exists?(email: @email) if @email.present?+ @user_exists = User.find_by_email_with_legacy_fallback(@email).present? if @email.present?flash.now[:alert] = "Invalid email or password"render :link, status: :unprocessable_entityenddiff --git a/app/controllers/password_resets_controller.rb b/app/controllers/password_resets_controller.rbindex 13f8d52e28..618a795966 100644--- a/app/controllers/password_resets_controller.rb+++ b/app/controllers/password_resets_controller.rb@@ -10,7 +10,7 @@ class PasswordResetsController < ApplicationControllerenddef create- if (user = User.find_by(email: params[:email]))+ if (user = User.find_by_email_with_legacy_fallback(params[:email]))# Security: Block password reset for SSO-only users.# These users have no local password and must authenticate via SSO.unless user.sso_only?diff --git a/app/controllers/sessions_controller.rb b/app/controllers/sessions_controller.rbindex 925fd8da30..8440cc8f92 100644--- a/app/controllers/sessions_controller.rb+++ b/app/controllers/sessions_controller.rb@@ -45,18 +45,18 @@ class SessionsController < ApplicationControlleruser = nilif AuthConfig.local_login_enabled?- user = User.authenticate_by(email: params[:email], password: params[:password])+ user = User.authenticate_by_email(email: params[:email], password: params[:password])else# Local login is disabled. Only allow attempts when an emergency super-admin# override is enabled and the email belongs to a super-admin.if AuthConfig.local_admin_override_enabled?- candidate = User.find_by(email: params[:email])+ candidate = User.find_by_email_with_legacy_fallback(params[:email])unless candidate&.super_admin?redirect_to new_session_path, alert: t("sessions.create.local_login_disabled")returnend- user = User.authenticate_by(email: params[:email], password: params[:password])+ user = User.authenticate_by_email(email: params[:email], password: params[:password])elseredirect_to new_session_path, alert: t("sessions.create.local_login_disabled")returndiff --git a/app/controllers/settings/providers_controller.rb b/app/controllers/settings/providers_controller.rbindex fa27c7fd49..ea29819322 100644--- a/app/controllers/settings/providers_controller.rb+++ b/app/controllers/settings/providers_controller.rb@@ -171,7 +171,7 @@ class Settings::ProvidersController < ApplicationControllerdef set_encryption_warning_context@provider_setup_encryption_warning = Rails.configuration.app_mode.self_hosted? &&- !ActiveRecordEncryptionConfig.explicitly_configured?+ !ActiveRecordEncryptionConfig.ready?end# Reload provider configurations after settings updatediff --git a/app/controllers/settings/securities_controller.rb b/app/controllers/settings/securities_controller.rbindex 6d32a07858..5c1f2c5903 100644--- a/app/controllers/settings/securities_controller.rb+++ b/app/controllers/settings/securities_controller.rb@@ -9,6 +9,6 @@ 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.explicitly_configured?+ !ActiveRecordEncryptionConfig.ready?endenddiff --git a/app/jobs/demo_family_refresh_job.rb b/app/jobs/demo_family_refresh_job.rbindex 92cf97e26c..e5fef2f220 100644--- a/app/jobs/demo_family_refresh_job.rb+++ b/app/jobs/demo_family_refresh_job.rb@@ -16,7 +16,7 @@ class DemoFamilyRefreshJob < ApplicationJobperiod_start = period_end - 24.hoursdemo_email = Rails.application.config_for(:demo).with_indifferent_access.fetch(:email)- demo_user = User.find_by(email: demo_email)+ demo_user = User.find_by_email_with_legacy_fallback(demo_email)old_family = demo_user&.familyif Rails.application.config.app_mode.self_hosted?@@ -42,7 +42,8 @@ class DemoFamilyRefreshJob < ApplicationJobDemo::Generator.new.generate_default_data!(skip_clear: true, email: demo_email)if Rails.application.config.app_mode.self_hosted?- new_family = User.find_by!(email: demo_email).family+ new_user = User.find_by_email_with_legacy_fallback(demo_email) || raise(ActiveRecord::RecordNotFound, "Demo user missing after regeneration")+ new_family = new_user.familySetting.demo_family_refresh_family_id = new_family.id.to_sretire_old_family!(old_family) if old_familyenddiff --git a/app/models/coinstats_item.rb b/app/models/coinstats_item.rbindex f22c420708..6dfaee1410 100644--- a/app/models/coinstats_item.rb+++ b/app/models/coinstats_item.rb@@ -1,20 +1,10 @@# Represents a CoinStats API connection for a family.# Stores credentials and manages associated wallet and exchange portfolio accounts.class CoinstatsItem < ApplicationRecord- include Syncable, Provided, Unlinking, DestroyableLater+ include Syncable, Provided, Unlinking, Encryptable, DestroyableLaterenum :status, { good: "good", requires_update: "requires_update" }, default: :good- # Checks if ActiveRecord Encryption is properly configured.- # @return [Boolean] true if encryption keys are available- def self.encryption_ready?- creds_ready = Rails.application.credentials.active_record_encryption.present?- env_ready = ENV["ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY"].present? &&- ENV["ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY"].present? &&- ENV["ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT"].present?- creds_ready || env_ready- end-# Encrypt sensitive credentials if ActiveRecord encryption is configuredencrypts :api_key, deterministic: true if encryption_ready?diff --git a/app/models/concerns/encryptable.rb b/app/models/concerns/encryptable.rbindex a04c773def..2f0c7162d9 100644--- a/app/models/concerns/encryptable.rb+++ b/app/models/concerns/encryptable.rb@@ -5,8 +5,13 @@ module Encryptable# Helper to detect if ActiveRecord Encryption is configured for this app.# This allows encryption to be optional - if not configured, sensitive fields# are stored in plaintext (useful for development or legacy deployments).+ #+ # Uses ready? (not explicitly_configured?) so self-hosted installs relying+ # on the documented SECRET_KEY_BASE auto-generation fallback are correctly+ # recognized as encrypted, instead of silently skipping every `encrypts`+ # declaration that guards on this method.def encryption_ready?- ActiveRecordEncryptionConfig.explicitly_configured?+ ActiveRecordEncryptionConfig.ready?endendenddiff --git a/app/models/indexa_capital_item.rb b/app/models/indexa_capital_item.rbindex 698c7d251e..cb415962dd 100644--- a/app/models/indexa_capital_item.rb+++ b/app/models/indexa_capital_item.rb@@ -1,19 +1,10 @@# frozen_string_literal: trueclass IndexaCapitalItem < ApplicationRecord- include Syncable, Provided, Unlinking, DestroyableLater+ include Syncable, Provided, Unlinking, Encryptable, DestroyableLaterenum :status, { good: "good", requires_update: "requires_update" }, default: :good- # Helper to detect if ActiveRecord Encryption is configured for this app- def self.encryption_ready?- creds_ready = Rails.application.credentials.active_record_encryption.present?- env_ready = ENV["ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY"].present? &&- ENV["ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY"].present? &&- ENV["ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT"].present?- creds_ready || env_ready- end-# Encrypt sensitive credentials if ActiveRecord encryption is configuredif encryption_ready?encrypts :password, deterministic: truediff --git a/app/models/mercury_item.rb b/app/models/mercury_item.rbindex ed3b5ba306..b4c4ed0a5e 100644--- a/app/models/mercury_item.rb+++ b/app/models/mercury_item.rb@@ -1,17 +1,8 @@class MercuryItem < ApplicationRecord- include Syncable, Provided, Unlinking, DestroyableLater+ include Syncable, Provided, Unlinking, Encryptable, DestroyableLaterenum :status, { good: "good", requires_update: "requires_update" }, default: :good- # Helper to detect if ActiveRecord Encryption is configured for this app- def self.encryption_ready?- creds_ready = Rails.application.credentials.active_record_encryption.present?- env_ready = ENV["ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY"].present? &&- ENV["ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY"].present? &&- ENV["ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT"].present?- creds_ready || env_ready- end-# Encrypt sensitive credentials if ActiveRecord encryption is configuredif encryption_ready?encrypts :token, deterministic: truediff --git a/app/models/snaptrade_item.rb b/app/models/snaptrade_item.rbindex 2d5539834a..3b76f240a3 100644--- a/app/models/snaptrade_item.rb+++ b/app/models/snaptrade_item.rb@@ -1,17 +1,8 @@class SnaptradeItem < ApplicationRecord- include Syncable, Provided, Unlinking, DestroyableLater+ include Syncable, Provided, Unlinking, Encryptable, DestroyableLaterenum :status, { good: "good", requires_update: "requires_update" }, default: :good- # Helper to detect if ActiveRecord Encryption is configured for this app- def self.encryption_ready?- creds_ready = Rails.application.credentials.active_record_encryption.present?- env_ready = ENV["ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY"].present? &&- ENV["ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY"].present? &&- ENV["ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT"].present?- creds_ready || env_ready- end-# Encrypt sensitive credentials if ActiveRecord encryption is configured# client_id/consumer_key use deterministic encryption (may need querying)# snaptrade_user_secret uses non-deterministic (more secure for pure secrets)diff --git a/app/models/sophtron_item.rb b/app/models/sophtron_item.rbindex 12bd33c763..c84d03890f 100644--- a/app/models/sophtron_item.rb+++ b/app/models/sophtron_item.rb@@ -12,26 +12,13 @@# @attr [Boolean] scheduled_for_deletion Whether the item is scheduled for deletion# @attr [DateTime] last_synced_at When the last successful sync occurredclass SophtronItem < ApplicationRecord- include Syncable, Provided, Unlinking, DestroyableLater+ include Syncable, Provided, Unlinking, Encryptable, DestroyableLaterINITIAL_LOAD_LOOKBACK_DAYS = 120MAX_TRANSACTION_HISTORY_YEARS = 3enum :status, { good: "good", requires_update: "requires_update" }, default: :good- # Helper to detect if ActiveRecord Encryption is configured for this app.- #- # Checks both Rails credentials and environment variables for encryption keys.- #- # @return [Boolean] true if encryption is properly configured- def self.encryption_ready?- creds_ready = Rails.application.credentials.active_record_encryption.present?- env_ready = ENV["ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY"].present? &&- ENV["ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY"].present? &&- ENV["ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT"].present?- creds_ready || env_ready- end-# Encrypt sensitive credentials if ActiveRecord encryption is configured (credentials OR env vars)if encryption_ready?encrypts :user_id, deterministic: truediff --git a/app/models/user.rb b/app/models/user.rbindex 7670c48042..1103e22096 100644--- a/app/models/user.rb+++ b/app/models/user.rb@@ -98,6 +98,43 @@ class User < ApplicationRecordUser.exists? ? fallback_role : :super_adminend+ # Deterministic lookups like `find_by(email:)` and `authenticate_by` miss+ # rows whose email is still legacy plaintext (stored before encryption was+ # active and not yet re-encrypted by `bin/rails security:backfill_encryption`):+ # extend_queries does not cover attributes that also use `normalizes`. The+ # fallback matches those rows by their literal column value.+ def self.find_by_email_with_legacy_fallback(email)+ normalized = email.to_s.strip.downcase+ return nil if normalized.blank?++ find_by(email: normalized) || find_by_legacy_plaintext_email(normalized)+ end++ # Takes the legacy path only for a plaintext row; every other case goes+ # through authenticate_by, which stays timing-safe for wrong passwords and+ # 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.+ def self.authenticate_by_email(email:, password:)+ return nil if password.nil? || password.empty?++ normalized = email.to_s.strip.downcase+ legacy_user = find_by_legacy_plaintext_email(normalized)+ return authenticate_by(email: normalized, password: password) unless legacy_user++ legacy_user if legacy_user.authenticate(password)+ end++ # Legacy rows were always stored normalized (`normalizes :email` predates+ # encryption), so an exact match uses the unique index. Only well-formed+ # emails are looked up, so a pasted ciphertext can never match its own row.+ def self.find_by_legacy_plaintext_email(normalized_email)+ return nil unless normalized_email.match?(URI::MailTo::EMAIL_REGEXP)++ find_by([ "email = ?", normalized_email ])+ end+ private_class_method :find_by_legacy_plaintext_email+class << selfdef human_attribute_name(attribute, options = {})locale = options[:locale] || I18n.localediff --git a/config/initializers/active_record_encryption.rb b/config/initializers/active_record_encryption.rbindex 35e6b865f7..ae0a7dd81b 100644--- a/config/initializers/active_record_encryption.rb+++ b/config/initializers/active_record_encryption.rb@@ -1,5 +1,80 @@require Rails.root.join("lib/active_record_encryption_config").to_s+# Until every existing row has been re-encrypted (see+# `bin/rails security:backfill_encryption`), plenty of installs still have+# genuinely plaintext data in columns that `encryption_ready?` now treats as+# encrypted (see #3142). Without these two settings, Rails raises+# ActiveRecord::Encryption::Errors::Decryption the moment any of that legacy+# data is read (e.g. an admin's or a self-hosted user's own email at login,+# via User#email's deterministic encryption) and deterministic lookups like+# `User.find_by(email:)` stop matching not-yet-backfilled rows entirely.+# Both default to false upstream and are meant exactly for this transition+# period; see https://guides.rubyonrails.org/active_record_encryption.html.+Rails.application.config.active_record.encryption.support_unencrypted_data = true+Rails.application.config.active_record.encryption.extend_queries = true++# KNOWN LIMITATION: extend_queries does not reliably extend deterministic+# lookups to match legacy plaintext data for attributes that combine+# `encrypts ..., deterministic: true, downcase: true` with a model-level+# `normalizes` declaration on the same attribute - which is exactly+# User#email and User#unconfirmed_email (see app/models/user.rb's+# `normalizes :email, with: ->(email) { email.strip.downcase }`).+# Invitation#email and InviteCode#token normalize in a before_validation+# callback instead and are not affected. Arel::Nodes::HomogeneousIn#casted_values calls+# #serialize on the *outermost* ActiveModel::Attributes::Normalization::+# NormalizedValueType wrapper, whose #cast runs the normalization proc+# directly on each query value - including extend_queries' internal+# AdditionalValue wrapper for the clean-text fallback, which doesn't+# respond to #strip. In production this makes `User.find_by(email:)`+# silently fail to match not-yet-backfilled legacy rows instead of raising+# (support_unencrypted_data still makes plain *reads* of already-loaded+# records work). Fixing this generically would mean patching the shared+# ActiveModel normalization type, which is used for unrelated attributes+# across the app - too invasive for this fix. Instead, the user-facing email+# lookups (web and API login, SSO linking, password reset, MCP, demo+# refresh) go through User.find_by_email_with_legacy_fallback and+# User.authenticate_by_email, which fall back to a literal match for legacy+# plaintext rows, so existing+# users can still sign in after upgrading. Operators should still run+# `bin/rails security:backfill_encryption`: other `User.find_by(email:)`+# callers (dev rake tasks, demo generator) do not have the fallback.+# Non-downcase deterministic fields (tokens, API keys,+# ...) are unaffected - confirmed in+# test/initializers/active_record_encryption_test.rb.++if Rails.env.test?+ # Rails' fixture-time attribute encryption (encrypt_fixtures, set in+ # config/environments/test.rb) replaces a fixture's clean value with an+ # already-serialized ciphertext String. For jsonb/json columns, the+ # fixture loader's own column type-casting then serializes *that string*+ # again on insert, double-JSON-encoding it — the same failure mode as+ # rails/rails#48601 (encrypted fixtures + a non-string column type). The+ # result fails to decrypt and, thanks to support_unencrypted_data above,+ # falls back to the still-double-encoded String instead of the original+ # Hash/Array, breaking every consumer of the payload (e.g. `.to_h`).+ #+ # String-column fixtures (tokens, api keys, email, ...) round-trip fine+ # through encrypt_fixtures and keep exercising real encrypt/decrypt in+ # tests; only json/jsonb-typed attributes are exempted here, so their+ # fixtures load as plain values — read back correctly via+ # support_unencrypted_data, exactly like not-yet-backfilled legacy data.+ Rails.application.config.after_initialize do+ ActiveRecord::Encryption::EncryptedFixtures.module_eval do+ def encrypt_fixture_data(fixture, model_class)+ model_class&.encrypted_attributes&.each do |attribute_name|+ next unless (clean_value = fixture[attribute_name.to_s])++ type = model_class.type_for_attribute(attribute_name)+ next if type.cast_type.is_a?(ActiveRecord::Type::Json)++ @clean_values[attribute_name.to_s] = clean_value+ fixture[attribute_name.to_s] = type.serialize(clean_value)+ end+ end+ end+ end+end+# Configure Active Record encryption keys# Priority order:# 1. Environment variables (works for both managed and self-hosted modes)@@ -15,6 +90,19 @@ if ActiveRecordEncryptionConfig.partial_env?raise ActiveRecordEncryptionConfig.partial_env_messageend+# A present-but-incomplete credentials.active_record_encryption block does+# NOT fall through to auto-generation below (see the elsif's `.present?`+# guard) - without this check it would silently disable encryption entirely+# instead of failing loudly, unlike the equivalent partial-ENV case above.+# Skipped when the ENV configuration is complete: ENV keys take priority+# over credentials, so a stale/incomplete credentials block must not stop+# such an installation from booting - the complete-ENV branch below applies+# and the credentials block is ignored (jjmata's review on #3189; covered in+# test/lib/active_record_encryption_config_test.rb).+if ActiveRecordEncryptionConfig.reject_partial_credentials?+ raise ActiveRecordEncryptionConfig.partial_credentials_message+end+# If all environment variables are present, use them (works for both managed and self-hosted)if ActiveRecordEncryptionConfig.complete_env?Rails.application.config.active_record.encryption.primary_key = primary_keydiff --git a/config/initializers/encryption_warning.rb b/config/initializers/encryption_warning.rbindex 31d19b4aaa..d6cc8afd8e 100644--- a/config/initializers/encryption_warning.rb+++ b/config/initializers/encryption_warning.rb@@ -7,15 +7,96 @@ require Rails.root.join("lib/active_record_encryption_config").to_sRails.application.config.after_initialize doapp_mode = Rails.application.config.app_mode- if app_mode.self_hosted? && !ActiveRecordEncryptionConfig.explicitly_configured?- Rails.logger.warn(<<~WARN)- [SECURITY] ActiveRecord Encryption is NOT configured. Sensitive data- (API keys, provider/bank tokens, MFA secrets, and PII) are being stored- UNENCRYPTED at rest. To enable encryption, set the following keys in your Rails credentials or environment variables:- ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY- ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY- ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT- Generate a set with: bin/rails db:encryption:init- WARN++ # Scoped to self-hosted only: this warning is about AR encryption not+ # being configured, which is only ever this app's own responsibility to+ # set up on a self-hosted install (managed instances are operated by the+ # Sure team with their own credential provisioning).+ if app_mode.self_hosted?+ if !ActiveRecordEncryptionConfig.ready?+ Rails.logger.warn(<<~WARN)+ [SECURITY] ActiveRecord Encryption is NOT configured. Sensitive data+ (API keys, provider/bank tokens, MFA secrets, and PII) are being stored+ UNENCRYPTED at rest. To enable encryption, set the following keys in your Rails credentials or environment variables:+ ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY+ ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY+ ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT+ Generate a set with: bin/rails db:encryption:init+ WARN+ end+ end++ # Deliberately NOT nested inside the `if app_mode.self_hosted?` block+ # above (a prior version of this file gated the whole `after_initialize`+ # body on a single `next unless app_mode.self_hosted?`, which silently+ # suppressed this check in managed mode too - jjmata caught this on+ # #3221's version of this same file): using_known_compromised_secret_key_base?+ # is a fact about SECRET_KEY_BASE itself (session cookies, Setting's own+ # encryptor - see app/models/setting.rb), independent of whether+ # ActiveRecord Encryption is configured at all, where its keys come from,+ # or which app_mode this install runs in - a managed instance spun up+ # from compose.example.yml (e.g. for staging/POC) and never rotated is+ # just as exposed as a self-hosted one. Suppressing it whenever AR+ # encryption has explicit keys, or whenever the app isn't self-hosted,+ # would hide a real compromise of sessions/Settings just because AR+ # encryption itself isn't affected.+ if 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+ Rails session cookies, and can decrypt any value stored via Setting+ (AI/market-data provider API keys, etc.), which derives its own+ encryption key directly from SECRET_KEY_BASE - independently of+ ActiveRecord Encryption. Your ActiveRecord Encryption keys are+ explicitly configured and are NOT derived from SECRET_KEY_BASE, so+ they are unaffected by this. Rotate SECRET_KEY_BASE to a unique+ value 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).+ WARN+ else+ Rails.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+ knows that value can compute the same encryption keys, so this+ installation's "encrypted" data is not actually protected. The same+ value also signs/encrypts Rails session cookies and Setting's own+ encrypted values (AI/market-data provider API keys, etc.), which+ are compromised regardless of ActiveRecord Encryption.+ Do NOT simply set a new SECRET_KEY_BASE and run+ security:backfill_encryption: if any data was already encrypted under+ the compromised key, the backfill task cannot tell that ciphertext+ apart from real plaintext, will re-encrypt it under the new key on+ top 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.+ WARN+ endendenddiff --git a/docs/hosting/encryption.md b/docs/hosting/encryption.mdnew file mode 100644index 0000000000..ba4676c178--- /dev/null+++ b/docs/hosting/encryption.md@@ -0,0 +1,159 @@+# 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. 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.++> 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 expect a short maintenance+window for step 3–4.++## 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+`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++```sh+bin/rails security:backfill_encryption # dry run: reports what would change+DRY_RUN=false bin/rails security:backfill_encryption # actually re-encrypts+```++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.++**It does not migrate deterministic columns** — see the next step.++## 3. Migrate the deterministic attributes explicitly++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:++```sh+grep -rn "deterministic: true" app/models+```++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+```++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}"+```++`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.)++## 4. Retire the compromised scheme++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.++## What this does not cover++- **`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.diff --git a/lib/active_record_encryption_config.rb b/lib/active_record_encryption_config.rbindex 463976adcb..a3ce0610fe 100644--- a/lib/active_record_encryption_config.rb+++ b/lib/active_record_encryption_config.rb@@ -7,6 +7,18 @@ 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+ # (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+ ].freeze+CONFIG_KEYS = %i[primary_keydeterministic_key@@ -33,11 +45,67 @@ module ActiveRecordEncryptionConfigenddef credentials_configured?(credentials = Rails.application.credentials)- credentials.active_record_encryption.present?+ config = credentials.active_record_encryption+ return false unless config.present?++ CONFIG_KEYS.all? { |key| config.public_send(key).present? }rescue NoMethodErrorfalseend+ # Unlike partial_env? (ENV vars), a present-but-incomplete Rails credentials+ # block does NOT fall through to auto-generation from SECRET_KEY_BASE - see+ # config/initializers/active_record_encryption.rb's `elsif ... &&+ # !Rails.application.credentials.active_record_encryption.present?` guard.+ # Left unchecked this silently disables encryption entirely (ready? / thus+ # every model's `encrypts` declaration goes false) instead of failing loudly+ # like the equivalent partial-ENV case does.+ #+ # Deliberately NOT the same shape as partial_env? (which requires at least+ # one key present): once the credentials block itself exists at all - even+ # with every individual key blank, e.g. `primary_key: ""` - that's already+ # a configuration mistake worth failing loudly on, unlike ENV vars being+ # entirely absent (a normal, unconfigured state that falls through to+ # other paths). CodeRabbit caught this: an all-blank block used to slip+ # through as present_count == 0, silently skipping both the raise and+ # self-hosted auto-generation (config.application.rb's `.present?` check+ # on the block already treats it as configured either way).+ def partial_credentials?(credentials = Rails.application.credentials)+ config = credentials.active_record_encryption+ return false unless config.present?++ !CONFIG_KEYS.all? { |key| config.public_send(key).present? }+ rescue NoMethodError+ false+ end++ def missing_credential_keys(credentials = Rails.application.credentials)+ config = credentials.active_record_encryption+ return CONFIG_KEYS.dup unless config.present?++ CONFIG_KEYS.reject { |key| config.public_send(key).present? }+ rescue NoMethodError+ CONFIG_KEYS.dup+ end++ def partial_credentials_message(credentials = Rails.application.credentials)+ "Active Record encryption Rails credentials are partially configured. Missing: #{missing_credential_keys(credentials).join(', ')}"+ end++ # Whether the boot check in config/initializers/active_record_encryption.rb+ # should reject a present-but-incomplete credentials block. Skipped when+ # the ENV configuration is complete: ENV keys take priority over+ # credentials (the documented priority order in that initializer), so a+ # stale/incomplete credentials block must not stop such an installation+ # from booting - the complete-ENV branch applies and the credentials block+ # is ignored entirely. Previously the initializer checked+ # partial_credentials? unconditionally and raised before the complete-ENV+ # branch was ever considered, which broke boot on upgrade for exactly+ # those installations (jjmata's review on #3189).+ def reject_partial_credentials?(env = ENV, credentials = Rails.application.credentials)+ !complete_env?(env) && partial_credentials?(credentials)+ end+def runtime_configured?(config = Rails.application.config.active_record.encryption)CONFIG_KEYS.all? { |key| config.public_send(key).present? }rescue NoMethodError@@ -52,6 +120,25 @@ module ActiveRecordEncryptionConfigexplicitly_configured? || runtime_configured?end+ # Deliberately independent of explicitly_configured?/ready?: this is a fact+ # about SECRET_KEY_BASE itself, not about whether Active Record Encryption's+ # own keys happen to be derived from it. Explicit AR keys only mean AR+ # encryption isn't affected - SECRET_KEY_BASE also signs/encrypts Rails+ # session cookies and is the sole key source for Setting's own encryptor+ # (app/models/setting.rb's setting_encryptor), independently of AR+ # encryption config. A previous version of this method returned false+ # whenever explicitly_configured? was true, which suppressed the warning+ # in config/initializers/encryption_warning.rb entirely for installs with+ # explicit AR keys - even though their sessions and Setting-encrypted+ # provider/AI API keys remained trivially crackable by anyone who knows+ # this public compromised value. See ActiveRecordEncryptionConfig#ready?+ # for the (separate) question of whether AR encryption itself is affected.+ def using_known_compromised_secret_key_base?(secret_key_base = Rails.application.secret_key_base)+ KNOWN_COMPROMISED_SECRET_KEY_BASES.include?(secret_key_base)+ rescue NoMethodError+ false+ end+def env_value_present?(env, key)env[key].present?enddiff --git a/lib/generators/provider/family/templates/item_model.rb.tt b/lib/generators/provider/family/templates/item_model.rb.ttindex 44f6ab2ec3..3895cbeb3e 100644--- a/lib/generators/provider/family/templates/item_model.rb.tt+++ b/lib/generators/provider/family/templates/item_model.rb.tt@@ -1,7 +1,7 @@# frozen_string_literal: trueclass <%= class_name %>Item < ApplicationRecord- include Syncable, Provided, Unlinking, DestroyableLater, ProviderDisconnectable+ include Syncable, Provided, Unlinking, Encryptable, DestroyableLater, ProviderDisconnectable# Set to true once this provider implements removal of the data it imported, so# a client may disconnect with disposition "discard". Left false until then:@@ -12,15 +12,6 @@ class <%= class_name %>Item < ApplicationRecordenum :status, { good: "good", requires_update: "requires_update" }, default: :good- # Helper to detect if ActiveRecord Encryption is configured for this app- def self.encryption_ready?- creds_ready = Rails.application.credentials.active_record_encryption.present?- env_ready = ENV["ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY"].present? &&- ENV["ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY"].present? &&- ENV["ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT"].present?- creds_ready || env_ready- end-# Encrypt sensitive credentials if ActiveRecord encryption is configuredif encryption_ready?<% parsed_fields.select { |f| f[:secret] }.each do |field| -%>diff --git a/lib/tasks/security_backfill.rake b/lib/tasks/security_backfill.rakeindex 02d8b43175..8aa7a1e992 100644--- a/lib/tasks/security_backfill.rake+++ b/lib/tasks/security_backfill.rake@@ -10,6 +10,13 @@ namespace :security do# the #2611 fix and provider payloads now decrypt to Strings (symptom:# zero balances on every provider-linked account after a sync), run the# 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.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"diff --git a/test/controllers/api/v1/auth_controller_test.rb b/test/controllers/api/v1/auth_controller_test.rbindex 814fa8ff28..9043e4587a 100644--- a/test/controllers/api/v1/auth_controller_test.rb+++ b/test/controllers/api/v1/auth_controller_test.rb@@ -301,6 +301,20 @@ class Api::V1::AuthControllerTest < ActionDispatch::IntegrationTestassert device.active?end+ test "should login a user whose email row is still legacy plaintext" do+ user = users(:family_admin)+ email = store_legacy_plaintext_email(user)++ post "/api/v1/auth/login", params: {+ email: email,+ password: user_password_test,+ device: @device_info+ }++ assert_response :success+ assert_equal user.id.to_s, JSON.parse(response.body)["user"]["id"]+ end+# SessionsController refuses local sign-in when SSO-only mode is on, with a# single exception for a super-admin when the emergency override is enabled.# The API mints the same credentials and enforced neither.@@ -729,6 +743,34 @@ class Api::V1::AuthControllerTest < ActionDispatch::IntegrationTestassert_nil Rails.cache.read("mobile_sso_link:#{linking_code}")end+ test "should link SSO for a user whose email row is still legacy plaintext" do+ user = users(:family_admin)+ email = store_legacy_plaintext_email(user)++ linking_code = SecureRandom.urlsafe_base64(32)+ Rails.cache.write("mobile_sso_link:#{linking_code}", {+ provider: "google_oauth2",+ uid: "google-uid-legacy",+ email: "[email protected]",+ first_name: "Google",+ last_name: "User",+ name: "Google User",+ device_info: @device_info.stringify_keys,+ allow_account_creation: true+ }, expires_in: 10.minutes)++ assert_difference("OidcIdentity.count", 1) do+ post "/api/v1/auth/sso_link", params: {+ linking_code: linking_code,+ email: email,+ password: user_password_test+ }+ end++ assert_response :success+ assert_equal user.id.to_s, JSON.parse(response.body)["user"]["id"]+ end+test "should reject SSO link for a deactivated user even with correct password" douser = users(:family_admin)user.update_column(:active, false)diff --git a/test/controllers/mcp_controller_test.rb b/test/controllers/mcp_controller_test.rbindex d52f8f4ccd..abf6eec81b 100644--- a/test/controllers/mcp_controller_test.rb+++ b/test/controllers/mcp_controller_test.rb@@ -170,6 +170,17 @@ class McpControllerTest < ActionDispatch::IntegrationTestendend+ test "env-var token works for a user whose email row is still legacy plaintext" do+ store_legacy_plaintext_email(@user)++ with_mcp_env do+ post "/mcp", params: jsonrpc_request("initialize").to_json,+ headers: mcp_headers(@token)++ assert_response :ok+ end+ end+test "returns 401 and warns when env-var token matches but MCP_USER_EMAIL finds no user" dowith_env_overrides("MCP_API_TOKEN" => @token, "MCP_USER_EMAIL" => "[email protected]") do # pipelock:ignoreRails.logger.expects(:warn).with(regexp_matches(/MCP_USER_EMAIL/)).oncediff --git a/test/controllers/oidc_accounts_controller_test.rb b/test/controllers/oidc_accounts_controller_test.rbindex f3b9970edb..113da4f7b9 100644--- a/test/controllers/oidc_accounts_controller_test.rb+++ b/test/controllers/oidc_accounts_controller_test.rb@@ -62,6 +62,20 @@ class OidcAccountsControllerTest < ActionController::TestCaseassert session[:pending_oidc_auth].present?end+ test "links a user whose email row is still legacy plaintext" do+ session[:pending_oidc_auth] = pending_auth+ email = store_legacy_plaintext_email(@user)++ get :link+ assert @controller.instance_variable_get(:@user_exists)++ assert_difference "OidcIdentity.count", 1 do+ post :create_link, params: { email: email, password: user_password_test }+ end++ assert_redirected_to root_path+ end+test "should reject linking with invalid password" dosession[:pending_oidc_auth] = pending_authdiff --git a/test/controllers/password_resets_controller_test.rb b/test/controllers/password_resets_controller_test.rbindex 8f01aeabb6..43d51ae68b 100644--- a/test/controllers/password_resets_controller_test.rb+++ b/test/controllers/password_resets_controller_test.rb@@ -17,6 +17,14 @@ class PasswordResetsControllerTest < ActionDispatch::IntegrationTestendend+ test "create sends a reset email to a user whose email row is still legacy plaintext" do+ email = store_legacy_plaintext_email(@user)++ assert_enqueued_emails 1 do+ post password_reset_path, params: { email: email }+ end+ end+test "edit" doget edit_password_reset_path(token: @user.generate_token_for(:password_reset))assert_response :okdiff --git a/test/controllers/sessions_controller_test.rb b/test/controllers/sessions_controller_test.rbindex 2b64eca9fb..575d399eab 100644--- a/test/controllers/sessions_controller_test.rb+++ b/test/controllers/sessions_controller_test.rb@@ -203,6 +203,25 @@ class SessionsControllerTest < ActionDispatch::IntegrationTestassert cookies[:session_token].blank?end+ test "signs in a user whose email row is still legacy plaintext" do+ email = store_legacy_plaintext_email(@user)++ post sessions_url, params: { email: email.upcase, password: user_password_test }++ assert_redirected_to root_url+ assert Session.exists?(user_id: @user.id)+ end++ test "rejects a bad password for a user whose email row is still legacy plaintext" do+ email = store_legacy_plaintext_email(@user)++ assert_no_difference "Session.count" do+ post sessions_url, params: { email: email, password: "bad" }+ end++ assert_response :unprocessable_entity+ end+test "fails to sign in with bad password" dopost sessions_url, params: { email: @user.email, password: "bad" }assert_response :unprocessable_entity@@ -261,6 +280,19 @@ class SessionsControllerTest < ActionDispatch::IntegrationTestassert Session.exists?(user_id: super_admin.id)end+ test "allows the super admin override for a user whose email row is still legacy plaintext" do+ super_admin = users(:sure_support_staff)+ email = store_legacy_plaintext_email(super_admin)++ AuthConfig.stubs(:local_login_enabled?).returns(false)+ AuthConfig.stubs(:local_admin_override_enabled?).returns(true)++ post sessions_url, params: { email: email, password: user_password_test }++ assert_redirected_to root_path+ assert Session.exists?(user_id: super_admin.id)+ end+test "shows invalid credentials for super admin when override enabled but password is wrong" dosuper_admin = users(:sure_support_staff)diff --git a/test/controllers/settings/providers_controller_test.rb b/test/controllers/settings/providers_controller_test.rbindex 5520b180e4..94e5842416 100644--- a/test/controllers/settings/providers_controller_test.rb+++ b/test/controllers/settings/providers_controller_test.rb@@ -675,7 +675,7 @@ class Settings::ProvidersControllerTest < ActionDispatch::IntegrationTesttest "GET show warns on configured provider forms when self-hosted encryption keys are not explicitly configured" doSetting["plaid_client_id"] = "test-client-id"Setting["plaid_secret"] = "test-secret"- ActiveRecordEncryptionConfig.stubs(:explicitly_configured?).returns(false)+ ActiveRecordEncryptionConfig.stubs(:ready?).returns(false)with_self_hosting doget settings_providers_url@@ -697,7 +697,7 @@ class Settings::ProvidersControllerTest < ActionDispatch::IntegrationTestSetting["plaid_client_id"] = "test-client-id"Setting["plaid_secret"] = "test-secret"Rails.configuration.stubs(:app_mode).returns("managed".inquiry)- ActiveRecordEncryptionConfig.stubs(:explicitly_configured?).returns(false)+ ActiveRecordEncryptionConfig.stubs(:ready?).returns(false)get settings_providers_url@@ -735,7 +735,7 @@ class Settings::ProvidersControllerTest < ActionDispatch::IntegrationTesttest "GET connect_form warns when self-hosted encryption keys are not explicitly configured" dowith_self_hosting do- ActiveRecordEncryptionConfig.stubs(:explicitly_configured?).returns(false)+ ActiveRecordEncryptionConfig.stubs(:ready?).returns(false)get connect_form_settings_providers_path(provider_key: "ibkr")@@ -752,7 +752,7 @@ class Settings::ProvidersControllerTest < ActionDispatch::IntegrationTesttest "GET connect_form hides encryption warning when self-hosted encryption keys are configured" dowith_self_hosting do- ActiveRecordEncryptionConfig.stubs(:explicitly_configured?).returns(true)+ ActiveRecordEncryptionConfig.stubs(:ready?).returns(true)get connect_form_settings_providers_path(provider_key: "ibkr")@@ -769,7 +769,7 @@ class Settings::ProvidersControllerTest < ActionDispatch::IntegrationTesttest "GET connect_form hides encryption warning in managed mode" doRails.configuration.stubs(:app_mode).returns("managed".inquiry)- ActiveRecordEncryptionConfig.stubs(:explicitly_configured?).returns(false)+ ActiveRecordEncryptionConfig.stubs(:ready?).returns(false)get connect_form_settings_providers_path(provider_key: "ibkr")@@ -785,7 +785,7 @@ class Settings::ProvidersControllerTest < ActionDispatch::IntegrationTesttest "GET connect_form uses shared encryption warning for provider panels" dowith_self_hosting do- ActiveRecordEncryptionConfig.stubs(:explicitly_configured?).returns(false)+ ActiveRecordEncryptionConfig.stubs(:ready?).returns(false)get connect_form_settings_providers_path(provider_key: "wise")@@ -818,6 +818,26 @@ class Settings::ProvidersControllerTest < ActionDispatch::IntegrationTestassert_match(I18n.t("settings.providers.trade_republic_panel.phone_number_label"), response.body)end+ test "GET show hides provider form encryption warning when only runtime-generated keys are available" do+ # Regression test for issue #3142: self-hosted installs relying on the+ # SECRET_KEY_BASE auto-generation fallback (explicitly_configured? false,+ # runtime_configured? true) must NOT see the "encryption keys missing" warning.+ Setting["plaid_client_id"] = "test-client-id"+ Setting["plaid_secret"] = "test-secret"+ Rails.configuration.stubs(:app_mode).returns("self_hosted".inquiry)+ ActiveRecordEncryptionConfig.stubs(:explicitly_configured?).returns(false)+ ActiveRecordEncryptionConfig.stubs(:runtime_configured?).returns(true)++ get settings_providers_url++ assert_response :success+ refute_includes response.body, I18n.t("settings.providers.provider_setup_encryption_warning.title")+ refute_includes response.body, I18n.t("settings.providers.provider_setup_encryption_warning.message")+ ensure+ Setting["plaid_client_id"] = nil+ Setting["plaid_secret"] = nil+ end+test "GET connect_form for snaptrade shows OAuth setup instructions when instance is not configured" doProvider::Snaptrade.stubs(:oauth_configured?).returns(false)diff --git a/test/controllers/settings/securities_controller_test.rb b/test/controllers/settings/securities_controller_test.rbindex f6009d7d8e..38179fc8c9 100644--- a/test/controllers/settings/securities_controller_test.rb+++ b/test/controllers/settings/securities_controller_test.rb@@ -5,7 +5,7 @@ class Settings::SecuritiesControllerTest < ActionDispatch::IntegrationTesttest "shows encryption warning when self-hosted and encryption is not configured" doRails.configuration.stubs(:app_mode).returns("self_hosted".inquiry)- ActiveRecordEncryptionConfig.stubs(:explicitly_configured?).returns(false)+ ActiveRecordEncryptionConfig.stubs(:ready?).returns(false)get settings_security_url@@ -18,7 +18,21 @@ class Settings::SecuritiesControllerTest < ActionDispatch::IntegrationTesttest "hides encryption warning when encryption is configured" doRails.configuration.stubs(:app_mode).returns("self_hosted".inquiry)- ActiveRecordEncryptionConfig.stubs(:explicitly_configured?).returns(true)+ ActiveRecordEncryptionConfig.stubs(:ready?).returns(true)++ get settings_security_url++ assert_response :success+ assert_not_includes response.body, I18n.t("settings.securities.show.encryption_warning.title")+ end++ test "hides encryption warning when only runtime-generated keys are available" do+ # Regression test for issue #3142: self-hosted installs relying on the+ # SECRET_KEY_BASE auto-generation fallback (explicitly_configured? false,+ # runtime_configured? true) must NOT see the "not configured" warning.+ Rails.configuration.stubs(:app_mode).returns("self_hosted".inquiry)+ ActiveRecordEncryptionConfig.stubs(:explicitly_configured?).returns(false)+ ActiveRecordEncryptionConfig.stubs(:runtime_configured?).returns(true)get settings_security_urldiff --git a/test/encryption_verification_test.rb b/test/encryption_verification_test.rbindex ed37bdc5de..5fe19acb16 100644--- a/test/encryption_verification_test.rb+++ b/test/encryption_verification_test.rb@@ -450,9 +450,11 @@ class EncryptionVerificationTest < ActiveSupport::TestCase)EnableBankingItem.where(id: eb_item.id).update_all("last_psu_ip = '203.0.113.50'")- # No global support_unencrypted_data: the attribute's own option must cover it- assert_not ActiveRecord::Encryption.config.support_unencrypted_data- assert_equal "203.0.113.50", eb_item.reload.last_psu_ip+ # The global setting can be on during the backfill window, so turn it off+ # here: the attribute's own option must cover the legacy value by itself.+ with_unencrypted_data_supported(false) do+ assert_equal "203.0.113.50", eb_item.reload.last_psu_ip+ endend# ============================================================================@@ -482,9 +484,9 @@ class EncryptionVerificationTest < ActiveSupport::TestCaseprivate- def with_unencrypted_data_supported+ def with_unencrypted_data_supported(enabled = true)previous = ActiveRecord::Encryption.config.support_unencrypted_data- ActiveRecord::Encryption.config.support_unencrypted_data = true+ ActiveRecord::Encryption.config.support_unencrypted_data = enabledyieldensureActiveRecord::Encryption.config.support_unencrypted_data = previousdiff --git a/test/initializers/active_record_encryption_test.rb b/test/initializers/active_record_encryption_test.rbnew file mode 100644index 0000000000..ba77041db4--- /dev/null+++ b/test/initializers/active_record_encryption_test.rb@@ -0,0 +1,79 @@+# frozen_string_literal: true++require "test_helper"++class ActiveRecordEncryptionInitializerTest < ActiveSupport::TestCase+ test "supports reading legacy plaintext data written before encryption was correctly gated" do+ # Without this, any not-yet-backfilled row (see bin/rails+ # security:backfill_encryption) raises ActiveRecord::Encryption::Errors::Decryption+ # the moment it's read, instead of falling back to the raw value.+ assert Rails.application.config.active_record.encryption.support_unencrypted_data+ end++ test "extends deterministic queries to also match legacy plaintext data" do+ # Without this, deterministic lookups (e.g. User.find_by(email:)) only+ # match already-encrypted rows and silently miss not-yet-backfilled ones.+ assert Rails.application.config.active_record.encryption.extend_queries+ end++ test "reads a legacy plaintext string value without raising" do+ skip "Encryption not configured" unless User.encryption_ready?++ user = users(:family_admin)+ # Bypass the encrypted setter to simulate a row written before encryption+ # was correctly gated (the exact bug fixed on this PR, see #3142).+ ActiveRecord::Base.connection.execute(+ ActiveRecord::Base.sanitize_sql([ "UPDATE users SET email = ? WHERE id = ?", "[email protected]", user.id ])+ )++ assert_equal "[email protected]", user.reload.email+ end++ test "deterministic find_by matches a legacy plaintext row for a plain (non-downcase) attribute" do+ skip "Encryption not configured" unless Invitation.encryption_ready?++ invitation = invitations(:one)+ ActiveRecord::Base.connection.execute(+ ActiveRecord::Base.sanitize_sql([ "UPDATE invitations SET token = ? WHERE id = ?", "legacy-token-abc", invitation.id ])+ )++ assert_equal invitation, Invitation.find_by(token: "legacy-token-abc")+ end++ # KNOWN LIMITATION (see the comment on extend_queries in+ # config/initializers/active_record_encryption.rb): deterministic finders+ # do not match legacy plaintext rows for attributes that combine+ # `encrypts ..., downcase: true` with a model-level `normalizes`+ # declaration - User#email is exactly that. This documents the current+ # behavior (returns nil, does not raise) so a future Rails upgrade that+ # fixes the underlying gap changes this test, not production behavior.+ test "deterministic find_by does not match a legacy plaintext row for a downcase+normalized attribute (known limitation)" 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_nil User.find_by(email: "[email protected]")+ # The direct read still works (support_unencrypted_data) - only the+ # deterministic query match is affected.+ assert_equal "[email protected]", user.reload.email+ end++ test "reads a legacy plaintext jsonb value as its original Hash, not a String" do+ skip "Encryption not configured" unless SnaptradeAccount.encryption_ready?++ account = snaptrade_accounts(:fidelity_401k)+ payload = { "account_category" => "DEPOSIT" }+ # jsonb columns need an explicit ::jsonb cast; a bare bind param would be+ # sent as text and rejected by the column type.+ ActiveRecord::Base.connection.execute(+ ActiveRecord::Base.sanitize_sql([ "UPDATE snaptrade_accounts SET raw_payload = ?::jsonb WHERE id = ?", payload.to_json, account.id ])+ )++ reloaded = account.reload.raw_payload+ assert_kind_of Hash, reloaded, "jsonb payload must deserialize to a Hash, not raw JSON text"+ assert_equal "DEPOSIT", reloaded["account_category"]+ end+enddiff --git a/test/lib/active_record_encryption_config_test.rb b/test/lib/active_record_encryption_config_test.rbindex 825d357d7a..bf672dcdcf 100644--- a/test/lib/active_record_encryption_config_test.rb+++ b/test/lib/active_record_encryption_config_test.rb@@ -45,6 +45,20 @@ class ActiveRecordEncryptionConfigTest < ActiveSupport::TestCaseassert ActiveRecordEncryptionConfig.runtime_configured?(config)end+ test "detects complete credentials configuration" do+ encryption_config = OpenStruct.new(primary_key: "primary", deterministic_key: "deterministic", key_derivation_salt: "salt")+ credentials = OpenStruct.new(active_record_encryption: encryption_config)++ assert ActiveRecordEncryptionConfig.credentials_configured?(credentials)+ end++ test "does not treat partial credentials as configured" do+ encryption_config = OpenStruct.new(primary_key: "primary", deterministic_key: nil, key_derivation_salt: "salt")+ credentials = OpenStruct.new(active_record_encryption: encryption_config)++ refute ActiveRecordEncryptionConfig.credentials_configured?(credentials)+ end+test "explicit configuration excludes runtime generated config" doActiveRecordEncryptionConfig.stubs(:complete_env?).returns(false)ActiveRecordEncryptionConfig.stubs(:credentials_configured?).returns(false)@@ -53,4 +67,109 @@ class ActiveRecordEncryptionConfigTest < ActiveSupport::TestCaserefute ActiveRecordEncryptionConfig.explicitly_configured?assert ActiveRecordEncryptionConfig.ready?end++ test "detects a secret key base that was previously shipped as a compose default" do+ known_default = ActiveRecordEncryptionConfig::KNOWN_COMPROMISED_SECRET_KEY_BASES.first++ assert ActiveRecordEncryptionConfig.using_known_compromised_secret_key_base?(known_default)+ refute ActiveRecordEncryptionConfig.using_known_compromised_secret_key_base?("a-real-generated-secret")+ end++ test "using_known_compromised_secret_key_base? defaults to the app's own secret_key_base" do+ Rails.application.stubs(:secret_key_base).returns(ActiveRecordEncryptionConfig::KNOWN_COMPROMISED_SECRET_KEY_BASES.first)+ assert ActiveRecordEncryptionConfig.using_known_compromised_secret_key_base?++ Rails.application.stubs(:secret_key_base).returns("a-real-generated-secret")+ refute ActiveRecordEncryptionConfig.using_known_compromised_secret_key_base?+ end++ test "using_known_compromised_secret_key_base? is true regardless of explicit AR encryption keys" do+ # SECRET_KEY_BASE also signs/encrypts Rails session cookies and is the+ # sole key source for Setting's own encryptor (app/models/setting.rb),+ # independently of ActiveRecord Encryption. An install with its own+ # explicit AR keys is unaffected on the AR-encryption front, but its+ # sessions and Setting-stored values (AI/market-data provider API keys)+ # remain just as crackable, so this must not be suppressed by+ # explicitly_configured? - see config/initializers/encryption_warning.rb+ # for how the two concerns are reported separately.+ known_default = ActiveRecordEncryptionConfig::KNOWN_COMPROMISED_SECRET_KEY_BASES.first+ ActiveRecordEncryptionConfig.stubs(:explicitly_configured?).returns(true)++ assert ActiveRecordEncryptionConfig.using_known_compromised_secret_key_base?(known_default)+ end++ test "detects partially configured encryption credentials" do+ encryption_config = OpenStruct.new(primary_key: "primary", deterministic_key: nil, key_derivation_salt: "salt")+ credentials = OpenStruct.new(active_record_encryption: encryption_config)++ refute ActiveRecordEncryptionConfig.credentials_configured?(credentials)+ assert ActiveRecordEncryptionConfig.partial_credentials?(credentials)+ assert_equal [ :deterministic_key ], ActiveRecordEncryptionConfig.missing_credential_keys(credentials)+ assert_includes ActiveRecordEncryptionConfig.partial_credentials_message(credentials), "deterministic_key"+ end++ test "does not treat absent encryption credentials as partial" do+ credentials = OpenStruct.new(active_record_encryption: nil)++ refute ActiveRecordEncryptionConfig.credentials_configured?(credentials)+ refute ActiveRecordEncryptionConfig.partial_credentials?(credentials)+ end++ test "does not treat complete encryption credentials as partial" do+ encryption_config = OpenStruct.new(primary_key: "primary", deterministic_key: "deterministic", key_derivation_salt: "salt")+ credentials = OpenStruct.new(active_record_encryption: encryption_config)++ assert ActiveRecordEncryptionConfig.credentials_configured?(credentials)+ refute ActiveRecordEncryptionConfig.partial_credentials?(credentials)+ end++ # Regression test for a gap CodeRabbit flagged: a present credentials block+ # with every individual key blank had present_count == 0, so the old+ # `present_count.positive? && ...` shape treated it the same as an absent+ # block (not partial) - silently skipping both the raise and self-hosted+ # auto-generation, since config/application.rb's `.present?` check on the+ # block itself already treats it as configured either way.+ test "treats a present credentials block with every key blank as partial" do+ encryption_config = OpenStruct.new(primary_key: "", deterministic_key: "", key_derivation_salt: "")+ credentials = OpenStruct.new(active_record_encryption: encryption_config)++ refute ActiveRecordEncryptionConfig.credentials_configured?(credentials)+ assert ActiveRecordEncryptionConfig.partial_credentials?(credentials)+ assert_equal ActiveRecordEncryptionConfig::CONFIG_KEYS, ActiveRecordEncryptionConfig.missing_credential_keys(credentials)+ end++ # Regression coverage for jjmata's review on #3189: the boot check used to+ # run partial_credentials? unconditionally, before the complete-ENV branch+ # of the initializer was ever considered - so an installation with a+ # complete, valid ACTIVE_RECORD_ENCRYPTION_* set AND a stale/incomplete+ # credentials block stopped booting on upgrade, despite the documented+ # ENV-first priority.+ test "complete ENV configuration is not rejected by a partial credentials block" do+ env = {+ "ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY" => "primary",+ "ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY" => "deterministic",+ "ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT" => "salt"+ }+ encryption_config = OpenStruct.new(primary_key: "stale", deterministic_key: nil, key_derivation_salt: "stale")+ credentials = OpenStruct.new(active_record_encryption: encryption_config)++ assert ActiveRecordEncryptionConfig.complete_env?(env)+ assert ActiveRecordEncryptionConfig.partial_credentials?(credentials)+ refute ActiveRecordEncryptionConfig.reject_partial_credentials?(env, credentials)+ end++ test "partial credentials are still rejected when the ENV configuration is absent or incomplete" do+ encryption_config = OpenStruct.new(primary_key: "primary", deterministic_key: nil, key_derivation_salt: "salt")+ credentials = OpenStruct.new(active_record_encryption: encryption_config)++ # Absent ENV entirely: the credentials block is the only candidate+ # configuration, and an incomplete one must still fail loudly.+ assert ActiveRecordEncryptionConfig.reject_partial_credentials?({}, credentials)+ # (A *partial* ENV set never reaches this predicate in the initializer -+ # partial_env? raises first - but the predicate stays honest standalone.)+ assert ActiveRecordEncryptionConfig.reject_partial_credentials?(+ { "ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY" => "primary" }, credentials+ )+ refute ActiveRecordEncryptionConfig.reject_partial_credentials?({}, OpenStruct.new(active_record_encryption: nil))+ endenddiff --git a/test/models/coinstats_item_test.rb b/test/models/coinstats_item_test.rbindex 37180e0dfe..f4065fb997 100644--- a/test/models/coinstats_item_test.rb+++ b/test/models/coinstats_item_test.rb@@ -228,4 +228,10 @@ class CoinstatsItemTest < ActiveSupport::TestCaseassert_equal "1 crypto wallets synced, 1 need setup", @coinstats_item.sync_status_summaryend++ test "declares api_key as encrypted" do+ skip "Encryption not configured" unless CoinstatsItem.encryption_ready?++ assert_includes CoinstatsItem.encrypted_attributes.map(&:to_s), "api_key"+ endenddiff --git a/test/models/concerns/encryptable_test.rb b/test/models/concerns/encryptable_test.rbnew file mode 100644index 0000000000..9725ffdbd0--- /dev/null+++ b/test/models/concerns/encryptable_test.rb@@ -0,0 +1,33 @@+require "test_helper"++class EncryptableTest < ActiveSupport::TestCase+ class TestRecord+ include Encryptable+ end++ test "encryption_ready? delegates to ActiveRecordEncryptionConfig.ready?" do+ ActiveRecordEncryptionConfig.stubs(:ready?).returns(true)+ assert TestRecord.encryption_ready?++ ActiveRecordEncryptionConfig.stubs(:ready?).returns(false)+ assert_not TestRecord.encryption_ready?+ end++ test "encryption_ready? is true for the SECRET_KEY_BASE auto-generated runtime path" do+ # Regression test for issue #3142: encryption_ready? must recognize keys+ # derived from SECRET_KEY_BASE and loaded into+ # Rails.application.config.active_record.encryption at boot, not just+ # explicit ACTIVE_RECORD_ENCRYPTION_* env vars or Rails credentials.+ ActiveRecordEncryptionConfig.stubs(:explicitly_configured?).returns(false)+ ActiveRecordEncryptionConfig.stubs(:runtime_configured?).returns(true)++ assert TestRecord.encryption_ready?+ end++ test "encryption_ready? is false when neither explicit nor runtime config is present" do+ ActiveRecordEncryptionConfig.stubs(:explicitly_configured?).returns(false)+ ActiveRecordEncryptionConfig.stubs(:runtime_configured?).returns(false)++ assert_not TestRecord.encryption_ready?+ end+enddiff --git a/test/models/indexa_capital_item_test.rb b/test/models/indexa_capital_item_test.rbindex 76bc77a225..32cf78d8ad 100644--- a/test/models/indexa_capital_item_test.rb+++ b/test/models/indexa_capital_item_test.rb@@ -140,4 +140,11 @@ class IndexaCapitalItemTest < ActiveSupport::TestCaseassert_equal I18n.t("indexa_capital_items.sync_status.synced_with_setup", linked: 1, unlinked: 1), @item.sync_status_summaryend++ test "declares password and api_token as encrypted" do+ skip "Encryption not configured" unless IndexaCapitalItem.encryption_ready?++ assert_includes IndexaCapitalItem.encrypted_attributes.map(&:to_s), "password"+ assert_includes IndexaCapitalItem.encrypted_attributes.map(&:to_s), "api_token"+ endenddiff --git a/test/models/mercury_item_test.rb b/test/models/mercury_item_test.rbindex 91d67c26df..6ce4758342 100644--- a/test/models/mercury_item_test.rb+++ b/test/models/mercury_item_test.rb@@ -87,4 +87,10 @@ class MercuryItemTest < ActiveSupport::TestCasesyncer = @mercury_item.send(:syncer)assert_instance_of MercuryItem::Syncer, syncerend++ test "declares token as encrypted" do+ skip "Encryption not configured" unless MercuryItem.encryption_ready?++ assert_includes MercuryItem.encrypted_attributes.map(&:to_s), "token"+ endenddiff --git a/test/models/snaptrade_item_test.rb b/test/models/snaptrade_item_test.rbindex 8bdaf3a4f5..55b4c69b10 100644--- a/test/models/snaptrade_item_test.rb+++ b/test/models/snaptrade_item_test.rb@@ -61,4 +61,15 @@ class SnaptradeItemTest < ActiveSupport::TestCaseitem.sync_later_with_follow_upendend++ test "declares OAuth credential fields as encrypted" do+ skip "Encryption not configured" unless SnaptradeItem.encryption_ready?++ encrypted = SnaptradeItem.encrypted_attributes.map(&:to_s)+ assert_includes encrypted, "client_id"+ assert_includes encrypted, "consumer_key"+ assert_includes encrypted, "snaptrade_user_secret"+ assert_includes encrypted, "oauth_access_token"+ assert_includes encrypted, "oauth_refresh_token"+ endenddiff --git a/test/models/sophtron_item_test.rb b/test/models/sophtron_item_test.rbindex c782856986..cfad67ed53 100644--- a/test/models/sophtron_item_test.rb+++ b/test/models/sophtron_item_test.rb@@ -215,4 +215,11 @@ class SophtronItemTest < ActiveSupport::TestCaseassert_empty manual_item.automatic_sync_sophtron_accountsassert_equal [ first_account, second_account ], manual_item.manual_sync_sophtron_accounts.to_aend++ test "declares user_id and access_key as encrypted" do+ skip "Encryption not configured" unless SophtronItem.encryption_ready?++ assert_includes SophtronItem.encrypted_attributes.map(&:to_s), "user_id"+ assert_includes SophtronItem.encrypted_attributes.map(&:to_s), "access_key"+ endenddiff --git a/test/models/user_test.rb b/test/models/user_test.rbindex 18362b3e90..aba87daef2 100644--- a/test/models/user_test.rb+++ b/test/models/user_test.rb@@ -20,6 +20,76 @@ class UserTest < ActiveSupport::TestCaseassert @user.valid?, @user.errors.full_messages.to_sentenceend+ test "find_by_email_with_legacy_fallback matches encrypted and legacy plaintext email rows" do+ assert_equal @user, User.find_by_email_with_legacy_fallback(" #{@user.email.upcase} ")++ email = store_legacy_plaintext_email(@user)++ assert_equal @user, User.find_by_email_with_legacy_fallback(email.upcase)+ assert_nil User.find_by_email_with_legacy_fallback("")+ assert_nil User.find_by_email_with_legacy_fallback("[email protected]")+ end++ test "authenticate_by_email checks the password for legacy plaintext email rows" do+ email = store_legacy_plaintext_email(@user)++ assert_equal @user, User.authenticate_by_email(email: email, password: user_password_test)+ assert_nil User.authenticate_by_email(email: email, password: "wrong")+ assert_nil User.authenticate_by_email(email: "[email protected]", password: user_password_test)+ end++ test "authenticate_by_email uses authenticate_by for encrypted rows and unknown emails" do+ User.expects(:authenticate_by).with(email: @user.email, password: "wrong").returns(nil)+ assert_nil User.authenticate_by_email(email: @user.email, password: "wrong")++ User.expects(:authenticate_by).with(email: "[email protected]", password: "x").returns(nil)+ assert_nil User.authenticate_by_email(email: "[email protected]", password: "x")+ end++ test "find_by_email_with_legacy_fallback does not match a row by its stored ciphertext" do+ ciphertext = User.connection.select_value(+ User.sanitize_sql([ "SELECT email FROM users WHERE id = ?", @user.id ])+ )++ assert_nil User.find_by_email_with_legacy_fallback(ciphertext)+ assert_nil User.authenticate_by_email(email: ciphertext, password: user_password_test)+ end++ test "email uniqueness covers legacy plaintext email rows" do+ email = store_legacy_plaintext_email(@user)++ duplicate = User.new(+ family: @user.family,+ email: " #{email.upcase} ",+ password: user_password_test,+ password_confirmation: user_password_test+ )++ assert_not duplicate.valid?+ assert duplicate.errors.of_kind?(:email, :taken)+ end++ test "a legacy plaintext email row stays valid on its own" do+ store_legacy_plaintext_email(@user)++ assert User.find(@user.id).valid?+ end++ test "authenticate_by_email rejects a blank password for legacy plaintext email rows" do+ email = store_legacy_plaintext_email(@user)+ @user.update_column(:password_digest, BCrypt::Password.create(""))++ assert_nil User.authenticate_by_email(email: email, password: "")+ assert_nil User.authenticate_by_email(email: email, password: nil)+ end++ test "authenticate_by_email accepts a whitespace-only password like authenticate_by" do+ email = store_legacy_plaintext_email(@user)+ @user.update_column(:password_digest, BCrypt::Password.create(" "))++ assert_equal @user, User.authenticate_by_email(email: email, password: " ")+ end+test "email must be present" dopotential_user = User.new(diff --git a/test/models/wise_item/importer_test.rb b/test/models/wise_item/importer_test.rbindex 49113804cf..e7c1d4193b 100644--- a/test/models/wise_item/importer_test.rb+++ b/test/models/wise_item/importer_test.rb@@ -2832,7 +2832,8 @@ class WiseItem::ImporterTest < ActiveSupport::TestCaseraise_on: { get_balance_statements: statements_forbidden })- result = WiseItem::Importer.new(@wise_item, wise_provider: provider).import+ # Postgres refuses a NUL only in a plaintext payload; ciphertext stores it.+ result = ActiveRecord::Encryption.without_encryption { WiseItem::Importer.new(@wise_item, wise_provider: provider).import }assert_not result[:success]assert_equal 1, result[:transactions_failed]@@ -2865,7 +2866,8 @@ class WiseItem::ImporterTest < ActiveSupport::TestCaseWiseItem::Importer.new(WiseItem.find(@wise_item.id), wise_provider: provider).importend- refused = import.call([ held.merge("title" => "<strong>Caf\u0000e</strong>") ])+ # Postgres refuses a NUL only in a plaintext payload; ciphertext stores it.+ refused = ActiveRecord::Encryption.without_encryption { import.call([ held.merge("title" => "<strong>Caf\u0000e</strong>") ]) }assert_equal 2, refused[:transactions_failed]assert_empty split_marksdiff --git a/test/test_helper.rb b/test/test_helper.rbindex 88007a11bd..cdccda1076 100644--- a/test/test_helper.rb+++ b/test/test_helper.rb@@ -130,6 +130,15 @@ module ActiveSupport"maybetestpassword817983172"end+ # Writes the email column directly, bypassing encryption, to simulate a+ # row stored before encryption was active and not yet backfilled.+ def store_legacy_plaintext_email(user, email = user.email)+ ActiveRecord::Base.connection.execute(+ ActiveRecord::Base.sanitize_sql([ "UPDATE users SET email = ? WHERE id = ?", email, user.id ])+ )+ end+def uploaded_file(filename:, content_type:, content: "date,amount\n2024-01-01,1\n")tempfile = Tempfile.new([ File.basename(filename, ".*"), File.extname(filename) ])tempfile.binmode