The personal finance app for everyone (by everyone)
Ruby
security: gate plaintext encryption fallback behind a backfill-completion flag (#3221)
GFR1e2003afec36
diff --git a/.github/workflows/pipelock.yml b/.github/workflows/pipelock.ymlindex 0f99b53901..03e518d415 100644--- a/.github/workflows/pipelock.yml+++ b/.github/workflows/pipelock.yml@@ -57,6 +57,14 @@ jobs:- name: Validate Pipelock deployment contractsshell: bash+ env:+ # compose.example.ai.yml intentionally requires SECRET_KEY_BASE with+ # no fallback default (see #3214/#3221) - the old fallback was+ # itself the exact publicly-known value KNOWN_COMPROMISED_SECRET_KEY_BASES+ # guards against. This validation step only renders/lints the+ # compose file, it never boots a container from it, so a throwaway+ # placeholder is fine here - it just needs to be present.+ SECRET_KEY_BASE: ci-validation-placeholder-not-a-real-secretrun: |set -euo pipefaildiff --git a/app/models/binance_item.rb b/app/models/binance_item.rbindex abb0528456..8aefc987a0 100644--- a/app/models/binance_item.rb+++ b/app/models/binance_item.rb@@ -10,6 +10,7 @@ class BinanceItem < ApplicationRecordif encryption_ready?encrypts :api_key, deterministic: trueencrypts :api_secret+ encrypts :raw_payloadendvalidates :name, presence: truediff --git a/app/models/brex_item.rb b/app/models/brex_item.rbindex ab71d52fab..d56d79bbb3 100644--- a/app/models/brex_item.rb+++ b/app/models/brex_item.rb@@ -8,6 +8,7 @@ class BrexItem < ApplicationRecordif encryption_ready?encrypts :token, deterministic: trueencrypts :raw_payload+ encrypts :raw_institution_payloadendvalidates :name, presence: truediff --git a/app/models/coinbase_item.rb b/app/models/coinbase_item.rbindex 45996e1cd2..cb8d014385 100644--- a/app/models/coinbase_item.rb+++ b/app/models/coinbase_item.rb@@ -9,6 +9,8 @@ class CoinbaseItem < ApplicationRecordif encryption_ready?encrypts :api_key, deterministic: trueencrypts :api_secret+ encrypts :raw_payload+ encrypts :raw_institution_payloadendvalidates :name, presence: truediff --git a/app/models/coinstats_item.rb b/app/models/coinstats_item.rbindex 6dfaee1410..9a88186d70 100644--- a/app/models/coinstats_item.rb+++ b/app/models/coinstats_item.rb@@ -6,7 +6,11 @@ class CoinstatsItem < ApplicationRecordenum :status, { good: "good", requires_update: "requires_update" }, default: :good# Encrypt sensitive credentials if ActiveRecord encryption is configured- encrypts :api_key, deterministic: true if encryption_ready?+ if encryption_ready?+ encrypts :api_key, deterministic: true+ encrypts :raw_payload+ encrypts :raw_institution_payload+ endvalidates :name, presence: truevalidates :api_key, presence: truediff --git a/app/models/indexa_capital_account.rb b/app/models/indexa_capital_account.rbindex e6d225ecce..2af332b4eb 100644--- a/app/models/indexa_capital_account.rb+++ b/app/models/indexa_capital_account.rb@@ -1,9 +1,16 @@# frozen_string_literal: trueclass IndexaCapitalAccount < ApplicationRecord- include CurrencyNormalizable+ include CurrencyNormalizable, Encryptableinclude IndexaCapitalAccount::DataHelpers+ # Encrypt raw payloads if ActiveRecord encryption is configured+ if encryption_ready?+ encrypts :raw_payload+ encrypts :raw_holdings_payload+ encrypts :raw_activities_payload+ end+belongs_to :indexa_capital_item# Association through account_providersdiff --git a/app/models/indexa_capital_item.rb b/app/models/indexa_capital_item.rbindex cb415962dd..8ca243efa4 100644--- a/app/models/indexa_capital_item.rb+++ b/app/models/indexa_capital_item.rb@@ -9,6 +9,10 @@ class IndexaCapitalItem < ApplicationRecordif encryption_ready?encrypts :password, deterministic: trueencrypts :api_token, deterministic: true+ encrypts :username+ encrypts :document+ encrypts :raw_payload+ encrypts :raw_institution_payloadendvalidates :name, presence: truediff --git a/app/models/mercury_item.rb b/app/models/mercury_item.rbindex b4c4ed0a5e..4bb65214c0 100644--- a/app/models/mercury_item.rb+++ b/app/models/mercury_item.rb@@ -6,6 +6,8 @@ class MercuryItem < ApplicationRecord# Encrypt sensitive credentials if ActiveRecord encryption is configuredif encryption_ready?encrypts :token, deterministic: true+ encrypts :raw_payload+ encrypts :raw_institution_payloadendvalidates :name, presence: truediff --git a/app/models/onchain_wallet_account.rb b/app/models/onchain_wallet_account.rbindex b0e84fc386..50dcbfa6a5 100644--- a/app/models/onchain_wallet_account.rb+++ b/app/models/onchain_wallet_account.rb@@ -4,6 +4,14 @@# three partial indexes — one per asset kind — because a native coin is# identified by its address while a token is identified by its contract.class OnchainWalletAccount < ApplicationRecord+ include Encryptable++ # Encrypt raw payloads if ActiveRecord encryption is configured+ if encryption_ready?+ encrypts :raw_payload+ encrypts :raw_movements_payload+ end+belongs_to :onchain_wallet_itemhas_one :account_provider, as: :provider, dependent: :destroydiff --git a/app/models/setting.rb b/app/models/setting.rbindex dbe567d7e1..085045cc36 100644--- a/app/models/setting.rb+++ b/app/models/setting.rb@@ -50,6 +50,16 @@ class Setting < RailsSettings::Basefield :brand_fetch_client_id, type: :string, default: ENV["BRAND_FETCH_CLIENT_ID"]field :brand_fetch_high_res_logos, type: :boolean, default: ENV.fetch("BRAND_FETCH_HIGH_RES_LOGOS", "false") == "true"+ # Set by `bin/rails security:backfill_encryption` once every model/field it+ # covers has been re-encrypted with zero failures. Read at boot (see+ # ActiveRecordEncryptionConfig.backfill_completed?) to decide whether the+ # legacy-plaintext fallback (support_unencrypted_data/extend_queries in+ # config/initializers/active_record_encryption.rb) is still needed.+ # Versioned rather than a plain boolean so that a *future* expansion of the+ # backfill task's model coverage doesn't get silently skipped for installs+ # that completed a backfill under an older, narrower version.+ field :encryption_backfill_completed_version, type: :integer, default: 0+BRAND_FETCH_LOGO_SIZE_STANDARD = 40BRAND_FETCH_LOGO_SIZE_HIGH_RES = 120# Matches both legacy single-segment URLs (`/apple.com/icon/...`) anddiff --git a/app/models/snaptrade_item.rb b/app/models/snaptrade_item.rbindex 3b76f240a3..77d6fadf59 100644--- a/app/models/snaptrade_item.rb+++ b/app/models/snaptrade_item.rb@@ -13,6 +13,8 @@ class SnaptradeItem < ApplicationRecordencrypts :snaptrade_user_secretencrypts :oauth_access_tokenencrypts :oauth_refresh_token+ encrypts :raw_payload+ encrypts :raw_institution_payloadendvalidates :name, presence: truediff --git a/app/models/sophtron_account.rb b/app/models/sophtron_account.rbindex 8bbf5a3826..6da477e9a6 100644--- a/app/models/sophtron_account.rb+++ b/app/models/sophtron_account.rb@@ -19,7 +19,13 @@# @attr [String, nil] balance_sign_override Credit card meaning: "credit", "debt", or nil for automatic# @attr [Boolean, nil] lender_signed Feed sign convention detected when the override is savedclass SophtronAccount < ApplicationRecord- include CurrencyNormalizable+ include CurrencyNormalizable, Encryptable++ # Encrypt raw payloads if ActiveRecord encryption is configured+ if encryption_ready?+ encrypts :raw_payload+ encrypts :raw_transactions_payload+ endbelongs_to :sophtron_itemdiff --git a/app/models/sophtron_item.rb b/app/models/sophtron_item.rbindex c84d03890f..fde7404a63 100644--- a/app/models/sophtron_item.rb+++ b/app/models/sophtron_item.rb@@ -23,6 +23,10 @@ class SophtronItem < ApplicationRecordif encryption_ready?encrypts :user_id, deterministic: trueencrypts :access_key, deterministic: true+ encrypts :raw_payload+ encrypts :raw_institution_payload+ encrypts :raw_customer_payload+ encrypts :raw_job_payloadendvalidates :name, presence: truediff --git a/compose.example.ai.yml b/compose.example.ai.ymlindex ed4ee9a80f..15ba92aef4 100644--- a/compose.example.ai.yml+++ b/compose.example.ai.yml@@ -70,11 +70,19 @@ x-db-env: &db_envx-rails-env: &rails_env<<: *db_env- SECRET_KEY_BASE: ${SECRET_KEY_BASE:-a7523c3d0ae56415046ad8abae168d71074a79534a7062258f8d1d51ac2f76d3c3bc86d86b6b0b307df30d9a6a90a2066a3fa9e67c5e6f374dbd7dd4e0778e13}- # Optional encryption keys for sensitive data; without them, self-hosted- # instances derive keys from SECRET_KEY_BASE. Set all three or none. Adding- # them to an instance that already has data changes its keys: see- # "Encrypting sensitive data" in docs/hosting/docker.md first.+ # No default: a shared, publicly-known SECRET_KEY_BASE would let anyone+ # 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").+ 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:init+ # Set all three or none. Adding them to an instance that already has data+ # changes its keys: see "Encrypting sensitive data" in docs/hosting/docker.md first.ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY: ${ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY:-}ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY: ${ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY:-}ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT: ${ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT:-}diff --git a/compose.example.yml b/compose.example.ymlindex b9e7d64a04..7fced7da9e 100644--- a/compose.example.yml+++ b/compose.example.yml@@ -49,11 +49,19 @@ x-db-env: &db_envx-rails-env: &rails_env<<: *db_env- SECRET_KEY_BASE: ${SECRET_KEY_BASE:-a7523c3d0ae56415046ad8abae168d71074a79534a7062258f8d1d51ac2f76d3c3bc86d86b6b0b307df30d9a6a90a2066a3fa9e67c5e6f374dbd7dd4e0778e13}- # Optional encryption keys for sensitive data; without them, self-hosted- # instances derive keys from SECRET_KEY_BASE. Set all three or none. Adding- # them to an instance that already has data changes its keys: see- # "Encrypting sensitive data" in docs/hosting/docker.md first.+ # No default: a shared, publicly-known SECRET_KEY_BASE would let anyone+ # 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").+ 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:init+ # Set all three or none. Adding them to an instance that already has data+ # changes its keys: see "Encrypting sensitive data" in docs/hosting/docker.md first.ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY: ${ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY:-}ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY: ${ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY:-}ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT: ${ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT:-}diff --git a/config/initializers/active_record_encryption.rb b/config/initializers/active_record_encryption.rbindex ae0a7dd81b..590098b1bc 100644--- a/config/initializers/active_record_encryption.rb+++ b/config/initializers/active_record_encryption.rb@@ -10,8 +10,73 @@ require Rails.root.join("lib/active_record_encryption_config").to_s# `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+#+# Gated on ActiveRecordEncryptionConfig.backfill_completed? (see #3214)+# instead of being unconditional: leaving this on forever means a plaintext+# value that lands in an encrypted column later - a bug, a bad migration, a+# manual DB edit - would be silently accepted instead of raising, quietly+# undermining the integrity guarantee encryption exists to provide. The flag+# it checks is a versioned Setting, flipped by security:backfill_encryption+# only on a clean (zero-failure), non-dry-run completion, and defaults to+# "not complete" (fallback enabled) whenever it can't be read - fresh+# installs, pre-migration boots, or DB errors - so this preserves the+# original crash-safe behavior for anyone who hasn't backfilled yet.+#+# MUST stay a plain, synchronous call here (not deferred into+# after_initialize or any other lazy hook): ActiveRecord's own+# "active_record_encryption.configuration" railtie initializer registers an+# ActiveSupport.on_load(:active_record_encryption) callback that snapshots+# Rails.application.config.active_record.encryption.* into the real,+# long-lived ActiveRecord::Encryption.config object the FIRST time anything+# touches ActiveRecord::Base's connection (verified empirically: it's the+# ActiveRecord::Base.connection call inside backfill_completed? itself that+# fires this, since establishing a connection pulls in AR's encrypted-type+# machinery). That same connection touch also fires the separate+# ActiveSupport.on_load(:active_record) hook AR's railtie uses to decide,+# ONCE, whether to install ExtendedDeterministicQueries/+# ExtendedDeterministicUniquenessValidator support - based on whatever+# extend_queries was at that moment (still unset, since this all happens+# before this statement gets to set it). Setting+# Rails.application.config.active_record.encryption.* afterwards (below) is+# necessary for anything that reads it directly, but insufficient on its+# own for either of these: ActiveRecord::Encryption.config is patched+# directly so the encryption engine picks up the right value regardless of+# exactly when the snapshot fired, and install_support is called directly+# (idempotent - Module#prepend/include are no-ops if already applied) so+# deterministic queries/uniqueness validations against legacy plaintext+# rows actually work when extend_queries ends up true, instead of silently+# never getting the query-rewriting support installed. Deferring the whole+# block into after_initialize does NOT fix any of this - the snapshot+# always happens before after_initialize runs (also verified empirically) -+# and reading `Setting` (an autoloaded app/* constant) directly here isn't+# possible in the first place: Rails autoloading isn't available yet while+# config/initializers/*.rb are still being evaluated. See the comment on+# ActiveRecordEncryptionConfig.backfill_completed? (lib/+# active_record_encryption_config.rb) for why it reads the `settings` table+# via raw SQL instead.+#+# The same premature-snapshot problem also applies to the actual encryption+# keys (primary_key/deterministic_key/key_derivation_salt) configured further+# below in this file: they're resolved from ENV/SECRET_KEY_BASE/credentials+# AFTER the backfill_completed? call above already fired the snapshot, so+# Rails.application.config.active_record.encryption.* alone would again be+# necessary-but-insufficient - see ActiveRecordEncryptionConfig.apply_keys!,+# used below, which patches ActiveRecord::Encryption.config directly for the+# keys exactly like support_unencrypted_data/extend_queries are patched here.+# (Rails credentials configured in config/application.rb are unaffected: that+# file loads before this initializer runs, so its assignment lands in the+# Rails config before backfill_completed?'s snapshot ever fires.)+encryption_fallback_enabled = !ActiveRecordEncryptionConfig.backfill_completed?+Rails.application.config.active_record.encryption.support_unencrypted_data = encryption_fallback_enabled+Rails.application.config.active_record.encryption.extend_queries = encryption_fallback_enabled+if defined?(ActiveRecord::Encryption)+ ActiveRecord::Encryption.config.support_unencrypted_data = encryption_fallback_enabled+ ActiveRecord::Encryption.config.extend_queries = encryption_fallback_enabled+ if encryption_fallback_enabled+ ActiveRecord::Encryption::ExtendedDeterministicQueries.install_support+ ActiveRecord::Encryption::ExtendedDeterministicUniquenessValidator.install_support+ end+end# KNOWN LIMITATION: extend_queries does not reliably extend deterministic# lookups to match legacy plaintext data for attributes that combine@@ -105,9 +170,9 @@ 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_key- Rails.application.config.active_record.encryption.deterministic_key = deterministic_key- Rails.application.config.active_record.encryption.key_derivation_salt = key_derivation_salt+ ActiveRecordEncryptionConfig.apply_keys!(+ primary_key: primary_key, deterministic_key: deterministic_key, key_derivation_salt: key_derivation_salt+ )elsif Rails.application.config.app_mode.self_hosted? && !Rails.application.credentials.active_record_encryption.present?# For self-hosted instances without credentials or env vars, auto-generate keys# Use SECRET_KEY_BASE as the seed for deterministic key generation@@ -120,8 +185,8 @@ elsif Rails.application.config.app_mode.self_hosted? && !Rails.application.credekey_derivation_salt = Digest::SHA256.hexdigest("#{secret_base}:key_derivation_salt")[0..63]# Configure Active Record encryption- Rails.application.config.active_record.encryption.primary_key = primary_key- Rails.application.config.active_record.encryption.deterministic_key = deterministic_key- Rails.application.config.active_record.encryption.key_derivation_salt = key_derivation_salt+ ActiveRecordEncryptionConfig.apply_keys!(+ primary_key: primary_key, deterministic_key: deterministic_key, key_derivation_salt: key_derivation_salt+ )end# If none of the above conditions are met, credentials from application.rb will be useddiff --git a/config/initializers/encryption_warning.rb b/config/initializers/encryption_warning.rbindex d6cc8afd8e..174b1a8946 100644--- a/config/initializers/encryption_warning.rb+++ b/config/initializers/encryption_warning.rb@@ -8,10 +8,10 @@ require Rails.root.join("lib/active_record_encryption_config").to_sRails.application.config.after_initialize doapp_mode = Rails.application.config.app_mode- # 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).+ # Scoped to self-hosted only: these two warnings are about AR encryption+ # not being configured/backfilled, 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)@@ -23,23 +23,34 @@ Rails.application.config.after_initialize doACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALTGenerate a set with: bin/rails db:encryption:initWARN+ elsif !ActiveRecordEncryptionConfig.backfill_completed?+ Rails.logger.warn(<<~WARN)+ [SECURITY] ActiveRecord Encryption is configured, but+ bin/rails security:backfill_encryption has not completed successfully+ yet. Until it does, legacy plaintext data in encrypted columns is+ still readable via a fallback (support_unencrypted_data/extend_queries+ in config/initializers/active_record_encryption.rb) instead of raising+ - which also means a stray plaintext write (bug, bad migration, manual+ DB edit) would be silently accepted instead of caught. Run+ bin/rails security:backfill_encryption now to close this gap.+ WARNendend# 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.+ # suppressed this check in managed mode too - jjmata caught this):+ # 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/backfilled 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)diff --git a/docs/hosting/docker.md b/docs/hosting/docker.mdindex 5364a34fd7..51fdff727e 100644--- a/docs/hosting/docker.md+++ b/docs/hosting/docker.md@@ -49,12 +49,19 @@ This command will do the following:At this point, you should have `compose.yml` in your directory. It includes an optional `backup` service; see [Backups, upgrades and rollbacks](#backups-upgrades-and-rollbacks).-### Step 3 (optional): Configure your environment+### Step 3 (required): Configure your environment-By default, our `compose.example.yml` file runs without any configuration.-That said, if you would like extra security (important if you're running outside of a local network), you can follow the steps below to set things up.+`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.-If you're running the app locally and don't care much about security, you can skip this step.+#### 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.#### Create your environment file@@ -456,6 +463,12 @@ docker compose pull web worker # Pull the newest image for your tagdocker compose up -d # Restart on the new version; database migrations run automatically```+### Re-encrypting data after an encryption-related update++If 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).++`web` and `worker` read whether the conversion has finished only when they start. The procedure stops both before converting and starts them again afterwards, so they pick up the result.+### Upgrade note: instance-wide settings need a super adminProvider credentials (such as Plaid), the shared AI connection settings (LLM provider, endpoints, API keys and models), sync settings, and the external assistant connection are stored once for the whole instance and apply to every family. On an instance with more than one family, only a `super_admin` can change them. When there is a single family, its admins keep access. Family-scoped choices, such as which assistant a family uses, stay with that family's admins.diff --git a/lib/active_record_encryption_config.rb b/lib/active_record_encryption_config.rbindex a3ce0610fe..1a904b7f18 100644--- a/lib/active_record_encryption_config.rb+++ b/lib/active_record_encryption_config.rb@@ -25,6 +25,101 @@ module ActiveRecordEncryptionConfigkey_derivation_salt].freeze+ # Bump this whenever a model/field is added to the coverage of+ # `bin/rails security:backfill_encryption` (lib/tasks/security_backfill.rake).+ # `backfill_completed?` compares an install's stored+ # Setting.encryption_backfill_completed_version against this value, so+ # bumping it correctly puts installs that completed a backfill under an+ # older, narrower version back into "not complete" until they re-run the+ # task - otherwise the legacy-plaintext fallback would get disabled for+ # models the install's last backfill never actually covered.+ CURRENT_BACKFILL_VERSION = 10++ # Single source of truth for which models/fields security:backfill_encryption+ # covers, keyed by the same symbol the task's `results` hash uses. Model+ # names are strings (not bare constants) and resolved via constantize only+ # from the task itself (after full Rails boot, via its :environment+ # dependency) - this file is `require`d from config/initializers/+ # active_record_encryption.rb, before autoloading is available, so a bare+ # constant reference here would raise NameError at boot.+ #+ # test/lib/tasks/security_backfill_test.rb asserts this stays in exact sync+ # with each model's real `encrypts` declarations, so a future field added+ # to a model's `encrypts` list without a matching manifest update (the+ # SnaptradeAccount#raw_balances_payload gap, previously) fails CI instead+ # of silently shipping a field the backfill - and thus the legacy-plaintext+ # fallback gating - never actually covers. It also requires every model that+ # declares `encrypts` to appear here, so a whole provider can't be left out+ # (Fio, Monobank and Coinspot, previously). Bump CURRENT_BACKFILL_VERSION+ # 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.+ BACKFILL_MANIFEST = {+ users: [ "User", %i[otp_secret email unconfirmed_email first_name last_name] ],+ invitations: [ "Invitation", %i[token email] ],+ invite_codes: [ "InviteCode", %i[token] ],+ mobile_devices: [ "MobileDevice", %i[device_id] ],+ plaid_items: [ "PlaidItem", %i[access_token raw_payload raw_institution_payload] ],+ simplefin_items: [ "SimplefinItem", %i[access_url raw_payload raw_institution_payload] ],+ lunchflow_items: [ "LunchflowItem", %i[api_key raw_payload raw_institution_payload] ],+ enable_banking_items: [ "EnableBankingItem", %i[client_certificate session_id raw_payload raw_institution_payload last_psu_ip] ],+ truelayer_items: [ "TruelayerItem", %i[client_secret access_token refresh_token raw_payload raw_institution_payload] ],+ fio_items: [ "FioItem", %i[token raw_payload raw_institution_payload] ],+ akahu_items: [ "AkahuItem", %i[app_token user_token raw_payload raw_institution_payload] ],+ binance_items: [ "BinanceItem", %i[api_key api_secret raw_payload] ],+ brex_items: [ "BrexItem", %i[token raw_payload raw_institution_payload] ],+ coinbase_items: [ "CoinbaseItem", %i[api_key api_secret raw_payload raw_institution_payload] ],+ coinspot_items: [ "CoinspotItem", %i[api_key api_secret raw_payload] ],+ coinstats_items: [ "CoinstatsItem", %i[api_key raw_payload raw_institution_payload] ],+ ibkr_items: [ "IbkrItem", %i[query_id token raw_payload] ],+ indexa_capital_items: [ "IndexaCapitalItem", %i[password api_token username document raw_payload raw_institution_payload] ],+ kraken_items: [ "KrakenItem", %i[api_key api_secret raw_payload] ],+ mercury_items: [ "MercuryItem", %i[token raw_payload raw_institution_payload] ],+ monobank_items: [ "MonobankItem", %i[access_token raw_payload raw_institution_payload] ],+ onchain_wallet_items: [ "OnchainWalletItem", %i[etherscan_api_key] ],+ questrade_items: [ "QuestradeItem", %i[refresh_token raw_payload raw_institution_payload] ],+ redbark_items: [ "RedbarkItem", %i[api_key raw_payload raw_institution_payload] ],+ snaptrade_items: [ "SnaptradeItem", %i[client_id consumer_key snaptrade_user_secret oauth_access_token oauth_refresh_token raw_payload raw_institution_payload] ],+ sharesight_items: [ "SharesightItem", %i[client_id client_secret] ],+ sophtron_items: [ "SophtronItem", %i[user_id access_key raw_payload raw_institution_payload raw_customer_payload raw_job_payload] ],+ trade_republic_items: [ "TradeRepublicItem", %i[phone_number session_blob pending_login_state] ],+ trading212_items: [ "Trading212Item", %i[api_key api_secret raw_instruments_payload] ],+ up_items: [ "UpItem", %i[access_token raw_payload raw_institution_payload] ],+ wise_items: [ "WiseItem", %i[token raw_payload sca_private_key] ],+ plaid_accounts: [ "PlaidAccount", %i[raw_payload raw_transactions_payload raw_holdings_payload raw_liabilities_payload] ],+ simplefin_accounts: [ "SimplefinAccount", %i[raw_payload raw_transactions_payload raw_holdings_payload] ],+ lunchflow_accounts: [ "LunchflowAccount", %i[raw_payload raw_transactions_payload raw_holdings_payload] ],+ enable_banking_accounts: [ "EnableBankingAccount", %i[raw_payload raw_transactions_payload] ],+ truelayer_accounts: [ "TruelayerAccount", %i[raw_payload raw_transactions_payload] ],+ fio_accounts: [ "FioAccount", %i[raw_payload raw_transactions_payload iban] ],+ snaptrade_accounts: [ "SnaptradeAccount", %i[raw_payload raw_transactions_payload raw_holdings_payload raw_activities_payload raw_balances_payload account_number] ],+ coinbase_accounts: [ "CoinbaseAccount", %i[raw_payload raw_transactions_payload] ],+ coinspot_accounts: [ "CoinspotAccount", %i[raw_payload raw_transactions_payload] ],+ coinstats_accounts: [ "CoinstatsAccount", %i[raw_payload raw_transactions_payload] ],+ mercury_accounts: [ "MercuryAccount", %i[raw_payload raw_transactions_payload] ],+ monobank_accounts: [ "MonobankAccount", %i[raw_payload raw_transactions_payload] ],+ akahu_accounts: [ "AkahuAccount", %i[raw_payload raw_transactions_payload formatted_account] ],+ binance_accounts: [ "BinanceAccount", %i[raw_payload raw_transactions_payload] ],+ brex_accounts: [ "BrexAccount", %i[raw_payload raw_transactions_payload] ],+ ibkr_accounts: [ "IbkrAccount", %i[raw_holdings_payload raw_activities_payload raw_cash_report_payload raw_equity_summary_payload] ],+ indexa_capital_accounts: [ "IndexaCapitalAccount", %i[raw_payload raw_holdings_payload raw_activities_payload] ],+ kraken_accounts: [ "KrakenAccount", %i[raw_payload raw_transactions_payload] ],+ onchain_wallet_accounts: [ "OnchainWalletAccount", %i[raw_payload raw_movements_payload] ],+ questrade_accounts: [ "QuestradeAccount", %i[raw_payload raw_holdings_payload raw_activities_payload raw_balances_payload] ],+ redbark_accounts: [ "RedbarkAccount", %i[raw_payload raw_transactions_payload raw_account_details_payload] ],+ sharesight_accounts: [ "SharesightAccount", %i[raw_payload raw_holdings_payload raw_trades_payload raw_payouts_payload raw_cash_transactions_payload] ],+ sophtron_accounts: [ "SophtronAccount", %i[raw_payload raw_transactions_payload] ],+ trade_republic_accounts: [ "TradeRepublicAccount", %i[raw_positions_payload raw_timeline_payload] ],+ trading212_accounts: [ "Trading212Account", %i[raw_positions_payload raw_orders_payload raw_dividends_payload raw_transactions_payload] ],+ up_accounts: [ "UpAccount", %i[raw_payload raw_transactions_payload] ],+ wise_accounts: [ "WiseAccount", %i[raw_payload raw_transactions_payload] ],+ api_keys: [ "ApiKey", %i[display_key] ],+ sso_providers: [ "SsoProvider", %i[client_secret] ],+ sso_identity_blocks: [ "SsoIdentityBlock", %i[identity_label] ],+ security_audit_logs: [ "SecurityAuditLog", %i[user_email ip_address user_agent] ]+ }.freeze+module_functiondef complete_env?(env = ENV)@@ -112,6 +207,30 @@ module ActiveRecordEncryptionConfigfalseend+ # Applies a resolved set of AR encryption keys to both the Rails config+ # object (for anything that reads it directly, e.g. runtime_configured?)+ # AND, if it's already been initialized, the live ActiveRecord::Encryption+ # engine config - mirroring the same belt-and-suspenders pattern this file+ # documents for support_unencrypted_data/extend_queries in config/+ # initializers/active_record_encryption.rb. Necessary because touching+ # ActiveRecord::Base.connection (as backfill_completed? does, earlier in+ # that same initializer) fires AR's one-time on_load(:active_record_+ # encryption_configuration) snapshot into ActiveRecord::Encryption.config+ # before these keys are known - Rails.application.config.active_record.+ # encryption.* alone is therefore insufficient; the engine itself needs+ # patching directly regardless of when that snapshot fired.+ def apply_keys!(primary_key:, deterministic_key:, key_derivation_salt:, config: Rails.application.config.active_record.encryption)+ config.primary_key = primary_key+ config.deterministic_key = deterministic_key+ config.key_derivation_salt = key_derivation_salt++ return unless defined?(ActiveRecord::Encryption)++ ActiveRecord::Encryption.config.primary_key = primary_key+ ActiveRecord::Encryption.config.deterministic_key = deterministic_key+ ActiveRecord::Encryption.config.key_derivation_salt = key_derivation_salt+ end+def explicitly_configured?complete_env? || credentials_configured?end@@ -142,4 +261,63 @@ module ActiveRecordEncryptionConfigdef env_value_present?(env, key)env[key].present?end++ # Whether `bin/rails security:backfill_encryption` has completed, cleanly,+ # against the current CURRENT_BACKFILL_VERSION's model/field coverage.+ #+ # Checked at boot in config/initializers/active_record_encryption.rb via a+ # PLAIN (non-deferred) call: ActiveRecord's own "active_record_encryption.+ # configuration" railtie initializer reads+ # Rails.application.config.active_record.encryption.* into the actual+ # ActiveRecord::Encryption.config object once, synchronously, in between+ # config/initializers running and Rails.application.config.after_initialize+ # firing - so setting support_unencrypted_data/extend_queries from inside+ # after_initialize (or any other deferred hook) is silently too late and+ # has no effect on real encryption behavior (verified empirically; this+ # method must stay callable synchronously at initializer time).+ #+ # That timing rules out using the `Setting` model directly: Setting is an+ # autoloaded app/* constant, and Rails autoloading isn't available yet+ # while config/initializers/*.rb are still being evaluated (referencing+ # any app/models class there raises `NameError: uninitialized constant`,+ # unconditionally - not just when the DB/table is missing). So this reads+ # the same `settings` table RailsSettings::Base uses directly via SQL,+ # sidestepping autoloading entirely while keeping the synchronous timing+ # `active_record_encryption.rb` depends on.+ #+ # This also runs before the backfill task can possibly have run on a fresh+ # install - and before the `settings` table is guaranteed to exist at all+ # (first `db:create`, asset precompile without a DB, etc). `false` is the+ # safe default in every one of those cases: it keeps the legacy-plaintext+ # fallback enabled, matching this app's pre-gating behavior, rather than+ # risking ActiveRecord::Encryption::Errors::Decryption on boot.+ #+ # Image builds run `assets:precompile` with SECRET_KEY_BASE_DUMMY and often+ # without a reachable database; skipping the query there avoids waiting on+ # a connection timeout for a value the build never uses.+ def backfill_completed?(required_version: CURRENT_BACKFILL_VERSION, env: ENV)+ return false if env["SECRET_KEY_BASE_DUMMY"].present?++ raw_value = ActiveRecord::Base.connection.select_value(+ "SELECT value FROM settings WHERE var = 'encryption_backfill_completed_version' LIMIT 1"+ )+ return false if raw_value.nil?++ # safe_load, not unsafe_load/load: raw_value comes from a raw SQL read of+ # a DB row (see comment above - this deliberately bypasses the Setting+ # model), so it must be treated as untrusted input. unsafe_load can+ # instantiate arbitrary Ruby objects from crafted YAML (CWE-502); anyone+ # who can write to this row (compromised DB credentials, SQLi elsewhere,+ # a bad manual edit) could otherwise get code execution at boot. The+ # value is always a plain serialized Integer, which Psych's default+ # safe_load permitted classes (Numeric, String, ...) already cover -+ # no permitted_classes/aliases expansion needed.+ stored_version = YAML.safe_load(raw_value)+ return false unless stored_version.is_a?(Integer)++ stored_version >= required_version+ rescue ActiveRecord::NoDatabaseError, ActiveRecord::ConnectionNotEstablished, ActiveRecord::StatementInvalid, Psych::Exception => e+ Rails.logger.warn("[ActiveRecordEncryptionConfig] Could not read encryption backfill status (#{e.class}); defaulting to fallback-enabled") if defined?(Rails.logger) && Rails.logger+ false+ endenddiff --git a/lib/generators/provider/family/templates/account_model.rb.tt b/lib/generators/provider/family/templates/account_model.rb.ttindex a2fc4bc5f8..16707b842c 100644--- a/lib/generators/provider/family/templates/account_model.rb.tt+++ b/lib/generators/provider/family/templates/account_model.rb.tt@@ -1,9 +1,21 @@# frozen_string_literal: trueclass <%= class_name %>Account < ApplicationRecord- include CurrencyNormalizable+ include CurrencyNormalizable, Encryptableinclude <%= class_name %>Account::DataHelpers+ # Encrypt raw provider payloads if ActiveRecord encryption is configured+ if encryption_ready?+ encrypts :raw_payload+<% if banking_provider? -%>+ encrypts :raw_transactions_payload+<% end -%>+<% if investment_provider? -%>+ encrypts :raw_holdings_payload+ encrypts :raw_activities_payload+<% end -%>+ end+belongs_to :<%= file_name %>_item# Association through account_providersdiff --git a/lib/generators/provider/family/templates/item_model.rb.tt b/lib/generators/provider/family/templates/item_model.rb.ttindex 3895cbeb3e..5d829d188c 100644--- a/lib/generators/provider/family/templates/item_model.rb.tt+++ b/lib/generators/provider/family/templates/item_model.rb.tt@@ -12,11 +12,14 @@ class <%= class_name %>Item < ApplicationRecordenum :status, { good: "good", requires_update: "requires_update" }, default: :good- # Encrypt sensitive credentials if ActiveRecord encryption is configured+ # Encrypt sensitive credentials and raw provider payloads if ActiveRecord+ # encryption is configuredif encryption_ready?<% parsed_fields.select { |f| f[:secret] }.each do |field| -%>encrypts :<%= field[:name] %>, deterministic: true<% end -%>+ encrypts :raw_payload+ encrypts :raw_institution_payloadendvalidates :name, presence: truediff --git a/lib/generators/provider/global/templates/global_account_model.rb.tt b/lib/generators/provider/global/templates/global_account_model.rb.ttindex 69eae09a50..c2ef2fe0ba 100644--- a/lib/generators/provider/global/templates/global_account_model.rb.tt+++ b/lib/generators/provider/global/templates/global_account_model.rb.tt@@ -1,5 +1,11 @@class <%= class_name %>Account < ApplicationRecord- include CurrencyNormalizable+ include CurrencyNormalizable, Encryptable++ # Encrypt raw provider payloads if ActiveRecord encryption is configured+ if encryption_ready?+ encrypts :raw_payload+ encrypts :raw_transactions_payload+ endbelongs_to :<%= file_name %>_itemdiff --git a/lib/generators/provider/global/templates/global_item_model.rb.tt b/lib/generators/provider/global/templates/global_item_model.rb.ttindex 917372305f..dadc225343 100644--- a/lib/generators/provider/global/templates/global_item_model.rb.tt+++ b/lib/generators/provider/global/templates/global_item_model.rb.tt@@ -1,8 +1,14 @@class <%= class_name %>Item < ApplicationRecord- include Syncable, Provided, DestroyableLater+ include Syncable, Provided, Encryptable, DestroyableLaterenum :status, { good: "good", requires_update: "requires_update" }, default: :good+ # Encrypt raw provider payloads if ActiveRecord encryption is configured+ if encryption_ready?+ encrypts :raw_payload+ encrypts :raw_institution_payload+ end+validates :name, presence: truebelongs_to :familydiff --git a/lib/tasks/security_backfill.rake b/lib/tasks/security_backfill.rakeindex 364e71cd8e..1501bdd10d 100644--- a/lib/tasks/security_backfill.rake+++ b/lib/tasks/security_backfill.rake@@ -42,19 +42,37 @@ namespace :security doexit 1end+ # Invalidate any previous completion flag before this run starts (not just+ # on failure at the end): if a prior run already completed successfully+ # and this run then fails or aborts partway through, leaving the old flag+ # in place would let ActiveRecordEncryptionConfig.backfill_completed?+ # report "complete" while this run's still-plaintext rows are unencrypted.+ Setting.encryption_backfill_completed_version = nil unless dry_run+results = {}puts "Starting security backfill (dry_run: #{dry_run}, batch_size: #{batch_size})..."- # Every model that declares `encrypts`, found at runtime so a provider- # added later is covered without editing this task. A model left out would- # keep plaintext rows that raise on every read once the keys are live.- encrypted_models_for_backfill.each do |model_class|- results[model_class.table_name.to_sym] =- backfill_model(model_class, model_class.encrypted_attributes.to_a, batch_size, dry_run)+ # Field lists live in ActiveRecordEncryptionConfig::BACKFILL_MANIFEST+ # (lib/active_record_encryption_config.rb), kept in sync with each model's+ # `encrypts` declarations by test/lib/tasks/security_backfill_test.rb.+ ActiveRecordEncryptionConfig::BACKFILL_MANIFEST.each do |key, (model_class_name, fields)|+ results[key] = backfill_model(model_class_name.constantize, fields, batch_size, dry_run)end+ results[:sessions] = backfill_model(Session, Session.encrypted_attributes.to_a, batch_size, dry_run)results[:session_ip_digests] = backfill_session_ip_digests(batch_size, dry_run)+ all_succeeded = results.values.all? { |r| r[:failed_count].zero? }++ # Only mark the backfill complete on a clean, non-dry-run pass: a partial+ # failure leaves some rows still plaintext, and flipping the flag would+ # disable the legacy-plaintext fallback (config/initializers/+ # active_record_encryption.rb) for models that still need it, turning a+ # readable row into a boot-time ActiveRecord::Encryption::Errors::Decryption.+ if !dry_run && all_succeeded+ Setting.encryption_backfill_completed_version = ActiveRecordEncryptionConfig::CURRENT_BACKFILL_VERSION+ end+# A row that fails here stays unreadable once the app runs with the keys,# so any failure makes the whole run fail.failed_count = results.values.sum { |result| result[:failed_count] }@@ -68,20 +86,6 @@ namespace :security doexit 1 unless failed_count.zero?end- # Concrete base models with encrypted attributes. STI subclasses share their- # base class's table and attributes, so only the base class is listed.- # Classes that aren't reachable by their name (anonymous or ad hoc ones)- # are skipped.- def encrypted_models_for_backfill- Rails.autoloaders.main.eager_load_dir(Rails.root.join("app/models").to_s)-- ApplicationRecord.descendants- .reject(&:abstract_class?)- .select { |model| model.name&.safe_constantize == model }- .select { |model| model.base_class == model && model.encrypted_attributes.present? }- .sort_by(&:name)- end-def backfill_model(model_class, fields, batch_size, dry_run, &filter_block)processed = 0updated = 0diff --git a/test/fixtures/indexa_capital_accounts.yml b/test/fixtures/indexa_capital_accounts.ymlindex b9ff174a96..b68562edad 100644--- a/test/fixtures/indexa_capital_accounts.yml+++ b/test/fixtures/indexa_capital_accounts.yml@@ -10,9 +10,9 @@ mutual_fund:account_status: "active"account_type: "mutual"provider: "Indexa Capital"- raw_payload: {}- raw_holdings_payload: []- raw_activities_payload: []+ raw_payload:+ raw_holdings_payload:+ raw_activities_payload:pension_plan:indexa_capital_item: configured_with_token@@ -24,6 +24,6 @@ pension_plan:account_status: "active"account_type: "pension"provider: "Indexa Capital"- raw_payload: {}- raw_holdings_payload: []- raw_activities_payload: []+ raw_payload:+ raw_holdings_payload:+ raw_activities_payload:diff --git a/test/initializers/active_record_encryption_test.rb b/test/initializers/active_record_encryption_test.rbindex ba77041db4..b3e86cc437 100644--- a/test/initializers/active_record_encryption_test.rb+++ b/test/initializers/active_record_encryption_test.rb@@ -3,6 +3,14 @@require "test_helper"class ActiveRecordEncryptionInitializerTest < ActiveSupport::TestCase+ # Both settings are gated on ActiveRecordEncryptionConfig.backfill_completed?+ # (see #3214) instead of being unconditionally on. They're expected to be+ # `true` here because the initializer runs once at boot, before this test+ # (or any test) can flip Setting.encryption_backfill_completed_version -+ # the test suite always boots in the "backfill not completed" state.+ # Coverage for the gating logic itself (both the "complete" and+ # "not complete" branches) lives in test/lib/active_record_encryption_config_test.rb,+ # since re-running the initializer per-test isn't possible.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@@ -16,6 +24,21 @@ class ActiveRecordEncryptionInitializerTest < ActiveSupport::TestCaseassert Rails.application.config.active_record.encryption.extend_queriesend+ # jjmata flagged that ExtendedDeterministicQueries/+ # ExtendedDeterministicUniquenessValidator (called directly in+ # config/initializers/active_record_encryption.rb - see its comment for+ # why the public extend_queries config flag alone isn't enough) are+ # undocumented Rails internals, not part of the public config surface. A+ # routine Rails patch/minor bump that renames or removes `install_support`+ # would otherwise raise NameError/NoMethodError synchronously at boot for+ # every self-hosted install still in the pre-backfill fallback window,+ # discovered in production rather than here. This turns that into a named,+ # obvious test failure instead.+ test "the private Rails APIs extend_queries depends on still exist" do+ assert_respond_to ActiveRecord::Encryption::ExtendedDeterministicQueries, :install_support+ assert_respond_to ActiveRecord::Encryption::ExtendedDeterministicUniquenessValidator, :install_support+ end+test "reads a legacy plaintext string value without raising" doskip "Encryption not configured" unless User.encryption_ready?diff --git a/test/lib/active_record_encryption_config_test.rb b/test/lib/active_record_encryption_config_test.rbindex bf672dcdcf..1302ed9888 100644--- a/test/lib/active_record_encryption_config_test.rb+++ b/test/lib/active_record_encryption_config_test.rb@@ -57,6 +57,55 @@ class ActiveRecordEncryptionConfigTest < ActiveSupport::TestCasecredentials = 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++ # 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++ 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++ test "apply_keys! copies keys onto both the given config and the live ActiveRecord::Encryption engine" do+ ActiveRecord::Encryption.config.expects(:primary_key=).with("pk")+ ActiveRecord::Encryption.config.expects(:deterministic_key=).with("dk")+ ActiveRecord::Encryption.config.expects(:key_derivation_salt=).with("salt")++ rails_config = OpenStruct.new++ ActiveRecordEncryptionConfig.apply_keys!(+ primary_key: "pk", deterministic_key: "dk", key_derivation_salt: "salt", config: rails_config+ )++ assert_equal "pk", rails_config.primary_key+ assert_equal "dk", rails_config.deterministic_key+ assert_equal "salt", rails_config.key_derivation_saltendtest "explicit configuration excludes runtime generated config" do@@ -98,44 +147,69 @@ class ActiveRecordEncryptionConfigTest < ActiveSupport::TestCaseassert 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)+ test "backfill_completed? is false before any backfill has run" do+ Setting.encryption_backfill_completed_version = 0- 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"+ refute ActiveRecordEncryptionConfig.backfill_completed?end- test "does not treat absent encryption credentials as partial" do- credentials = OpenStruct.new(active_record_encryption: nil)+ test "backfill_completed? is true once the stored version meets the required version" do+ Setting.encryption_backfill_completed_version = ActiveRecordEncryptionConfig::CURRENT_BACKFILL_VERSION- refute ActiveRecordEncryptionConfig.credentials_configured?(credentials)- refute ActiveRecordEncryptionConfig.partial_credentials?(credentials)+ assert ActiveRecordEncryptionConfig.backfill_completed?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)+ test "backfill_completed? is false when the stored version predates a coverage expansion" do+ # Simulates an install that completed a backfill under an older, narrower+ # CURRENT_BACKFILL_VERSION before upgrading to code that covers more+ # models/fields - it must not be treated as complete until it re-runs+ # the task, or the fallback gets disabled for newly-covered models that+ # were never actually backfilled.+ Setting.encryption_backfill_completed_version = 1- assert ActiveRecordEncryptionConfig.credentials_configured?(credentials)- refute ActiveRecordEncryptionConfig.partial_credentials?(credentials)+ refute ActiveRecordEncryptionConfig.backfill_completed?(required_version: 2)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)+ test "backfill_completed? skips the database during asset builds" do+ Setting.encryption_backfill_completed_version = ActiveRecordEncryptionConfig::CURRENT_BACKFILL_VERSION+ ActiveRecord::Base.connection.expects(:select_value).never- refute ActiveRecordEncryptionConfig.credentials_configured?(credentials)- assert ActiveRecordEncryptionConfig.partial_credentials?(credentials)- assert_equal ActiveRecordEncryptionConfig::CONFIG_KEYS, ActiveRecordEncryptionConfig.missing_credential_keys(credentials)+ refute ActiveRecordEncryptionConfig.backfill_completed?(env: { "SECRET_KEY_BASE_DUMMY" => "1" })+ end++ test "backfill_completed? defaults to false when the settings table can't be read" do+ # backfill_completed? deliberately bypasses the Setting model (see its+ # comment for why) and queries the settings table directly via+ # ActiveRecord::Base.connection.select_value - stubbing Setting itself,+ # as a previous version of this test did, never exercises the real+ # rescue path at all since that method is never called.+ ActiveRecord::Base.connection.stubs(:select_value).raises(ActiveRecord::StatementInvalid, "relation \"settings\" does not exist")++ refute ActiveRecordEncryptionConfig.backfill_completed?+ end++ test "backfill_completed? defaults to false when the stored value isn't a YAML-serialized Integer" do+ ActiveRecord::Base.connection.stubs(:select_value).returns("not_an_integer")++ refute ActiveRecordEncryptionConfig.backfill_completed?+ end++ test "backfill_completed? defaults to false when the stored value is malformed YAML" do+ ActiveRecord::Base.connection.stubs(:select_value).raises(Psych::Exception, "malformed yaml")++ refute ActiveRecordEncryptionConfig.backfill_completed?+ end++ test "backfill_completed? does not deserialize disallowed Ruby objects from the stored value (CWE-502)" do+ # Regression test for using YAML.unsafe_load/YAML.load on this raw,+ # attacker-reachable DB value (compromised DB credentials, SQLi+ # elsewhere, a bad manual edit): a crafted YAML payload naming an+ # arbitrary Ruby class must be rejected by safe_load's default+ # permitted-classes check, not instantiated.+ malicious_yaml = "--- !ruby/object:OpenStruct {}\n"+ ActiveRecord::Base.connection.stubs(:select_value).returns(malicious_yaml)++ refute ActiveRecordEncryptionConfig.backfill_completed?end# Regression coverage for jjmata's review on #3189: the boot check used todiff --git a/test/lib/generators/provider/family_generator_test.rb b/test/lib/generators/provider/family_generator_test.rbindex 2c0f512e05..7fed5dc371 100644--- a/test/lib/generators/provider/family_generator_test.rb+++ b/test/lib/generators/provider/family_generator_test.rb@@ -346,6 +346,36 @@ class Provider::FamilyGeneratorTest < ActiveSupport::TestCaseassert_includes Provider::FamilyGenerator::RESERVED_ITEM_COLUMNS, "institution_id"end+ # Every hand-written *_item.rb / *_account.rb model in app/models encrypts its raw+ # provider payload columns (they hold full API responses, which can contain secrets).+ # These templates generate the starting point for every *new* provider, so a gap here+ # means every future provider ships with unencrypted payloads until someone notices.+ def template_path(name)+ File.expand_path("../../../../../lib/generators/provider/family/templates/#{name}", __FILE__)+ end++ test "item model template encrypts raw_payload and raw_institution_payload" do+ template = File.read(template_path("item_model.rb.tt"))+ encryption_block = template[/if encryption_ready\?.*?\n end/m]++ assert encryption_block, "expected an `if encryption_ready?` block in item_model.rb.tt"+ assert_includes encryption_block, "encrypts :raw_payload"+ assert_includes encryption_block, "encrypts :raw_institution_payload"+ end++ test "account model template includes Encryptable and encrypts raw payload columns" do+ template = File.read(template_path("account_model.rb.tt"))++ assert_includes template, "Encryptable"+ encryption_block = template[/if encryption_ready\?.*?\n end/m]++ assert encryption_block, "expected an `if encryption_ready?` block in account_model.rb.tt"+ assert_includes encryption_block, "encrypts :raw_payload"+ assert_includes encryption_block, "encrypts :raw_transactions_payload"+ assert_includes encryption_block, "encrypts :raw_holdings_payload"+ assert_includes encryption_block, "encrypts :raw_activities_payload"+ end+# The old templates built opening tags with "<" + and closing ones with "%" + ">".# A string-built closer that ends a multi-line tag breaks the compiled Ruby, so# the parse check catches it, but one standing alone still parses and renders adiff --git a/test/lib/generators/provider/global_generator_test.rb b/test/lib/generators/provider/global_generator_test.rbnew file mode 100644index 0000000000..e0b0371cbf--- /dev/null+++ b/test/lib/generators/provider/global_generator_test.rb@@ -0,0 +1,34 @@+require "test_helper"++# Every hand-written *_item.rb / *_account.rb model in app/models encrypts its raw+# provider payload columns (they hold full API responses, which can contain secrets).+# This template generates the starting point for every *new* global provider, so a gap+# here means every future global provider ships with unencrypted payloads until someone+# notices. Mirrors the equivalent family_generator_test.rb coverage for the family flow.+class Provider::GlobalGeneratorTest < ActiveSupport::TestCase+ def template_path(name)+ File.expand_path("../../../../../lib/generators/provider/global/templates/#{name}", __FILE__)+ end++ test "item model template includes Encryptable and encrypts raw payload columns" do+ template = File.read(template_path("global_item_model.rb.tt"))++ assert_includes template, "Encryptable"+ encryption_block = template[/if encryption_ready\?.*?\n end/m]++ assert encryption_block, "expected an `if encryption_ready?` block in global_item_model.rb.tt"+ assert_includes encryption_block, "encrypts :raw_payload"+ assert_includes encryption_block, "encrypts :raw_institution_payload"+ end++ test "account model template includes Encryptable and encrypts raw payload columns" do+ template = File.read(template_path("global_account_model.rb.tt"))++ assert_includes template, "Encryptable"+ encryption_block = template[/if encryption_ready\?.*?\n end/m]++ assert encryption_block, "expected an `if encryption_ready?` block in global_account_model.rb.tt"+ assert_includes encryption_block, "encrypts :raw_payload"+ assert_includes encryption_block, "encrypts :raw_transactions_payload"+ end+enddiff --git a/test/lib/tasks/security_backfill_test.rb b/test/lib/tasks/security_backfill_test.rbindex 319dd9e3ee..1d3280c803 100644--- a/test/lib/tasks/security_backfill_test.rb+++ b/test/lib/tasks/security_backfill_test.rb@@ -258,8 +258,208 @@ class SecurityBackfillTest < ActiveSupport::TestCaseassert_equal payload, item.reload.raw_payloadend+ test "a clean non-dry-run completion marks the backfill flag complete" do+ Setting.encryption_backfill_completed_version = 0++ capture_io { Rake::Task["security:backfill_encryption"].invoke("500", "false") }++ assert_equal ActiveRecordEncryptionConfig::CURRENT_BACKFILL_VERSION, Setting.encryption_backfill_completed_version+ end++ test "a dry run does not mark the backfill flag complete" do+ Setting.encryption_backfill_completed_version = 0++ capture_io { Rake::Task["security:backfill_encryption"].invoke("500", "true") }++ assert_equal 0, Setting.encryption_backfill_completed_version+ end++ test "a run with failures does not mark the backfill flag complete" do+ Setting.encryption_backfill_completed_version = 0++ item = LunchflowItem.new(family: families(:dylan_family), name: "Backfill Failure Test", api_key: "seed")+ item.save!(validate: false)+ ActiveRecord::Base.connection.execute(ActiveRecord::Base.sanitize_sql([+ "UPDATE lunchflow_items SET api_key = ? WHERE id = ?", "plaintext-key", item.id ]))++ # Force the write phase of this record's backfill to fail so failed_count > 0.+ LunchflowItem.any_instance.stubs(:api_key=).raises(StandardError, "simulated failure")++ invoke_backfill("500", "false")++ assert_equal 0, Setting.encryption_backfill_completed_version+ end++ # Regression test for a gap jjmata flagged: the task computed per-model+ # success correctly (enough to gate the completion flag above) but printed+ # a hardcoded ok: true and always exited zero regardless, so an operator or+ # deployment script checking only the exit code - not hand-parsing the JSON+ # - would believe a partially-failed backfill fully succeeded.+ test "a run with failures reports ok: false and exits non-zero" do+ item = LunchflowItem.new(family: families(:dylan_family), name: "Backfill Exit Status Test", api_key: "seed")+ item.save!(validate: false)+ ActiveRecord::Base.connection.execute(ActiveRecord::Base.sanitize_sql([+ "UPDATE lunchflow_items SET api_key = ? WHERE id = ?", "plaintext-key", item.id ]))++ LunchflowItem.any_instance.stubs(:api_key=).raises(StandardError, "simulated failure")++ out, _err, exit_status = invoke_backfill("500", "false")++ assert_equal 1, exit_status, "a failed backfill must exit non-zero so automation can detect it"+ assert_equal false, JSON.parse(out.lines.last)["ok"], "a failed backfill must report ok: false, not a blanket success"+ end++ test "a clean run reports ok: true and exits zero" do+ out, _err, exit_status = invoke_backfill("500", "true")++ assert_nil exit_status, "a successful (or dry) run must not exit the process"+ assert_equal true, JSON.parse(out.lines.last)["ok"]+ end++ # Regression test for a gap CodeRabbit flagged: without invalidating the flag+ # up front, a *previously completed* backfill's flag would survive a later+ # failed run untouched, letting ActiveRecordEncryptionConfig.backfill_completed?+ # keep reporting "complete" while this run's still-plaintext rows sit unencrypted.+ test "a run with failures invalidates a previously-set completion flag" do+ Setting.encryption_backfill_completed_version = ActiveRecordEncryptionConfig::CURRENT_BACKFILL_VERSION++ item = LunchflowItem.new(family: families(:dylan_family), name: "Backfill Reinvalidate Test", api_key: "seed")+ item.save!(validate: false)+ ActiveRecord::Base.connection.execute(ActiveRecord::Base.sanitize_sql([+ "UPDATE lunchflow_items SET api_key = ? WHERE id = ?", "plaintext-key", item.id ]))++ LunchflowItem.any_instance.stubs(:api_key=).raises(StandardError, "simulated failure")++ invoke_backfill("500", "false")++ assert_equal 0, Setting.encryption_backfill_completed_version+ end++ # Regression test for a gap Codex flagged: SnaptradeAccount#raw_balances_payload+ # is an encrypted column (app/models/snaptrade_account.rb) but was missing from+ # this task's field list, so upgraded installs with plaintext balance data would+ # get marked "backfill complete" while that column was still readable-but-raw -+ # and once support_unencrypted_data turns off, reads of it raise.+ test "backfills SnaptradeAccount#raw_balances_payload" do+ account = snaptrade_accounts(:fidelity_401k)+ ActiveRecord::Base.connection.execute(ActiveRecord::Base.sanitize_sql([+ "UPDATE snaptrade_accounts SET raw_balances_payload = ?::jsonb WHERE id = ?",+ [ { "currency" => "USD", "cash" => 1500.0 } ].to_json, account.id ]))++ capture_io { Rake::Task["security:backfill_encryption"].invoke("500", "false") }++ account.reload+ assert_kind_of Array, account.raw_balances_payload+ assert_equal "USD", account.raw_balances_payload.first["currency"]+ at_rest = account.read_attribute_before_type_cast(:raw_balances_payload).to_s+ refute_includes at_rest, "1500.0"+ end++ test "backfills plaintext FioAccount IBAN" do+ account = fio_accounts(:checking)+ ActiveRecord::Base.connection.execute(ActiveRecord::Base.sanitize_sql([+ "UPDATE fio_accounts SET iban = ? WHERE id = ?", "CZ-PLAINTEXT-IBAN", account.id ]))++ capture_io { Rake::Task["security:backfill_encryption"].invoke("500", "false") }++ assert_equal "CZ-PLAINTEXT-IBAN", account.reload.iban+ refute_includes account.read_attribute_before_type_cast(:iban).to_s, "CZ-PLAINTEXT-IBAN"+ end++ # Pins the manifest's content to CURRENT_BACKFILL_VERSION: a manifest change+ # without a version bump would leave installs that completed the previous+ # backfill marked "complete", turning off the plaintext fallback for fields+ # their backfill never touched. On a deliberate change, bump the version and+ # add its digest here.+ BACKFILL_MANIFEST_DIGESTS = {+ 4 => "9630168637fae661a583b828adb447e990416c8eae8b5f12eeaf1dad428acfb2",+ 5 => "aef59eef15fde2bc5f8e12079235e86b586564755fa86f7459c7fd087c27ce71",+ 6 => "8a7848cc0f0f829ebf0c9a54d349640696bb4e24f7f1e1e4b8bd5827e6f1fdd1",+ 7 => "362ec2acfad421eaf6299bdeae78d859e13f8d4a65b6a3e615a80b274219698a",+ 8 => "a4d113aa214e8754361484267d377174b2aeda3fe01c5ca0c553f9ab76ef2ab0",+ 9 => "9f814939a5125a6903d9ba4e96392056ffafe9f6110b10b5c1cae0d87a564ac7",+ 10 => "0bcaa72ed675acde5d5ae2ce72305bf73375c0faa5580fe80e3985e88aa4f9e4"+ }.freeze++ test "backfill manifest changes come with a CURRENT_BACKFILL_VERSION bump" do+ digest = Digest::SHA256.hexdigest(ActiveRecordEncryptionConfig::BACKFILL_MANIFEST.sort.to_h.to_json)++ assert_equal BACKFILL_MANIFEST_DIGESTS[ActiveRecordEncryptionConfig::CURRENT_BACKFILL_VERSION], digest,+ "BACKFILL_MANIFEST changed - bump CURRENT_BACKFILL_VERSION and record the new digest (#{digest})"+ end++ test "covers every provider item and account model, not just the original subset" do+ out, _err = capture_io { Rake::Task["security:backfill_encryption"].invoke("500", "true") }+ results = JSON.parse(out.lines.last)["results"]++ # Sanity check for models that were missing from this task's coverage+ # entirely before this change (would leave plaintext data with no+ # remediation path even after the encryption_ready? gating bug is fixed).+ %w[+ akahu_items binance_items brex_items coinbase_items coinspot_items coinstats_items+ fio_items ibkr_items indexa_capital_items kraken_items mercury_items monobank_items+ onchain_wallet_items questrade_items redbark_items snaptrade_items+ sophtron_items trade_republic_items trading212_items up_items wise_items+ akahu_accounts binance_accounts brex_accounts coinspot_accounts fio_accounts ibkr_accounts+ indexa_capital_accounts kraken_accounts monobank_accounts onchain_wallet_accounts+ questrade_accounts redbark_accounts sophtron_accounts trade_republic_accounts+ trading212_accounts up_accounts wise_accounts+ api_keys sso_providers sso_identity_blocks+ ].each do |key|+ assert results.key?(key), "expected security:backfill_encryption to cover #{key}"+ end+ end++ # Regression test for a gap jjmata flagged: the previous test above only+ # checked that a `results` key exists for each of a hand-picked subset of+ # models, not that the *fields* backfilled for a model exactly match what+ # it actually `encrypts` - so a new encrypted field added to a model+ # without a matching manifest update (exactly the SnaptradeAccount#+ # raw_balances_payload gap fixed elsewhere in this file) would stay green+ # here forever. This asserts exact parity for every model in the manifest.+ test "backfill manifest exactly matches each model's encrypted attributes" do+ ActiveRecordEncryptionConfig::BACKFILL_MANIFEST.each do |key, (model_class_name, fields)|+ model_class = model_class_name.constantize++ assert_equal fields.sort, model_class.encrypted_attributes.to_a.sort,+ "#{model_class_name} (results[:#{key}]) has drifted from " \+ "ActiveRecordEncryptionConfig::BACKFILL_MANIFEST - update the manifest " \+ "and bump CURRENT_BACKFILL_VERSION together with whatever changed " \+ "#{model_class_name}'s `encrypts` declarations"+ end+ end++ # The parity test above only checks models already listed in the manifest,+ # so a model that encrypts fields but was never added (Fio, Monobank and+ # Coinspot, previously) passed silently - and once the completed backfill+ # turns off the legacy-plaintext fallback, its old rows raise on read.+ # Session is excluded on purpose, see BACKFILL_MANIFEST's comment.+ test "every model with encrypted attributes is in the backfill manifest" do+ Rails.application.eager_load!++ manifest = ActiveRecordEncryptionConfig::BACKFILL_MANIFEST.values.to_h+ # Named, loadable classes only: anonymous test-only subclasses aren't real models.+ encrypted_models = ApplicationRecord.descendants.select do |model|+ !model.abstract_class? && model.name&.safe_constantize == model && model.encrypted_attributes.present?+ end++ encrypted_models.each do |model|+ next if model.base_class.name == "Session"++ fields = manifest[model.base_class.name]+ assert fields, "#{model.name} encrypts #{model.encrypted_attributes.to_a.sort.inspect} but is missing from " \+ "ActiveRecordEncryptionConfig::BACKFILL_MANIFEST - add it and bump CURRENT_BACKFILL_VERSION"+ assert_empty model.encrypted_attributes.to_a - fields,+ "#{model.name} encrypts fields the backfill manifest does not cover"+ end+ end+private+ def encrypted_models_for_backfill+ ActiveRecordEncryptionConfig::BACKFILL_MANIFEST.values.map { |name, _| name.constantize } + [ Session ]+ end+# Runs the task like an operator would and returns its JSON report. The# task exits 1 when rows fail, which must not end the test process.def run_backfill(dry_run:)@@ -341,4 +541,21 @@ class SecurityBackfillTest < ActiveSupport::TestCaseelse column.array? ? "{}" : "backfill-placeholder-#{SecureRandom.hex(4)}"endend++ # The task now calls `exit 1` on a failed (non-dry-run) invocation.+ # capture_io's own `return` never runs if the block it wraps raises past+ # it, so plain `capture_io { ... invoke ... }` would make out/err+ # unreachable for a failing run - rescue inside the block instead, so+ # stdout is still captured and the exit status is still observable.+ def invoke_backfill(*args)+ exit_status = nil+ out, err = capture_io do+ begin+ Rake::Task["security:backfill_encryption"].invoke(*args)+ rescue SystemExit => e+ exit_status = e.status+ end+ end+ [ out, err, exit_status ]+ endenddiff --git a/test/models/binance_item_test.rb b/test/models/binance_item_test.rbindex c9a03bf31a..e4dc031669 100644--- a/test/models/binance_item_test.rb+++ b/test/models/binance_item_test.rb@@ -108,4 +108,13 @@ class BinanceItemTest < ActiveSupport::TestCaseassert_equal 1, @item.linked_accounts_countend++ test "declares credentials and raw payload as encrypted" do+ skip "Encryption not configured" unless BinanceItem.encryption_ready?++ encrypted = BinanceItem.encrypted_attributes.map(&:to_s)+ assert_includes encrypted, "api_key"+ assert_includes encrypted, "api_secret"+ assert_includes encrypted, "raw_payload"+ endenddiff --git a/test/models/brex_item_test.rb b/test/models/brex_item_test.rbindex 9d454b2fd4..cc850d1fe6 100644--- a/test/models/brex_item_test.rb+++ b/test/models/brex_item_test.rb@@ -104,8 +104,10 @@ class BrexItemTest < ActiveSupport::TestCasetest "declares Brex token and raw payload as encrypted" doskip "Encryption not configured" unless BrexItem.encryption_ready?- assert_includes BrexItem.encrypted_attributes.map(&:to_s), "token"- assert_includes BrexItem.encrypted_attributes.map(&:to_s), "raw_payload"+ encrypted = BrexItem.encrypted_attributes.map(&:to_s)+ assert_includes encrypted, "token"+ assert_includes encrypted, "raw_payload"+ assert_includes encrypted, "raw_institution_payload"endtest "resolve for returns explicit credentialed item scoped to family" dodiff --git a/test/models/coinbase_item_test.rb b/test/models/coinbase_item_test.rbindex 25085432ba..83bbd3eb42 100644--- a/test/models/coinbase_item_test.rb+++ b/test/models/coinbase_item_test.rb@@ -224,4 +224,14 @@ class CoinbaseItemTest < ActiveSupport::TestCaseassert_equal I18n.t("coinbase_items.coinbase_item.sync_status.partial_sync", linked_count: 1, unlinked_count: 1), @coinbase_item.sync_status_summaryend++ test "declares credentials and raw payloads as encrypted" do+ skip "Encryption not configured" unless CoinbaseItem.encryption_ready?++ encrypted = CoinbaseItem.encrypted_attributes.map(&:to_s)+ assert_includes encrypted, "api_key"+ assert_includes encrypted, "api_secret"+ assert_includes encrypted, "raw_payload"+ assert_includes encrypted, "raw_institution_payload"+ endenddiff --git a/test/models/coinstats_item_test.rb b/test/models/coinstats_item_test.rbindex f4065fb997..502e7fe162 100644--- a/test/models/coinstats_item_test.rb+++ b/test/models/coinstats_item_test.rb@@ -229,9 +229,12 @@ class CoinstatsItemTest < ActiveSupport::TestCaseassert_equal "1 crypto wallets synced, 1 need setup", @coinstats_item.sync_status_summaryend- test "declares api_key as encrypted" do+ test "declares api_key and raw payloads as encrypted" doskip "Encryption not configured" unless CoinstatsItem.encryption_ready?- assert_includes CoinstatsItem.encrypted_attributes.map(&:to_s), "api_key"+ encrypted = CoinstatsItem.encrypted_attributes.map(&:to_s)+ assert_includes encrypted, "api_key"+ assert_includes encrypted, "raw_payload"+ assert_includes encrypted, "raw_institution_payload"endenddiff --git a/test/models/indexa_capital_account_test.rb b/test/models/indexa_capital_account_test.rbindex 7620608b72..ac8bcf60bc 100644--- a/test/models/indexa_capital_account_test.rb+++ b/test/models/indexa_capital_account_test.rb@@ -123,4 +123,13 @@ class IndexaCapitalAccountTest < ActiveSupport::TestCase@account.ensure_account_provider!(linked_account)endend++ test "declares raw payloads as encrypted" do+ skip "Encryption not configured" unless IndexaCapitalAccount.encryption_ready?++ encrypted = IndexaCapitalAccount.encrypted_attributes.map(&:to_s)+ assert_includes encrypted, "raw_payload"+ assert_includes encrypted, "raw_holdings_payload"+ assert_includes encrypted, "raw_activities_payload"+ endenddiff --git a/test/models/indexa_capital_item_test.rb b/test/models/indexa_capital_item_test.rbindex 32cf78d8ad..b075e4f135 100644--- a/test/models/indexa_capital_item_test.rb+++ b/test/models/indexa_capital_item_test.rb@@ -141,10 +141,15 @@ 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+ test "declares credentials and raw payloads as encrypted" doskip "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"+ encrypted = IndexaCapitalItem.encrypted_attributes.map(&:to_s)+ assert_includes encrypted, "password"+ assert_includes encrypted, "api_token"+ assert_includes encrypted, "username"+ assert_includes encrypted, "document"+ assert_includes encrypted, "raw_payload"+ assert_includes encrypted, "raw_institution_payload"endenddiff --git a/test/models/mercury_item_test.rb b/test/models/mercury_item_test.rbindex 6ce4758342..728b7b54b6 100644--- a/test/models/mercury_item_test.rb+++ b/test/models/mercury_item_test.rb@@ -88,9 +88,12 @@ class MercuryItemTest < ActiveSupport::TestCaseassert_instance_of MercuryItem::Syncer, syncerend- test "declares token as encrypted" do+ test "declares token and raw payloads as encrypted" doskip "Encryption not configured" unless MercuryItem.encryption_ready?- assert_includes MercuryItem.encrypted_attributes.map(&:to_s), "token"+ encrypted = MercuryItem.encrypted_attributes.map(&:to_s)+ assert_includes encrypted, "token"+ assert_includes encrypted, "raw_payload"+ assert_includes encrypted, "raw_institution_payload"endenddiff --git a/test/models/onchain_wallet_account_test.rb b/test/models/onchain_wallet_account_test.rbindex f6fd01247f..db5c54fedf 100644--- a/test/models/onchain_wallet_account_test.rb+++ b/test/models/onchain_wallet_account_test.rb@@ -220,4 +220,12 @@ class OnchainWalletAccountTest < ActiveSupport::TestCaseassert_equal [ native.id, token_asset.id ], @item.onchain_wallet_accounts.ordered.map(&:id)end++ test "declares raw payloads as encrypted" do+ skip "Encryption not configured" unless OnchainWalletAccount.encryption_ready?++ encrypted = OnchainWalletAccount.encrypted_attributes.map(&:to_s)+ assert_includes encrypted, "raw_payload"+ assert_includes encrypted, "raw_movements_payload"+ endenddiff --git a/test/models/snaptrade_item_test.rb b/test/models/snaptrade_item_test.rbindex 55b4c69b10..6eff0d0a3f 100644--- a/test/models/snaptrade_item_test.rb+++ b/test/models/snaptrade_item_test.rb@@ -71,5 +71,7 @@ class SnaptradeItemTest < ActiveSupport::TestCaseassert_includes encrypted, "snaptrade_user_secret"assert_includes encrypted, "oauth_access_token"assert_includes encrypted, "oauth_refresh_token"+ assert_includes encrypted, "raw_payload"+ assert_includes encrypted, "raw_institution_payload"endenddiff --git a/test/models/sophtron_account_test.rb b/test/models/sophtron_account_test.rbindex 53af368bb5..2a49832f63 100644--- a/test/models/sophtron_account_test.rb+++ b/test/models/sophtron_account_test.rb@@ -24,6 +24,14 @@ class SophtronAccountTest < ActiveSupport::TestCaseassert_equal "ui-apple", account.institution_metadata["user_institution_id"]end+ test "declares raw payloads as encrypted" do+ skip "Encryption not configured" unless SophtronAccount.encryption_ready?++ encrypted = SophtronAccount.encrypted_attributes.map(&:to_s)+ assert_includes encrypted, "raw_payload"+ assert_includes encrypted, "raw_transactions_payload"+ end+test "database rejects an unsupported balance sign override" doaccount = build_sophtron_accountaccount.balance_sign_override = "unsupported"diff --git a/test/models/sophtron_item_test.rb b/test/models/sophtron_item_test.rbindex cfad67ed53..de0114e1e8 100644--- a/test/models/sophtron_item_test.rb+++ b/test/models/sophtron_item_test.rb@@ -216,10 +216,15 @@ class SophtronItemTest < ActiveSupport::TestCaseassert_equal [ first_account, second_account ], manual_item.manual_sync_sophtron_accounts.to_aend- test "declares user_id and access_key as encrypted" do+ test "declares credentials and raw payloads as encrypted" doskip "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"+ encrypted = SophtronItem.encrypted_attributes.map(&:to_s)+ assert_includes encrypted, "user_id"+ assert_includes encrypted, "access_key"+ assert_includes encrypted, "raw_payload"+ assert_includes encrypted, "raw_institution_payload"+ assert_includes encrypted, "raw_customer_payload"+ assert_includes encrypted, "raw_job_payload"endend