Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Encrypt the remaining provider identifiers at rest (#4336)

GFR59e6b5293d5e
diff --git a/app/models/akahu_account.rb b/app/models/akahu_account.rb
index ec8fd54a3c..1ef369c0f5 100644
--- a/app/models/akahu_account.rb
+++ b/app/models/akahu_account.rb
@@ -14,6 +14,10 @@ class AkahuAccount < ApplicationRecord
if encryption_ready?
encrypts :raw_payload
encrypts :raw_transactions_payload
+ # The full bank account number; never looked up by value. Rows synced
+ # before this was encrypted stay readable (support_unencrypted_data) until
+ # they are encrypted; new writes are always encrypted.
+ encrypts :formatted_account, support_unencrypted_data: true
end
belongs_to :akahu_item
@@ -64,9 +68,7 @@ class AkahuAccount < ApplicationRecord
institution_metadata: {
id: connection[:_id].presence || connection[:id],
name: connection[:name],
- logo: connection[:logo],
- account_number: snapshot[:formatted_account].presence || payment_details[:account_number],
- holder: meta[:holder].presence || payment_details[:account_holder]
+ logo: connection[:logo]
}.compact,
raw_payload: account_snapshot
)
diff --git a/app/models/enable_banking_item.rb b/app/models/enable_banking_item.rb
index 34fc03e37b..c211e85f81 100644
--- a/app/models/enable_banking_item.rb
+++ b/app/models/enable_banking_item.rb
@@ -9,6 +9,10 @@ class EnableBankingItem < ApplicationRecord
encrypts :session_id, deterministic: true
encrypts :raw_payload
encrypts :raw_institution_payload
+ # The user's IP address, kept only while the bank session needs it (see
+ # with_stale_psu_ip); never looked up by value. Values stored before this
+ # was encrypted stay readable until they are encrypted.
+ encrypts :last_psu_ip, support_unencrypted_data: true
end
validates :name, presence: true
diff --git a/app/models/lunchflow_account.rb b/app/models/lunchflow_account.rb
index dcc0a04e25..9435d7e385 100644
--- a/app/models/lunchflow_account.rb
+++ b/app/models/lunchflow_account.rb
@@ -5,6 +5,9 @@ class LunchflowAccount < ApplicationRecord
if encryption_ready?
encrypts :raw_payload
encrypts :raw_transactions_payload
+ # Added after the other payloads: rows synced earlier stay readable until
+ # they are encrypted; new writes are always encrypted.
+ encrypts :raw_holdings_payload, support_unencrypted_data: true
end
belongs_to :lunchflow_item
diff --git a/db/migrate/20261015220000_remove_account_details_from_akahu_institution_metadata.rb b/db/migrate/20261015220000_remove_account_details_from_akahu_institution_metadata.rb
new file mode 100644
index 0000000000..379f7c2840
--- /dev/null
+++ b/db/migrate/20261015220000_remove_account_details_from_akahu_institution_metadata.rb
@@ -0,0 +1,19 @@
+# Akahu used to copy the full bank account number and the account holder's
+# name into institution_metadata, a plain jsonb column. Nothing reads either
+# key: the account number lives in formatted_account (now encrypted) and the
+# raw payload, and the holder name is not shown anywhere. Strip both from
+# existing rows so the personal data no longer sits there in plaintext.
+class RemoveAccountDetailsFromAkahuInstitutionMetadata < ActiveRecord::Migration[8.1]
+ def up
+ execute <<~SQL.squish
+ UPDATE akahu_accounts
+ SET institution_metadata = institution_metadata - 'account_number' - 'holder'
+ WHERE institution_metadata ?| array['account_number', 'holder']
+ SQL
+ end
+
+ def down
+ # The removed values are still in raw_payload; the next sync does not
+ # write them back, so there is nothing to restore here.
+ end
+end
diff --git a/db/migrate/20261015220100_encrypt_existing_provider_identifiers.rb b/db/migrate/20261015220100_encrypt_existing_provider_identifiers.rb
new file mode 100644
index 0000000000..923b625626
--- /dev/null
+++ b/db/migrate/20261015220100_encrypt_existing_provider_identifiers.rb
@@ -0,0 +1,107 @@
+# EnableBankingItem#last_psu_ip, AkahuAccount#formatted_account and
+# LunchflowAccount#raw_holdings_payload are encrypted from this release on.
+# Rows synced earlier still hold plaintext. The attributes keep reading it
+# (support_unencrypted_data), so nothing breaks, but the data would stay
+# plaintext at rest until someone runs security:backfill_encryption. Encrypt
+# it now instead.
+#
+# Does nothing when encryption is not configured: the attributes are then not
+# encrypted at all, and security:backfill_encryption covers them once keys are
+# set.
+class EncryptExistingProviderIdentifiers < ActiveRecord::Migration[8.1]
+ # Each row commits on its own, so a running sync never waits on locks held
+ # until the whole migration finishes. A rerun after a partial run is safe:
+ # rows already done are skipped.
+ disable_ddl_transaction!
+
+ COLUMNS = {
+ "EnableBankingItem" => %w[last_psu_ip],
+ "AkahuAccount" => %w[formatted_account],
+ "LunchflowAccount" => %w[raw_holdings_payload]
+ }.freeze
+
+ BATCH_SIZE = 500
+
+ def up
+ COLUMNS.each do |model_name, columns|
+ model = model_name.constantize
+ next unless model.encryption_ready?
+
+ model.reset_column_information
+ columns.each { |column| encrypt_plaintext(model, column) }
+ end
+ end
+
+ # Writes the values back as plaintext, so code from before this release can
+ # read them again after a rollback. The current code reads both forms.
+ def down
+ COLUMNS.each do |model_name, columns|
+ model = model_name.constantize
+ next unless model.encryption_ready?
+
+ model.reset_column_information
+ columns.each { |column| decrypt_ciphertext(model, column) }
+ end
+ end
+
+ private
+
+ def encrypt_plaintext(model, column)
+ json = json_column?(model, column)
+
+ # update_all casts through the encrypted attribute type, so the value is
+ # written as ciphertext.
+ rewrite_stored_values(model, column, encrypted: false) do |raw|
+ { column => json ? JSON.parse(raw) : raw }
+ end
+ end
+
+ def decrypt_ciphertext(model, column)
+ cast = "::jsonb" if json_column?(model, column)
+
+ # Plain SQL, so the value is not encrypted again on the way in.
+ rewrite_stored_values(model, column, encrypted: true) do |raw|
+ [ "#{connection.quote_column_name(column)} = ?#{cast}", ActiveRecord::Encryption.encryptor.decrypt(raw) ]
+ end
+ end
+
+ # Rewrites each stored value that is currently encrypted (or not) with the
+ # update the block returns for it. Values in the other state are skipped,
+ # so a rerun after a partial run only touches the rows left over.
+ def rewrite_stored_values(model, column, encrypted:)
+ each_stored_value(model, column) do |id, raw|
+ next unless ActiveRecord::Encryption.encryptor.encrypted?(raw) == encrypted
+
+ unchanged(model, column, id, raw).update_all(yield(raw))
+ end
+ end
+
+ # Paged by id so large payload columns are not loaded all at once.
+ def each_stored_value(model, column)
+ quoted = connection.quote_column_name(column)
+ last_id = nil
+
+ loop do
+ after = last_id ? "AND id > #{connection.quote(last_id)}" : ""
+ rows = connection.select_rows(<<~SQL)
+ SELECT id, #{quoted}::text FROM #{model.quoted_table_name}
+ WHERE #{quoted} IS NOT NULL #{after}
+ ORDER BY id LIMIT #{BATCH_SIZE}
+ SQL
+ break if rows.empty?
+
+ rows.each { |id, raw| yield id, raw }
+ last_id = rows.last.first
+ end
+ end
+
+ # Skips the row if a sync wrote a new value since it was read, instead of
+ # overwriting that value with the old one.
+ def unchanged(model, column, id, raw)
+ model.unscoped.where(id: id).where("#{connection.quote_column_name(column)}::text = ?", raw)
+ end
+
+ def json_column?(model, column)
+ %i[json jsonb].include?(model.columns_hash[column].type)
+ end
+end
diff --git a/lib/tasks/security_backfill.rake b/lib/tasks/security_backfill.rake
index fa267996c2..02d8b43175 100644
--- a/lib/tasks/security_backfill.rake
+++ b/lib/tasks/security_backfill.rake
@@ -58,19 +58,20 @@ namespace :security do
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], 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], 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)
puts({
ok: true,
@@ -101,31 +102,40 @@ namespace :security do
next if dry_run
begin
- # Read plaintext values safely
- plaintext_values = {}
- fields.each do |field|
- value = safe_read_field(record, field)
- plaintext_values[field] = value unless value.nil?
+ # Read and write under a row lock: an app write between the read
+ # and update_columns (a new last_psu_ip, or DataCleanerJob clearing
+ # it) would otherwise be overwritten with the stale value.
+ written = record.with_lock do
+ # Read plaintext values safely
+ plaintext_values = {}
+ fields.each do |field|
+ value = safe_read_field(record, field)
+ plaintext_values[field] = value unless value.nil?
+ end
+
+ next false if plaintext_values.empty?
+
+ # Use a temporary instance to encrypt values (avoids triggering
+ # validations/callbacks that might read other encrypted fields)
+ encryptor = model_class.new
+ plaintext_values.each do |field, value|
+ encryptor.send("#{field}=", value)
+ end
+
+ # Extract the encrypted values from the temporary instance
+ encrypted_attrs = {}
+ plaintext_values.keys.each do |field|
+ encrypted_attrs[field] = encryptor.read_attribute_before_type_cast(field)
+ end
+
+ # Write directly to database, bypassing callbacks/validations
+ record.update_columns(encrypted_attrs)
+ true
end
-
- next if plaintext_values.empty?
-
- # Use a temporary instance to encrypt values (avoids triggering
- # validations/callbacks that might read other encrypted fields)
- encryptor = model_class.new
- plaintext_values.each do |field, value|
- encryptor.send("#{field}=", value)
- end
-
- # Extract the encrypted values from the temporary instance
- encrypted_attrs = {}
- plaintext_values.keys.each do |field|
- encrypted_attrs[field] = encryptor.read_attribute_before_type_cast(field)
- end
-
- # Write directly to database, bypassing callbacks/validations
- record.update_columns(encrypted_attrs)
- updated += 1
+ updated += 1 if written
+ rescue ActiveRecord::RecordNotFound
+ # Deleted since the batch was loaded; nothing left to encrypt.
+ next
rescue => e
failed << { id: record.id, error: e.class.name, message: e.message }
end
diff --git a/test/encryption_verification_test.rb b/test/encryption_verification_test.rb
index 39723a260d..597b91d75b 100644
--- a/test/encryption_verification_test.rb
+++ b/test/encryption_verification_test.rb
@@ -391,6 +391,42 @@ class EncryptionVerificationTest < ActiveSupport::TestCase
assert_column_not_plaintext(PlaidAccount, account.id, :raw_holdings_payload, "sec_probe")
end
+ test "provider account identifiers are encrypted at rest" do
+ family = families(:dylan_family)
+
+ eb_item = EnableBankingItem.create!(
+ family: family, name: "EB probe", country_code: "FI", application_id: "app", client_certificate: "cert",
+ last_psu_ip: "203.0.113.42"
+ )
+ akahu_account = AkahuAccount.create!(
+ akahu_item: AkahuItem.create!(family: family, name: "Akahu probe", app_token: "app", user_token: "user"),
+ name: "Everyday", account_id: "acc_probe", currency: "NZD", formatted_account: "12-3456-7654321-00"
+ )
+ lunchflow_account = lunchflow_items(:one).lunchflow_accounts.create!(
+ name: "Brokerage", currency: "GBP", account_id: "holdings-probe",
+ raw_holdings_payload: [ { "symbol" => "HOLDPROBE" } ]
+ )
+
+ assert_equal "203.0.113.42", eb_item.reload.last_psu_ip
+ assert_equal "12-3456-7654321-00", akahu_account.reload.formatted_account
+ assert_equal "HOLDPROBE", lunchflow_account.reload.raw_holdings_payload.first["symbol"]
+
+ assert_column_not_plaintext(EnableBankingItem, eb_item.id, :last_psu_ip, "203.0.113.42")
+ assert_column_not_plaintext(AkahuAccount, akahu_account.id, :formatted_account, "7654321")
+ assert_column_not_plaintext(LunchflowAccount, lunchflow_account.id, :raw_holdings_payload, "HOLDPROBE")
+ end
+
+ test "provider identifiers stored before encryption stay readable" do
+ eb_item = EnableBankingItem.create!(
+ family: families(:dylan_family), name: "EB legacy", country_code: "FI", application_id: "app", client_certificate: "cert"
+ )
+ EnableBankingItem.where(id: eb_item.id).update_all("last_psu_ip = '203.0.113.50'")
+
+ # No global support_unencrypted_data: the attribute's own option must cover it
+ assert_not ActiveRecord::Encryption.config.support_unencrypted_data
+ assert_equal "203.0.113.50", eb_item.reload.last_psu_ip
+ end
+
# ============================================================================
# DATABASE VERIFICATION TESTS
# ============================================================================
diff --git a/test/lib/tasks/security_backfill_test.rb b/test/lib/tasks/security_backfill_test.rb
index 16f72c111f..4b61f99629 100644
--- a/test/lib/tasks/security_backfill_test.rb
+++ b/test/lib/tasks/security_backfill_test.rb
@@ -49,6 +49,50 @@ class SecurityBackfillTest < ActiveSupport::TestCase
refute_includes at_rest, "tx-1"
end
+ test "backfill encrypts provider account identifiers stored as plaintext" do
+ eb_item = EnableBankingItem.create!(
+ family: families(:dylan_family), name: "Backfill EB", country_code: "FI", application_id: "app", client_certificate: "cert"
+ )
+ akahu_account = AkahuAccount.create!(
+ akahu_item: AkahuItem.create!(family: families(:dylan_family), name: "Backfill Akahu", app_token: "app", user_token: "user"),
+ name: "Everyday", account_id: "acc_backfill", currency: "NZD"
+ )
+
+ # Plaintext values, as left by an install that synced before these columns were encrypted
+ connection = ActiveRecord::Base.connection
+ connection.execute(ActiveRecord::Base.sanitize_sql([
+ "UPDATE enable_banking_items SET last_psu_ip = ? WHERE id = ?", "203.0.113.7", eb_item.id ]))
+ connection.execute(ActiveRecord::Base.sanitize_sql([
+ "UPDATE akahu_accounts SET formatted_account = ? WHERE id = ?", "12-3456-7654321-00", akahu_account.id ]))
+
+ capture_io { Rake::Task["security:backfill_encryption"].invoke("500", "false") }
+
+ assert_equal "203.0.113.7", eb_item.reload.last_psu_ip
+ assert_equal "12-3456-7654321-00", akahu_account.reload.formatted_account
+ refute_includes eb_item.read_attribute_before_type_cast(:last_psu_ip).to_s, "203.0.113.7"
+ refute_includes akahu_account.read_attribute_before_type_cast(:formatted_account).to_s, "7654321"
+ end
+
+ # The backfill loads a batch, then encrypts each row. DataCleanerJob may
+ # clear last_psu_ip in between; writing the value read before that would
+ # put the IP back. The filter block runs on the loaded record before the
+ # write, so it stands in for that concurrent clear.
+ test "backfill does not restore a value cleared after the batch was loaded" do
+ eb_item = EnableBankingItem.create!(
+ family: families(:dylan_family), name: "Backfill EB race", country_code: "FI", application_id: "app", client_certificate: "cert"
+ )
+ connection = ActiveRecord::Base.connection
+ connection.execute(ActiveRecord::Base.sanitize_sql([
+ "UPDATE enable_banking_items SET last_psu_ip = ? WHERE id = ?", "203.0.113.9", eb_item.id ]))
+
+ backfill_model(EnableBankingItem.where(id: eb_item.id), %i[last_psu_ip], 500, false) do |record|
+ record.class.where(id: record.id).update_all(last_psu_ip: nil)
+ true
+ end
+
+ assert_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.
diff --git a/test/migrations/encrypt_existing_provider_identifiers_migration_test.rb b/test/migrations/encrypt_existing_provider_identifiers_migration_test.rb
new file mode 100644
index 0000000000..8341fc01e1
--- /dev/null
+++ b/test/migrations/encrypt_existing_provider_identifiers_migration_test.rb
@@ -0,0 +1,101 @@
+# frozen_string_literal: true
+
+require "test_helper"
+require Rails.root.join("db/migrate/20261015220100_encrypt_existing_provider_identifiers")
+
+class EncryptExistingProviderIdentifiersMigrationTest < ActiveSupport::TestCase
+ setup do
+ skip "Encryption not configured" unless EnableBankingItem.encryption_ready?
+
+ family = families(:dylan_family)
+ @eb_item = EnableBankingItem.create!(family: family, name: "EB", country_code: "FI", application_id: "app", client_certificate: "cert")
+ @akahu_account = AkahuAccount.create!(
+ akahu_item: AkahuItem.create!(family: family, name: "Akahu", app_token: "app", user_token: "user"),
+ name: "Everyday", account_id: "acc_encrypt_migration", currency: "NZD"
+ )
+ @lunchflow_account = lunchflow_items(:one).lunchflow_accounts.create!(name: "Brokerage", currency: "GBP", account_id: "encrypt-migration")
+ end
+
+ test "encrypts plaintext left by earlier syncs" do
+ write_raw(EnableBankingItem, @eb_item.id, "last_psu_ip", "203.0.113.9")
+ write_raw(AkahuAccount, @akahu_account.id, "formatted_account", "12-3456-7654321-00")
+ write_raw(LunchflowAccount, @lunchflow_account.id, "raw_holdings_payload", [ { "symbol" => "HOLDPROBE" } ].to_json, cast: "::jsonb")
+
+ # Still readable before the migration, so syncs keep working meanwhile
+ assert_equal "203.0.113.9", @eb_item.reload.last_psu_ip
+ assert_equal [ { "symbol" => "HOLDPROBE" } ], @lunchflow_account.reload.raw_holdings_payload
+
+ run_migration
+
+ assert_equal "203.0.113.9", @eb_item.reload.last_psu_ip
+ assert_equal "12-3456-7654321-00", @akahu_account.reload.formatted_account
+ assert_equal [ { "symbol" => "HOLDPROBE" } ], @lunchflow_account.reload.raw_holdings_payload
+ refute_includes @eb_item.read_attribute_before_type_cast(:last_psu_ip).to_s, "203.0.113.9"
+ refute_includes @akahu_account.read_attribute_before_type_cast(:formatted_account).to_s, "7654321"
+ refute_includes @lunchflow_account.read_attribute_before_type_cast(:raw_holdings_payload).to_s, "HOLDPROBE"
+ end
+
+ test "leaves values that are already encrypted unchanged" do
+ @akahu_account.update!(formatted_account: "12-3456-7654321-00")
+ ciphertext = @akahu_account.reload.read_attribute_before_type_cast(:formatted_account)
+
+ run_migration
+
+ assert_equal ciphertext, @akahu_account.reload.read_attribute_before_type_cast(:formatted_account)
+ assert_equal "12-3456-7654321-00", @akahu_account.formatted_account
+ end
+
+ test "leaves an already encrypted json payload unchanged" do
+ @lunchflow_account.update!(raw_holdings_payload: [ { "symbol" => "HOLDPROBE" } ])
+ ciphertext = stored_text(LunchflowAccount, @lunchflow_account.id, "raw_holdings_payload")
+
+ run_migration
+
+ assert_equal ciphertext, stored_text(LunchflowAccount, @lunchflow_account.id, "raw_holdings_payload")
+ assert_equal [ { "symbol" => "HOLDPROBE" } ], @lunchflow_account.reload.raw_holdings_payload
+ end
+
+ test "does not overwrite a value written after it was read" do
+ write_raw(EnableBankingItem, @eb_item.id, "last_psu_ip", "203.0.113.20")
+ migration = EncryptExistingProviderIdentifiers.new
+ migration.stubs(:each_stored_value).yields(@eb_item.id, "203.0.113.10")
+
+ migration.send(:encrypt_plaintext, EnableBankingItem, "last_psu_ip")
+
+ assert_equal "203.0.113.20", stored_text(EnableBankingItem, @eb_item.id, "last_psu_ip")
+ end
+
+ test "down writes the values back as plaintext" do
+ @eb_item.update!(last_psu_ip: "203.0.113.30")
+ @akahu_account.update!(formatted_account: "12-3456-7654321-00")
+ @lunchflow_account.update!(raw_holdings_payload: [ { "symbol" => "HOLDPROBE" } ])
+
+ run_migration(:down)
+
+ assert_equal "203.0.113.30", stored_text(EnableBankingItem, @eb_item.id, "last_psu_ip")
+ assert_equal "12-3456-7654321-00", stored_text(AkahuAccount, @akahu_account.id, "formatted_account")
+ assert_equal [ { "symbol" => "HOLDPROBE" } ], JSON.parse(stored_text(LunchflowAccount, @lunchflow_account.id, "raw_holdings_payload"))
+ assert_equal "203.0.113.30", @eb_item.reload.last_psu_ip
+ assert_equal [ { "symbol" => "HOLDPROBE" } ], @lunchflow_account.reload.raw_holdings_payload
+ end
+
+ private
+
+ def stored_text(model, id, column)
+ ActiveRecord::Base.connection.select_value(
+ model.unscoped.where(id: id).select(Arel.sql("#{column}::text")).to_sql
+ )
+ end
+
+ def write_raw(model, id, column, value, cast: "")
+ ActiveRecord::Base.connection.execute(ActiveRecord::Base.sanitize_sql([
+ "UPDATE #{model.quoted_table_name} SET #{column} = ?#{cast} WHERE id = ?", value, id
+ ]))
+ end
+
+ def run_migration(direction = :up)
+ ActiveRecord::Migration.suppress_messages do
+ EncryptExistingProviderIdentifiers.new.migrate(direction)
+ end
+ end
+end
diff --git a/test/migrations/remove_account_details_from_akahu_institution_metadata_migration_test.rb b/test/migrations/remove_account_details_from_akahu_institution_metadata_migration_test.rb
new file mode 100644
index 0000000000..793fa9b506
--- /dev/null
+++ b/test/migrations/remove_account_details_from_akahu_institution_metadata_migration_test.rb
@@ -0,0 +1,49 @@
+# frozen_string_literal: true
+
+require "test_helper"
+require Rails.root.join("db/migrate/20261015220000_remove_account_details_from_akahu_institution_metadata")
+
+class RemoveAccountDetailsFromAkahuInstitutionMetadataMigrationTest < ActiveSupport::TestCase
+ setup do
+ item = AkahuItem.create!(family: families(:dylan_family), name: "Akahu", app_token: "app", user_token: "user")
+ @account = AkahuAccount.create!(akahu_item: item, name: "Everyday", account_id: "acc_migration", currency: "NZD")
+ end
+
+ test "strips the account number and holder but keeps the institution details" do
+ @account.update_column(:institution_metadata, {
+ "id" => "conn_1", "name" => "Test Bank", "logo" => "logo.png",
+ "account_number" => "12-3456-7654321-00", "holder" => "Test Person"
+ })
+
+ run_migration
+
+ assert_equal({ "id" => "conn_1", "name" => "Test Bank", "logo" => "logo.png" }, @account.reload.institution_metadata)
+ end
+
+ test "strips either key when only one of them is present" do
+ other = AkahuAccount.create!(akahu_item: @account.akahu_item, name: "Savings", account_id: "acc_migration_2", currency: "NZD")
+ @account.update_column(:institution_metadata, { "name" => "Test Bank", "account_number" => "12-3456-7654321-00" })
+ other.update_column(:institution_metadata, { "name" => "Test Bank", "holder" => "Test Person" })
+
+ run_migration
+
+ assert_equal({ "name" => "Test Bank" }, @account.reload.institution_metadata)
+ assert_equal({ "name" => "Test Bank" }, other.reload.institution_metadata)
+ end
+
+ test "leaves metadata without those keys alone" do
+ @account.update_column(:institution_metadata, { "name" => "Test Bank" })
+
+ run_migration
+
+ assert_equal({ "name" => "Test Bank" }, @account.reload.institution_metadata)
+ end
+
+ private
+
+ def run_migration
+ ActiveRecord::Migration.suppress_messages do
+ RemoveAccountDetailsFromAkahuInstitutionMetadata.new.migrate(:up)
+ end
+ end
+end
diff --git a/test/models/akahu_item/importer_test.rb b/test/models/akahu_item/importer_test.rb
index 06d2df1687..5c02c0e609 100644
--- a/test/models/akahu_item/importer_test.rb
+++ b/test/models/akahu_item/importer_test.rb
@@ -92,6 +92,10 @@ class AkahuItem::ImporterTest < ActiveSupport::TestCase
assert_equal BigDecimal("123.45"), @akahu_account.current_balance
assert_equal "12-3456-0000000-00", @akahu_account.formatted_account
assert_equal "Test Bank", @akahu_account.institution_metadata["name"]
+ assert_not @akahu_account.institution_metadata.key?("account_number"),
+ "the account number belongs in the encrypted formatted_account only"
+ assert_not @akahu_account.institution_metadata.key?("holder"),
+ "the holder's name must not be copied into plaintext metadata"
transactions = @akahu_account.raw_transactions_payload
assert_equal [ "tx_1", "pending_1" ], transactions.map { |tx| tx["_id"] }