The personal finance app for everyone (by everyone)
Ruby
fix(plaid): stop duplicating accounts when Plaid reissues account IDs (#4726)
Weiqi Zhouc6dbf5ac1fc7
diff --git a/app/models/plaid_item/importer.rb b/app/models/plaid_item/importer.rbindex defca74321..b64b9d852b 100644--- a/app/models/plaid_item/importer.rb+++ b/app/models/plaid_item/importer.rb@@ -50,12 +50,11 @@ class PlaidItem::Importerdef fetch_and_import_accounts_datasnapshot = PlaidItem::AccountsSnapshot.new(plaid_item, plaid_provider: plaid_provider)+ returned_ids = snapshot.accounts.map(&:account_id)PlaidItem.transaction dosnapshot.accounts.each do |raw_account|- plaid_account = plaid_item.plaid_accounts.find_or_initialize_by(- plaid_id: raw_account.account_id- )+ plaid_account = plaid_account_for(raw_account, returned_ids: returned_ids)PlaidAccount::Importer.new(plaid_account,@@ -69,4 +68,73 @@ class PlaidItem::Importerplaid_item.update!(next_cursor: snapshot.transactions_cursor)endend++ def plaid_account_for(raw_account, returned_ids:)+ plaid_item.plaid_accounts.find_by(plaid_id: raw_account.account_id) ||+ reissued_plaid_account(raw_account, returned_ids: returned_ids) ||+ plaid_item.plaid_accounts.new(plaid_id: raw_account.account_id)+ end++ # At institutions with tokenized account numbers, such as Chase, re-consenting+ # through update mode can make Plaid issue a new account_id for an account it+ # already shares, while persistent_account_id stays the same. Moving the+ # existing PlaidAccount to the new id keeps it, and the Sure account linked to+ # it, instead of importing the account a second time. Only an account Plaid no+ # longer returns under its old id is taken over. The payload is encrypted, so+ # the match is made in Ruby.+ #+ # An Item duplicated before this matching existed holds stale copies next to+ # the one in use. A copy linked to a Sure account is preferred, then the most+ # recently created, which is the one Plaid moved to last. updated_at cannot+ # tell them apart, because clearing an omitted copy's liabilities updates it.+ def reissued_plaid_account(raw_account, returned_ids:)+ persistent_id = raw_account.try(:persistent_account_id).presence+ return unless persistent_id++ candidates = omitted_accounts(returned_ids)+ matches = candidates.select { |_, candidate_persistent_id| candidate_persistent_id == persistent_id }.keys+ plaid_account = matches.max_by { |candidate| [ candidate.current_account ? 1 : 0, candidate.created_at ] }+ return unless plaid_account++ candidates.delete(plaid_account)+ plaid_account.plaid_id = raw_account.account_id+ plaid_account+ end++ # The accounts Plaid did not return in this import, each with its+ # persistent_account_id. They are loaded and their payloads decrypted once,+ # when the first unknown account_id needs them, so an unreadable payload is+ # logged once. An account is removed once it has been taken over.+ def omitted_accounts(returned_ids)+ @omitted_accounts ||= plaid_item.plaid_accounts.where.not(plaid_id: returned_ids).to_h do |plaid_account|+ [ plaid_account, persistent_account_id_of(plaid_account) ]+ end+ end++ # A payload that cannot be decrypted is left unmatched, so the account is+ # imported as it was before this matching rather than failing the import.+ def persistent_account_id_of(plaid_account)+ payload = plaid_account.raw_payload+ payload["persistent_account_id"] if payload.is_a?(Hash)+ rescue ActiveRecord::Encryption::Errors::Decryption+ log_unreadable_payload(plaid_account)+ nil+ end++ def log_unreadable_payload(plaid_account)+ DebugLogEntry.capture(+ category: "provider_sync",+ level: "warn",+ message: "Skipped a Plaid account with an unreadable payload when matching a reissued account_id",+ source: self.class.name,+ provider_key: "plaid",+ family: plaid_item.family,+ account: plaid_account.current_account,+ account_provider: plaid_account.account_provider,+ metadata: {+ plaid_item_id: plaid_item.id,+ plaid_account_id: plaid_account.id+ }+ )+ endenddiff --git a/test/models/plaid_item/importer_test.rb b/test/models/plaid_item/importer_test.rbindex a7e54b1b6a..eff0fc7476 100644--- a/test/models/plaid_item/importer_test.rb+++ b/test/models/plaid_item/importer_test.rb@@ -50,6 +50,149 @@ class PlaidItem::ImporterTest < ActiveSupport::TestCase@importer.importend+ # At institutions with tokenized account numbers, such as Chase, re-consenting+ # through update mode can make Plaid issue a new account_id for an account it+ # already shares. persistent_account_id stays the same across that change.+ test "updates the existing account when Plaid reissues its account_id" do+ existing = plaid_accounts(:one)+ existing.update!(raw_payload: { "account_id" => existing.plaid_id, "persistent_account_id" => "persistent_acc_1" })++ stub_accounts_snapshot(+ raw_plaid_account(account_id: "acc_mock_1_reissued", persistent_account_id: "persistent_acc_1")+ )++ assert_no_difference -> { @plaid_item.plaid_accounts.count } do+ @importer.import+ end++ assert_equal "acc_mock_1_reissued", existing.reload.plaid_id+ end++ test "imports an account with a new persistent_account_id as a new account" do+ existing = plaid_accounts(:one)+ existing.update!(raw_payload: { "account_id" => existing.plaid_id, "persistent_account_id" => "persistent_acc_1" })++ stub_accounts_snapshot(+ raw_plaid_account(account_id: existing.plaid_id, persistent_account_id: "persistent_acc_1"),+ raw_plaid_account(account_id: "acc_new_card", persistent_account_id: "persistent_acc_2")+ )++ assert_difference -> { @plaid_item.plaid_accounts.count }, 1 do+ @importer.import+ end++ assert_equal "acc_mock_1", existing.reload.plaid_id+ assert @plaid_item.plaid_accounts.exists?(plaid_id: "acc_new_card")+ end++ test "does not take over an account Plaid still returns under its own id" do+ existing = plaid_accounts(:one)+ existing.update!(raw_payload: { "account_id" => existing.plaid_id, "persistent_account_id" => "persistent_acc_1" })++ stub_accounts_snapshot(+ raw_plaid_account(account_id: existing.plaid_id, persistent_account_id: "persistent_acc_1"),+ raw_plaid_account(account_id: "acc_mock_1_reissued", persistent_account_id: "persistent_acc_1")+ )++ assert_difference -> { @plaid_item.plaid_accounts.count }, 1 do+ @importer.import+ end++ assert_equal "acc_mock_1", existing.reload.plaid_id+ end++ # Clearing the liabilities of an omitted copy saves it, so the stale copy can+ # carry the newest updated_at.+ test "takes over the newest copy of an already duplicated account" do+ stale = plaid_accounts(:one)+ stale.update!(raw_payload: { "account_id" => stale.plaid_id, "persistent_account_id" => "persistent_acc_1" })+ in_use = duplicate_plaid_account(plaid_id: "acc_mock_1_duplicate", persistent_account_id: "persistent_acc_1")+ AccountProvider.create!(account: accounts(:credit_card), provider: in_use)+ stale.update_columns(created_at: 2.days.ago, updated_at: Time.current)+ in_use.update_columns(created_at: 1.day.ago, updated_at: 1.day.ago)++ stub_accounts_snapshot(+ raw_plaid_account(account_id: "acc_mock_1_reissued", persistent_account_id: "persistent_acc_1")+ )++ assert_no_difference -> { @plaid_item.plaid_accounts.count } do+ @importer.import+ end++ assert_equal "acc_mock_1_reissued", in_use.reload.plaid_id+ assert_equal "acc_mock_1", stale.reload.plaid_id+ end++ test "prefers a copy linked to a Sure account over a newer unlinked copy" do+ linked = plaid_accounts(:one)+ linked.update!(raw_payload: { "account_id" => linked.plaid_id, "persistent_account_id" => "persistent_acc_1" })+ linked.update_columns(created_at: 2.days.ago)+ unlinked = duplicate_plaid_account(plaid_id: "acc_mock_1_duplicate", persistent_account_id: "persistent_acc_1")++ stub_accounts_snapshot(+ raw_plaid_account(account_id: "acc_mock_1_reissued", persistent_account_id: "persistent_acc_1")+ )++ assert_no_difference -> { @plaid_item.plaid_accounts.count } do+ @importer.import+ end++ assert_equal "acc_mock_1_reissued", linked.reload.plaid_id+ assert_equal "acc_mock_1_duplicate", unlinked.reload.plaid_id+ end++ test "imports a reissued account as new when a stored payload cannot be decrypted" do+ existing = plaid_accounts(:one)+ existing.update!(raw_payload: { "account_id" => existing.plaid_id, "persistent_account_id" => "persistent_acc_1" })+ account_provider = AccountProvider.create!(account: accounts(:connected), provider: existing)+ PlaidAccount.any_instance.stubs(:raw_payload).raises(ActiveRecord::Encryption::Errors::Decryption)++ stub_accounts_snapshot(+ raw_plaid_account(account_id: "acc_mock_1_reissued", persistent_account_id: "persistent_acc_1")+ )++ assert_difference -> { @plaid_item.plaid_accounts.count }, 1 do+ @importer.import+ end++ assert_equal "acc_mock_1", existing.reload.plaid_id++ entry = DebugLogEntry.find_by!(source: "PlaidItem::Importer", level: "warn", provider_key: "plaid")+ assert_equal account_provider, entry.account_provider+ assert_equal accounts(:connected), entry.account+ end++ test "reads and logs an unreadable payload once per import" do+ existing = plaid_accounts(:one)+ existing.update!(raw_payload: { "account_id" => existing.plaid_id, "persistent_account_id" => "persistent_acc_1" })+ PlaidAccount.any_instance.expects(:raw_payload).once.raises(ActiveRecord::Encryption::Errors::Decryption)++ stub_accounts_snapshot(+ raw_plaid_account(account_id: "acc_mock_1_reissued", persistent_account_id: "persistent_acc_1"),+ raw_plaid_account(account_id: "acc_new_card", persistent_account_id: "persistent_acc_2")+ )++ assert_difference -> { DebugLogEntry.where(source: "PlaidItem::Importer").count }, 1 do+ @importer.import+ end+ end++ test "takes over an omitted account only once per import" do+ existing = plaid_accounts(:one)+ existing.update!(raw_payload: { "account_id" => existing.plaid_id, "persistent_account_id" => "persistent_acc_1" })++ stub_accounts_snapshot(+ raw_plaid_account(account_id: "acc_mock_1_reissued", persistent_account_id: "persistent_acc_1"),+ raw_plaid_account(account_id: "acc_mock_1_reissued_again", persistent_account_id: "persistent_acc_1")+ )++ assert_difference -> { @plaid_item.plaid_accounts.count }, 1 do+ @importer.import+ end++ assert_equal "acc_mock_1_reissued", existing.reload.plaid_id+ end+test "clears requires update status after a successful import" do@plaid_item.update!(status: :requires_update)@importer.stubs(:fetch_and_import_item_data)@@ -73,4 +216,44 @@ class PlaidItem::ImporterTest < ActiveSupport::TestCaseassert_predicate @plaid_item.reload, :requires_update?end++ private+ def raw_plaid_account(account_id:, persistent_account_id:)+ Plaid::AccountBase.new(+ account_id: account_id,+ persistent_account_id: persistent_account_id,+ name: "Plaid Depository Account",+ mask: "0000",+ type: "depository",+ subtype: "checking",+ balances: Plaid::AccountBalance.new(current: 1000, available: 1000, iso_currency_code: "USD")+ )+ end++ def duplicate_plaid_account(plaid_id:, persistent_account_id:)+ @plaid_item.plaid_accounts.create!(+ plaid_id: plaid_id,+ name: "Plaid Depository Account",+ plaid_type: "depository",+ currency: "USD",+ current_balance: 1000,+ raw_payload: { "account_id" => plaid_id, "persistent_account_id" => persistent_account_id }+ )+ end++ def stub_accounts_snapshot(*raw_accounts)+ PlaidItem::AccountsSnapshot.any_instance.stubs(:accounts).returns(raw_accounts)+ raw_accounts.each do |raw_account|+ PlaidItem::AccountsSnapshot.any_instance.stubs(:get_account_data).with(raw_account.account_id).returns(+ PlaidItem::AccountsSnapshot::AccountData.new(+ account_data: raw_account,+ transactions_data: nil,+ investments_data: nil,+ liabilities_data: nil+ )+ )+ end+ PlaidItem::AccountsSnapshot.any_instance.stubs(:transactions_cursor).returns("test_cursor_1")+ @importer.stubs(:fetch_and_import_item_data)+ endend