The personal finance app for everyone (by everyone)
Ruby
Encrypt every table in the backfill and document adding keys to an instance with data (#4936)
GFR303bfe421136
diff --git a/.env.example b/.env.exampleindex d33be15f85..4906dfced0 100644--- a/.env.example+++ b/.env.example@@ -249,6 +249,8 @@ POSTHOG_HOST=# For managed mode: Set these environment variables to provide encryption keys.# For self-hosted mode: If not provided, they will be automatically generated based on your SECRET_KEY_BASE.# You can generate your own keys by running: 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_DETERMINISTIC_KEY=# ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT=diff --git a/app/views/settings/_encryption_migration_guide.html.erb b/app/views/settings/_encryption_migration_guide.html.erbindex 94313ee7c5..52592e5b24 100644--- a/app/views/settings/_encryption_migration_guide.html.erb+++ b/app/views/settings/_encryption_migration_guide.html.erb@@ -1,5 +1,5 @@<p><%= link_to t("settings.encryption_migration_guide"),- "https://github.com/we-promise/docs/blob/main/self-hosting.mdx#turning-on-active-record-encryption-after-first-boot",+ "https://github.com/we-promise/sure/blob/main/docs/hosting/docker.md#encrypting-sensitive-data",target: "_blank", rel: "noopener noreferrer", class: "text-link underline" %></p>diff --git a/compose.example.ai.yml b/compose.example.ai.ymlindex 0011c8550b..ed4ee9a80f 100644--- a/compose.example.ai.yml+++ b/compose.example.ai.yml@@ -71,6 +71,13 @@ x-db-env: &db_envx-rails-env: &rails_env<<: *db_envSECRET_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.+ 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:-}SELF_HOSTED: "true"RAILS_FORCE_SSL: "false"RAILS_ASSUME_SSL: "false"diff --git a/compose.example.yml b/compose.example.ymlindex 7208be14f1..b9e7d64a04 100644--- a/compose.example.yml+++ b/compose.example.yml@@ -50,6 +50,13 @@ x-db-env: &db_envx-rails-env: &rails_env<<: *db_envSECRET_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.+ 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:-}SELF_HOSTED: "true"RAILS_FORCE_SSL: "false"RAILS_ASSUME_SSL: "false"diff --git a/docs/hosting/docker.md b/docs/hosting/docker.mdindex 8d82e18b2c..5364a34fd7 100644--- a/docs/hosting/docker.md+++ b/docs/hosting/docker.md@@ -95,6 +95,8 @@ SECRET_KEY_BASE="replacemewiththegeneratedstringfromthepriorstep"POSTGRES_PASSWORD="replacemewithyourdesireddatabasepassword"```+To encrypt sensitive data such as bank credentials with your own keys, set them now, before the first start; see [Encrypting sensitive data](#encrypting-sensitive-data).+#### Using HTTPSAssuming you want to access your instance from the internet, you should have secured your URL address with an SSL certificate.@@ -523,7 +525,7 @@ Uploaded files are backed up from the `app-storage` volume. If you store them inThe version comes from the running app: every time `web` starts it records its version, and a backup is refused if the database schema no longer matches it.> [!WARNING]-> `config/.env` contains `SECRET_KEY_BASE` and your API keys. Without `SECRET_KEY_BASE`, encrypted data in the database cannot be read. Keep the backup folder private, and encrypt off-site copies (for example with [rclone crypt](https://rclone.org/crypt/)).+> `config/.env` contains `SECRET_KEY_BASE`, your API keys and, if you set them, your [encryption keys](#encrypting-sensitive-data). Without them, encrypted data in the database cannot be read. Keep the backup folder private, and encrypt off-site copies (for example with [rclone crypt](https://rclone.org/crypt/)).### Settings@@ -609,6 +611,125 @@ Off-site backups now go to `<BACKUP_DESTINATION>/<INSTANCE_ID>/<version>/<date>-If you download the new `bin/db-backup.sh` without updating the compose file, the backup service stops with an error that points here.+## Encrypting sensitive data++Sure encrypts sensitive fields in the database, such as bank and provider credentials, MFA secrets, email addresses and names. A self-hosted instance takes the keys from one of two places:++- Your own keys, set with the three `ACTIVE_RECORD_ENCRYPTION_*` variables. Set all three or none: the app refuses to start when only some of them are set.+- Otherwise, keys that Sure derives from `SECRET_KEY_BASE`. Changing `SECRET_KEY_BASE` then changes the keys as well.++> [!WARNING]+> Encrypted data can only be read with the keys it was encrypted with. On an instance with data, don't change the three keys or `SECRET_KEY_BASE` except as described below, and keep `config/.env` (which backups include) private.++Your own keys are recommended, because they don't depend on `SECRET_KEY_BASE`. If the boot log warns that `SECRET_KEY_BASE` is a value from an example compose file, the derived keys are public; see [Encryption key rotation](encryption.md).++### Generate the keys++Run this three times and keep the three values:++```bash+openssl rand -hex 32+```++Compose files from before this section existed don't pass the keys to the containers. If the `x-rails-env` block of your `compose.yml` has no `ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY` line, copy the three `ACTIVE_RECORD_ENCRYPTION_*` lines from [`compose.example.yml`](../../compose.example.yml) into it. Until you do, keys in `.env` have no effect.++> [!IMPORTANT]+> If `.env` already holds the keys but your `compose.yml` didn't pass them on, they were never active. Passing them on changes the keys of your instance, so remove the three lines from `.env` before you update `compose.yml`, and add them back only as described in [Switching an existing instance to your own keys](#switching-an-existing-instance-to-your-own-keys).++### On a new instance++Add the keys to `.env` before the first `docker compose up`:++```txt+ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY="first value"+ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY="second value"+ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT="third value"+```++### Encrypting data stored without encryption++Older versions of Sure stored this data unencrypted when no keys were set. After an update, Sure still reads those rows and encrypts whatever it writes, but rows it hasn't written since stay unencrypted until you convert them. The conversion uses the keys the instance already has and doesn't change them.++Update Sure to a version that includes this guide first and let it start once, so its database migrations have run. Older versions convert only some of the tables. Then:++1. Take a backup and note the folder name it prints (for example `0.7.6/2026-10-27_111135-manual`):++ ```bash+ docker compose run --rm backup create+ ```++2. Stop the app, so nothing is written while the data is converted:++ ```bash+ docker compose stop web worker+ ```++3. Preview the conversion. This changes nothing, and must list every table with `"failed_count":0` and include a `session_ip_digests` entry:++ ```bash+ docker compose run --rm web bin/rails security:backfill_encryption+ ```++ If rows fail, they hold data encrypted with keys the instance no longer has, for example after `SECRET_KEY_BASE` was changed. Don't convert: run `docker compose up -d`, and put the keys or `SECRET_KEY_BASE` that data was encrypted with back in place first.++4. Convert the data:++ ```bash+ docker compose run --rm web bin/rails "security:backfill_encryption[100,0]"+ ```++ The command must finish without an error, and the JSON report on its last line must show `"ok":true` and `"failed_count":0`. If it doesn't, run the command again; it is safe to repeat. The per-table `failed_samples` name rows that keep failing.++5. Start the app with `docker compose up -d`, sign in, and open **Settings > Bank Sync** to check that your connections load.++### Switching an existing instance to your own keys++Data an instance has already encrypted with the derived keys can't be read with new keys. The steps below first check whether the instance holds any such data. If it doesn't, for example because it was updated straight from a version that stored everything unencrypted, they convert it to your keys directly. If it does, moving that data to new keys is a key rotation, which these steps don't cover.++> [!NOTE]+> Already added the keys without these steps? Data encrypted with the old keys then reads back as unreadable text, and provider syncs fail. Remove the three lines from `.env` and run `docker compose up -d`. Keep the three values and use the same ones when you switch: anything the app wrote while they were active is encrypted with them.++Update Sure to a version that includes this guide first and let it start once, so its database migrations have run. Don't combine the switch with a version update. Then:++1. Take a backup and note the folder name it prints (for example `0.7.6/2026-10-27_111135-manual`):++ ```bash+ docker compose run --rm backup create+ ```++2. Stop the app:++ ```bash+ docker compose stop web worker+ ```++3. Add the three keys to `.env` (and the three lines to `compose.yml` if they are missing; see above).++4. Preview the conversion with the new keys. This changes nothing:++ ```bash+ docker compose run --rm web bin/rails security:backfill_encryption+ ```++ Continue only if it lists every table with `"failed_count":0` and includes a `session_ip_digests` entry. Failed rows hold data encrypted with the old keys. In that case, remove the three lines from `.env` again and run `docker compose up -d`. The instance keeps working with the derived keys, and its data stays encrypted with them. The manual rotation in [Encryption key rotation](encryption.md) needs a custom initializer and the old keys inside the containers, which the example compose files don't provide.++5. Convert the data:++ ```bash+ docker compose run --rm web bin/rails "security:backfill_encryption[100,0]"+ ```++ The command must finish without an error, and the JSON report on its last line must show `"ok":true` and `"failed_count":0`. If it doesn't, run the command again; it is safe to repeat. If rows keep failing (the per-table `failed_samples` name them), don't start the app: undo the change as described below.++6. Start the app with `docker compose up -d`, sign in, and open **Settings > Bank Sync** to check that your connections load.++To undo the switch, stop `web` and `worker`, restore the backup from step 1 by its name (not `latest`, which may be a newer scheduled backup taken with the keys), remove the three `ACTIVE_RECORD_ENCRYPTION_*` lines from `.env`, and run `docker compose up -d`:++```bash+docker compose stop web worker+docker compose run --rm backup restore 0.7.6/2026-10-27_111135-manual+```+## Troubleshooting### ActiveRecord::DatabaseConnectionErrordiff --git a/lib/tasks/security_backfill.rake b/lib/tasks/security_backfill.rakeindex 8aa7a1e992..364e71cd8e 100644--- a/lib/tasks/security_backfill.rake+++ b/lib/tasks/security_backfill.rake@@ -45,47 +45,41 @@ namespace :security doresults = {}puts "Starting security backfill (dry_run: #{dry_run}, batch_size: #{batch_size})..."- # User fields (MFA + PII)- # Note: otp_backup_codes excluded - it's a PostgreSQL array column incompatible with AR encryption- results[:users] = backfill_model(User, %i[otp_secret email unconfirmed_email first_name last_name], batch_size, dry_run)-- # Invitation tokens and email- results[:invitations] = backfill_model(Invitation, %i[token email], batch_size, dry_run)-- # InviteCode tokens- results[:invite_codes] = backfill_model(InviteCode, %i[token], batch_size, dry_run)-- # Session user_agent (encryption) and ip_address_digest (hashing)- results[:sessions] = backfill_sessions(batch_size, dry_run)-- # MobileDevice device_id- results[:mobile_devices] = backfill_model(MobileDevice, %i[device_id], batch_size, dry_run)-- # Provider items- results[:plaid_items] = backfill_model(PlaidItem, %i[access_token raw_payload raw_institution_payload], batch_size, dry_run)- results[:simplefin_items] = backfill_model(SimplefinItem, %i[access_url raw_payload raw_institution_payload], batch_size, dry_run)- results[:lunchflow_items] = backfill_model(LunchflowItem, %i[api_key raw_payload raw_institution_payload], batch_size, dry_run)- results[:enable_banking_items] = backfill_model(EnableBankingItem, %i[client_certificate session_id raw_payload raw_institution_payload last_psu_ip], batch_size, dry_run)- results[:truelayer_items] = backfill_model(TruelayerItem, %i[client_secret access_token refresh_token raw_payload raw_institution_payload], batch_size, dry_run)-- # Provider accounts- results[:plaid_accounts] = backfill_model(PlaidAccount, %i[raw_payload raw_transactions_payload raw_holdings_payload raw_liabilities_payload], batch_size, dry_run)- results[:simplefin_accounts] = backfill_model(SimplefinAccount, %i[raw_payload raw_transactions_payload raw_holdings_payload], batch_size, dry_run)- results[:lunchflow_accounts] = backfill_model(LunchflowAccount, %i[raw_payload raw_transactions_payload raw_holdings_payload], batch_size, dry_run)- results[:enable_banking_accounts] = backfill_model(EnableBankingAccount, %i[raw_payload raw_transactions_payload], batch_size, dry_run)- results[:truelayer_accounts] = backfill_model(TruelayerAccount, %i[raw_payload raw_transactions_payload], batch_size, dry_run)- results[:snaptrade_accounts] = backfill_model(SnaptradeAccount, %i[raw_payload raw_transactions_payload raw_holdings_payload raw_activities_payload account_number], batch_size, dry_run)- results[:coinbase_accounts] = backfill_model(CoinbaseAccount, %i[raw_payload raw_transactions_payload], batch_size, dry_run)- results[:coinstats_accounts] = backfill_model(CoinstatsAccount, %i[raw_payload raw_transactions_payload], batch_size, dry_run)- results[:mercury_accounts] = backfill_model(MercuryAccount, %i[raw_payload raw_transactions_payload], batch_size, dry_run)- results[:akahu_accounts] = backfill_model(AkahuAccount, %i[raw_payload raw_transactions_payload formatted_account], batch_size, dry_run)+ # 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)+ end++ results[:session_ip_digests] = backfill_session_ip_digests(batch_size, dry_run)+ # 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] }puts({- ok: true,+ ok: failed_count.zero?,dry_run: dry_run,batch_size: batch_size,+ failed_count: failed_count,results: results}.to_json)+ exit 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)enddef backfill_model(model_class, fields, batch_size, dry_run, &filter_block)@@ -106,7 +100,12 @@ namespace :security do# the encrypted getters raise on once keys are live.next unless fields.any? { |f| !safe_read_field(record, f).nil? }- next if dry_run+ if dry_run+ # Report the rows the real run would refuse, so the preview shows them.+ refused = fields.find { |f| undecryptable_ciphertext?(safe_read_field(record, f)) }+ failed << { id: record.id, error: ActiveRecord::Encryption::Errors::Decryption.name, message: "#{refused} holds ciphertext that no configured key decrypts" } if refused+ next+ endbegin# Read and write under a row lock: an app write between the read@@ -117,6 +116,12 @@ namespace :security doplaintext_values = {}fields.each do |field|value = safe_read_field(record, field)+ # Ciphertext that no configured key decrypts comes back as its+ # raw envelope (a Hash on json/jsonb columns); encrypting it+ # again would lose the original value for good.+ if undecryptable_ciphertext?(value)+ raise ActiveRecord::Encryption::Errors::Decryption, "#{field} holds ciphertext that no configured key decrypts"+ endplaintext_values[field] = value unless value.nil?end@@ -157,6 +162,25 @@ namespace :security do}end+ # Rails' encryption envelope: {"p": payload, "h": {"iv": ..., "at": ..., ...}}.+ # Matches the whole shape, since Encryptor#encrypted? accepts any object+ # with a "p" key and would flag plaintext payloads such as {"p": null}.+ def undecryptable_ciphertext?(value)+ envelope = value+ if value.is_a?(String)+ return false unless value.start_with?("{")++ envelope = begin+ JSON.parse(value)+ rescue JSON::ParserError+ return false+ end+ end++ envelope.is_a?(Hash) && envelope.keys.sort == %w[h p] && envelope["p"].is_a?(String) &&+ envelope["h"].is_a?(Hash) && envelope["h"].key?("iv") && envelope["h"].key?("at")+ end+# Safely read a field value, handling both encrypted and plaintext data.# When encryption is configured but the value is plaintext, the getter# raises ActiveRecord::Encryption::Errors::Decryption. In this case,@@ -167,7 +191,10 @@ namespace :security do# String, breaking every consumer of the payload.def safe_read_field(record, field)record.send(field)- rescue ActiveRecord::Encryption::Errors::Decryption+ rescue ActiveRecord::Encryption::Errors::Base, NoMethodError, TypeError+ # Rails reads any json/jsonb object with a "p" key as an encryption+ # envelope, so plaintext like {"p": 1, "h": "x"} can fail with+ # NoMethodError or TypeError instead of a Decryption error.raw = record.read_attribute_before_type_cast(field)column = record.class.columns_hash[field.to_s]if raw.is_a?(String) && [ :json, :jsonb ].include?(column&.type)@@ -181,37 +208,22 @@ namespace :security doendend- def backfill_sessions(batch_size, dry_run)+ # Hashes legacy session IP addresses into ip_address_digest. The encrypted+ # Session columns go through backfill_model like every other model.+ def backfill_session_ip_digests(batch_size, dry_run)processed = 0updated = 0failed = []- Session.order(:id).in_batches(of: batch_size) do |batch|+ Session.where.not(ip_address: [ nil, "" ]).where(ip_address_digest: [ nil, "" ])+ .select(:id, :ip_address, :ip_address_digest).order(:id).in_batches(of: batch_size) do |batch|batch.each do |session|processed += 1next if dry_runbegin- changes = {}-- # Re-save user_agent to trigger encryption (use safe read for plaintext)- user_agent_value = safe_read_field(session, :user_agent)- unless user_agent_value.nil?- # Use temporary instance to encrypt- encryptor = Session.new- encryptor.user_agent = user_agent_value- changes[:user_agent] = encryptor.read_attribute_before_type_cast(:user_agent)- end-- # Hash IP address into ip_address_digest if not already done- if session.ip_address.present? && session.ip_address_digest.blank?- changes[:ip_address_digest] = Digest::SHA256.hexdigest(session.ip_address.to_s)- end-- if changes.present?- session.update_columns(changes)- updated += 1- end+ session.update_columns(ip_address_digest: Digest::SHA256.hexdigest(session.ip_address.to_s))+ updated += 1rescue => efailed << { id: session.id, error: e.class.name, message: e.message }enddiff --git a/test/controllers/settings/providers_controller_test.rb b/test/controllers/settings/providers_controller_test.rbindex 94e5842416..87aba748c0 100644--- a/test/controllers/settings/providers_controller_test.rb+++ b/test/controllers/settings/providers_controller_test.rb@@ -683,7 +683,7 @@ class Settings::ProvidersControllerTest < ActionDispatch::IntegrationTestassert_response :successassert_includes response.body, I18n.t("settings.providers.provider_setup_encryption_warning.title")assert_select 'a[href=?][target="_blank"][rel="noopener noreferrer"]',- "https://github.com/we-promise/docs/blob/main/self-hosting.mdx#turning-on-active-record-encryption-after-first-boot",+ "https://github.com/we-promise/sure/blob/main/docs/hosting/docker.md#encrypting-sensitive-data",minimum: 1assert_includes response.body, I18n.t("settings.providers.provider_setup_encryption_warning.message")assert_includes response.body, I18n.t("settings.providers.drawer_trust_statement_encryption_unconfigured")@@ -704,7 +704,7 @@ class Settings::ProvidersControllerTest < ActionDispatch::IntegrationTestassert_response :successrefute_includes response.body, I18n.t("settings.providers.provider_setup_encryption_warning.title")assert_select 'a[href=?][target="_blank"][rel="noopener noreferrer"]',- "https://github.com/we-promise/docs/blob/main/self-hosting.mdx#turning-on-active-record-encryption-after-first-boot",+ "https://github.com/we-promise/sure/blob/main/docs/hosting/docker.md#encrypting-sensitive-data",count: 0refute_includes response.body, I18n.t("settings.providers.provider_setup_encryption_warning.message")refute_includes response.body, I18n.t("settings.providers.drawer_trust_statement_encryption_unconfigured")@@ -742,7 +742,7 @@ class Settings::ProvidersControllerTest < ActionDispatch::IntegrationTestassert_response :successassert_includes response.body, I18n.t("settings.providers.provider_setup_encryption_warning.title")assert_select 'a[href=?][target="_blank"][rel="noopener noreferrer"]',- "https://github.com/we-promise/docs/blob/main/self-hosting.mdx#turning-on-active-record-encryption-after-first-boot",+ "https://github.com/we-promise/sure/blob/main/docs/hosting/docker.md#encrypting-sensitive-data",minimum: 1assert_includes response.body, I18n.t("settings.providers.provider_setup_encryption_warning.message")assert_includes response.body, I18n.t("settings.providers.drawer_trust_statement_encryption_unconfigured")@@ -759,7 +759,7 @@ class Settings::ProvidersControllerTest < ActionDispatch::IntegrationTestassert_response :successrefute_includes response.body, I18n.t("settings.providers.provider_setup_encryption_warning.title")assert_select 'a[href=?][target="_blank"][rel="noopener noreferrer"]',- "https://github.com/we-promise/docs/blob/main/self-hosting.mdx#turning-on-active-record-encryption-after-first-boot",+ "https://github.com/we-promise/sure/blob/main/docs/hosting/docker.md#encrypting-sensitive-data",count: 0refute_includes response.body, I18n.t("settings.providers.provider_setup_encryption_warning.message")assert_includes response.body, I18n.t("settings.providers.drawer_trust_statement")@@ -776,7 +776,7 @@ class Settings::ProvidersControllerTest < ActionDispatch::IntegrationTestassert_response :successrefute_includes response.body, I18n.t("settings.providers.provider_setup_encryption_warning.title")assert_select 'a[href=?][target="_blank"][rel="noopener noreferrer"]',- "https://github.com/we-promise/docs/blob/main/self-hosting.mdx#turning-on-active-record-encryption-after-first-boot",+ "https://github.com/we-promise/sure/blob/main/docs/hosting/docker.md#encrypting-sensitive-data",count: 0refute_includes response.body, I18n.t("settings.providers.provider_setup_encryption_warning.message")assert_includes response.body, I18n.t("settings.providers.drawer_trust_statement")@@ -792,7 +792,7 @@ class Settings::ProvidersControllerTest < ActionDispatch::IntegrationTestassert_response :successassert_includes response.body, I18n.t("settings.providers.provider_setup_encryption_warning.title")assert_select 'a[href=?][target="_blank"][rel="noopener noreferrer"]',- "https://github.com/we-promise/docs/blob/main/self-hosting.mdx#turning-on-active-record-encryption-after-first-boot",+ "https://github.com/we-promise/sure/blob/main/docs/hosting/docker.md#encrypting-sensitive-data",minimum: 1assert_includes response.body, I18n.t("settings.providers.provider_setup_encryption_warning.message")refute_includes response.body, I18n.t("wise_items.provider_panel.encryption_warning.title")diff --git a/test/controllers/settings/securities_controller_test.rb b/test/controllers/settings/securities_controller_test.rbindex 38179fc8c9..929066e15c 100644--- a/test/controllers/settings/securities_controller_test.rb+++ b/test/controllers/settings/securities_controller_test.rb@@ -12,7 +12,7 @@ class Settings::SecuritiesControllerTest < ActionDispatch::IntegrationTestassert_response :successassert_includes response.body, I18n.t("settings.securities.show.encryption_warning.title")assert_select 'a[href=?][target="_blank"][rel="noopener noreferrer"]',- "https://github.com/we-promise/docs/blob/main/self-hosting.mdx#turning-on-active-record-encryption-after-first-boot",+ "https://github.com/we-promise/sure/blob/main/docs/hosting/docker.md#encrypting-sensitive-data",count: 1end@@ -39,7 +39,7 @@ class Settings::SecuritiesControllerTest < ActionDispatch::IntegrationTestassert_response :successassert_not_includes response.body, I18n.t("settings.securities.show.encryption_warning.title")assert_select 'a[href=?][target="_blank"][rel="noopener noreferrer"]',- "https://github.com/we-promise/docs/blob/main/self-hosting.mdx#turning-on-active-record-encryption-after-first-boot",+ "https://github.com/we-promise/sure/blob/main/docs/hosting/docker.md#encrypting-sensitive-data",count: 0end@@ -51,7 +51,7 @@ class Settings::SecuritiesControllerTest < ActionDispatch::IntegrationTestassert_response :successassert_not_includes response.body, I18n.t("settings.securities.show.encryption_warning.title")assert_select 'a[href=?][target="_blank"][rel="noopener noreferrer"]',- "https://github.com/we-promise/docs/blob/main/self-hosting.mdx#turning-on-active-record-encryption-after-first-boot",+ "https://github.com/we-promise/sure/blob/main/docs/hosting/docker.md#encrypting-sensitive-data",count: 0enddiff --git a/test/lib/tasks/security_backfill_test.rb b/test/lib/tasks/security_backfill_test.rbindex 4b61f99629..319dd9e3ee 100644--- a/test/lib/tasks/security_backfill_test.rb+++ b/test/lib/tasks/security_backfill_test.rb@@ -93,9 +93,8 @@ class SecurityBackfillTest < ActiveSupport::TestCaseassert_nil eb_item.reload.read_attribute_before_type_cast(:last_psu_ip)end- # Guards the task's field list: dropping :account_number from the- # SnaptradeAccount entry would leave the model-level encryption test green- # while pre-encryption rows stayed plaintext.+ # A plaintext column next to already-encrypted payloads on the same row must+ # still be converted.test "backfill encrypts a plaintext SnapTrade account number" doaccount = snaptrade_accounts(:fidelity_401k)ActiveRecord::Base.connection.execute(ActiveRecord::Base.sanitize_sql([@@ -131,4 +130,215 @@ class SecurityBackfillTest < ActiveSupport::TestCaseassert_match(/"p":/, account.read_attribute_before_type_cast(:raw_payload).to_s,"the stored value must be an encryption envelope, not plaintext {}")end++ # The task finds encrypted models at runtime. Compare that against the+ # `encrypts` lines in app/models, so a model the discovery misses fails here+ # instead of keeping plaintext that raises once the keys are live.+ test "backfill covers every encrypts declaration in app/models" do+ declared = Hash.new { |hash, key| hash[key] = [] }+ Dir[Rails.root.join("app/models/**/*.rb")].each do |path|+ File.read(path).scan(/^\s*encrypts\s+((?::\w+\s*,\s*)*:\w+)/) do |(names)|+ model = path.delete_prefix("#{Rails.root.join("app/models")}/").delete_suffix(".rb").camelize.constantize+ declared[model.base_class.table_name].concat(names.scan(/\w+/))+ end+ end+ assert_operator declared.size, :>=, 50, "the encrypts scan found too few models"++ output = run_backfill(dry_run: true)+ results = output["results"]+ discovered = encrypted_models_for_backfill.to_h { |model| [ model.table_name, model.encrypted_attributes.map(&:to_s) ] }++ declared.each do |table, fields|+ assert results.key?(table), "security:backfill_encryption does not cover #{table}"+ assert_empty fields - discovered[table], "#{table}: fields missing from the backfill"+ end+ tables = encrypted_models_for_backfill.map(&:table_name)+ assert_equal tables.uniq, tables, "two encrypted models share a table; their results would overwrite each other"++ # Framework models (ActionText::EncryptedRichText) declare `encrypts`+ # themselves; only models defined in this app must be ApplicationRecords.+ app_dir = Rails.root.join("app").to_s+ outside = ActiveRecord::Base.descendants.reject { |model| model <= ApplicationRecord || model.abstract_class? }+ .select { |model| model.encrypted_attributes.present? }+ .select { |model| Object.const_source_location(model.name.to_s)&.first.to_s.start_with?(app_dir) }+ assert_empty outside.map(&:name), "encrypted models outside ApplicationRecord are not backfilled"+ end++ # One plaintext row per encrypted model, as left by an install that ran+ # without keys. After one run, every encrypted column of every table must+ # hold ciphertext that decrypts to the original value.+ test "backfill encrypts plaintext in every encrypted column of every table" do+ connection = ActiveRecord::Base.connection+ rows = encrypted_models_for_backfill.to_h { |model| [ model, insert_plaintext_row(model) ] }++ output = run_backfill(dry_run: false)+ results = output["results"]++ rows.each do |model, (id, plaintext)|+ assert_equal 0, results.dig(model.table_name, "failed_count"), "#{model.table_name}: #{results[model.table_name]}"+ record = model.find(id)+ plaintext.each do |field, value|+ expected = json_column?(model, field) ? JSON.parse(value) : value+ assert_equal expected, record.public_send(field), "#{model.name}##{field} must decrypt to its original value"+ raw = connection.select_value(model.unscoped.where(id: id).select(field).to_sql).to_s+ refute_includes raw, "backfill-probe", "#{model.name}##{field} must be stored as ciphertext"+ assert ActiveRecord::Encryption.encryptor.encrypted?(raw),+ "#{model.name}##{field} must hold an encryption envelope"+ end+ end+ end++ test "backfill leaves converted values readable on a rerun" do+ item = kraken_items(:one)+ ActiveRecord::Base.connection.execute(ActiveRecord::Base.sanitize_sql([+ "UPDATE kraken_items SET api_secret = ? WHERE id = ?", "plaintext-secret", item.id ]))++ run_backfill(dry_run: false)+ output = run_backfill(dry_run: false)++ assert_equal "plaintext-secret", item.reload.api_secret+ assert_equal 0, output.dig("results", "kraken_items", "failed_count")+ end++ # Ciphertext under keys the app no longer has (keys changed, or data+ # encrypted with keys derived from SECRET_KEY_BASE) reads back as the raw+ # envelope. Encrypting that again would make the original unrecoverable.+ test "backfill refuses ciphertext that no configured key decrypts" do+ item = kraken_items(:one)+ foreign_key = ActiveRecord::Encryption::DerivedSecretKeyProvider.new(SecureRandom.hex(32))+ foreign_text = ActiveRecord::Encryption.encryptor.encrypt("lost-secret", key_provider: foreign_key)+ foreign_json = ActiveRecord::Encryption.encryptor.encrypt({ "lost" => true }.to_json, key_provider: foreign_key)+ other = kraken_items(:requires_update)+ # Rails stores encrypted json/jsonb values as a JSON object envelope.+ KrakenItem.where(id: item.id).update_all([ "api_secret = ?", foreign_text ])+ KrakenItem.where(id: other.id).update_all([ "raw_payload = ?::jsonb", foreign_json ])++ preview = run_backfill(dry_run: true)+ assert_equal 2, preview.dig("results", "kraken_items", "failed_count"),+ "the dry run must report the rows the real run refuses"++ result = run_backfill(dry_run: false)+ assert_equal false, result["ok"]+ assert_equal 2, result["failed_count"]+ assert_equal 2, result.dig("results", "kraken_items", "failed_count")+ connection = ActiveRecord::Base.connection+ assert_equal foreign_text, connection.select_value(KrakenItem.where(id: item.id).select(:api_secret).to_sql)+ assert_equal JSON.parse(foreign_json),+ JSON.parse(connection.select_value(KrakenItem.where(id: other.id).select("raw_payload::text").to_sql))+ end++ test "backfill encrypts session user agents and hashes legacy IP addresses" do+ session = sessions(:one)+ ActiveRecord::Base.connection.execute(ActiveRecord::Base.sanitize_sql([+ "UPDATE sessions SET user_agent = ?, ip_address = ?, ip_address_digest = NULL WHERE id = ?",+ "Probe-Agent/1.0", "198.51.100.4", session.id ]))++ output = run_backfill(dry_run: false)+ results = output["results"]++ session.reload+ assert_equal "Probe-Agent/1.0", session.user_agent+ refute_includes session.read_attribute_before_type_cast(:user_agent).to_s, "Probe-Agent"+ assert_equal Digest::SHA256.hexdigest("198.51.100.4"), session.ip_address_digest+ assert_equal 0, results.dig("sessions", "failed_count")+ assert_equal 0, results.dig("session_ip_digests", "failed_count")+ end++ # Encryptor#encrypted? only checks for a "p" key; a plaintext payload of+ # that shape must still be converted, not refused.+ test "backfill converts plaintext json that only resembles an envelope" do+ item = kraken_items(:one)+ payload = { "p" => nil, "h" => "header" }+ ActiveRecord::Base.connection.execute(ActiveRecord::Base.sanitize_sql([+ "UPDATE kraken_items SET raw_payload = ?::jsonb WHERE id = ?", payload.to_json, item.id ]))++ output = run_backfill(dry_run: false)++ assert_equal 0, output.dig("results", "kraken_items", "failed_count")+ assert_equal payload, item.reload.raw_payload+ end++ private++ # 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:)+ task = Rake::Task["security:backfill_encryption"]+ task.reenable+ output, = capture_io do+ task.invoke("500", dry_run.to_s)+ rescue SystemExit+ nil+ end+ JSON.parse(output.lines.last)+ end++ def json_column?(model, field)+ %i[json jsonb].include?(model.columns_hash[field.to_s].type)+ end++ # Writes plaintext into every encrypted column with raw SQL: into a+ # fixture row where the table has one (so its check constraints hold),+ # otherwise into a new row with placeholder values.+ def insert_plaintext_row(model)+ plaintext = model.encrypted_attributes.to_h do |field|+ value = json_column?(model, field) ? { "probe" => "backfill-probe-#{field}" }.to_json : "backfill-probe-#{field}"+ [ field.to_s, value ]+ end++ id = model.unscoped.order(:id).pick(:id)+ if id+ model.unscoped.where(id: id).update_all(plaintext.keys.map { |field| "#{model.connection.quote_column_name(field)} = ?" }+ .join(", ").then { |sql| [ sql, *plaintext.values ] })+ else+ id = insert_row(model.table_name, plaintext, fresh_parents: true)+ end+ [ id, plaintext ]+ end++ # fresh_parents: a new parent row per foreign key, so unique indexes that+ # span the parent (one account per item and kind, ...) are not hit.+ def insert_row(table, given = {}, fresh_parents: false)+ connection = ActiveRecord::Base.connection+ references = connection.foreign_keys(table).to_h { |fk| [ fk.column, fk.to_table ] }++ values = connection.columns(table).each_with_object({}) do |column, map|+ next if given.key?(column.name) || column.null || !column.default.nil? || column.default_function+ map[column.name] =+ if references.key?(column.name)+ fresh_parents ? insert_row(references[column.name]) : existing_or_new_row(references[column.name])+ else+ placeholder_for(table, column)+ end+ end.merge(given)++ columns = values.keys.map { |name| connection.quote_column_name(name) }.join(", ")+ quoted = values.values.map { |value| connection.quote(value) }.join(", ")+ connection.select_value("INSERT INTO #{connection.quote_table_name(table)} (#{columns}) VALUES (#{quoted}) RETURNING id")+ end++ def existing_or_new_row(table)+ ActiveRecord::Base.connection.select_value("SELECT id FROM #{ActiveRecord::Base.connection.quote_table_name(table)} LIMIT 1") ||+ insert_row(table)+ end++ def placeholder_for(table, column)+ # A check constraint that limits the column to a list of values+ # ("kind::text = ANY (ARRAY['wallet'::...])") names a valid one.+ allowed = ActiveRecord::Base.connection.check_constraints(table).lazy.filter_map do |constraint|+ constraint.expression[/\b#{column.name}::[\w ]+= (?:ANY \(ARRAY\[)?'([^']*)'/, 1]+ end.first+ return allowed if allowed++ case column.type+ when :uuid then SecureRandom.uuid+ when :integer, :bigint, :decimal, :float then 0+ when :boolean then false+ when :date then Date.current+ when :datetime, :timestamp then Time.current+ when :json, :jsonb then "{}"+ when :enum then ActiveRecord::Base.connection.select_value("SELECT unnest(enum_range(NULL::#{column.sql_type})) LIMIT 1")+ else column.array? ? "{}" : "backfill-placeholder-#{SecureRandom.hex(4)}"+ end+ endend