The personal finance app for everyone (by everyone)
Ruby
Handle SimpleFIN protocol-v2 errlist responses (#3954)
0xmarty_c337b38aa915
diff --git a/app/models/provider/simplefin.rb b/app/models/provider/simplefin.rbindex 786a933e04..7cf7b514b5 100644--- a/app/models/provider/simplefin.rb+++ b/app/models/provider/simplefin.rb@@ -54,7 +54,7 @@ class Provider::Simplefindef get_accounts(access_url, start_date: nil, end_date: nil, pending: nil)# Build query parameters- query_params = {}+ query_params = { "version" => "2" }# SimpleFin expects Unix timestamps for datesif start_datediff --git a/app/models/simplefin_item/importer.rb b/app/models/simplefin_item/importer.rbindex b60bcbaf8d..422f4c6158 100644--- a/app/models/simplefin_item/importer.rb+++ b/app/models/simplefin_item/importer.rb@@ -613,6 +613,14 @@ class SimplefinItem::Importerendend+ # A response with provider errors is not a complete upstream inventory.+ # Keep the accounts that were returned, but do not prune or repair+ # linkages from a list that may omit a failed connection or account.+ if partial_provider_response?(discovery_data)+ Rails.logger.info("SimpleFin discovery: skipping inventory reconciliation because the response was partial")+ return+ end+# Clean up orphaned SimplefinAccount records whose account_id no longer exists upstream.# This handles the case where a user deletes and re-adds an institution in SimpleFIN,# which generates new account IDs. Without this cleanup, both old (stale) and new@@ -717,14 +725,21 @@ class SimplefinItem::ImporterRails.logger.debug("SimpleFIN raw: #{accounts_data.inspect}")end- # Handle errors if present in response- if accounts_data[:errors] && accounts_data[:errors].any?- if accounts_data[:accounts].to_a.any?+ # Protocol v2 uses `errlist`; retain legacy `errors` compatibility.+ # Prefer the structured v2 list if a transitional server returns both.+ structured_errors = accounts_data[:errlist].presence+ provider_errors = structured_errors || accounts_data[:errors]+ if provider_errors.present?+ # `gen.*` errors apply to the response as a whole. Any accounts returned+ # alongside them may be stale or incomplete, so they cannot be imported+ # as a successful partial response. Only `gen.auth` invalidates the item.+ general_v2_error = structured_errors&.any? { |error| general_provider_error?(error) }+ if accounts_data[:accounts].to_a.any? && !general_v2_error# Partial failure: record errors for visibility but continue processing accounts- record_errors(accounts_data[:errors])+ record_errors(provider_errors, connections: accounts_data[:connections])else# Global failure: no accounts were returned; treat as fatal- handle_errors(accounts_data[:errors])+ handle_errors(provider_errors)return nilendend@@ -732,7 +747,7 @@ class SimplefinItem::Importer# Some servers return a top-level message/string rather than an errors arrayif accounts_data[:error].present?if accounts_data[:accounts].to_a.any?- record_errors([ accounts_data[:error] ])+ record_errors([ accounts_data[:error] ], connections: accounts_data[:connections])elsehandle_errors([ accounts_data[:error] ])return nil@@ -1000,7 +1015,7 @@ class SimplefinItem::Importer# requires_update - that would block sync for every other institution on# the same connection. The top-level handle_errors path is the correct# place to flag the item when the SimpleFIN token itself is dead.- def record_errors(errors)+ def record_errors(errors, connections: nil)arr = Array(errors)return if arr.empty?@@ -1012,37 +1027,21 @@ class SimplefinItem::Importer)arr.each do |error|- msg = if error.is_a?(String)- error- else- error[:description] || error[:message] || error[:error] || error.to_s- end- down = msg.to_s.downcase- category = if down.include?("timeout") || down.include?("timed out")- "network"- elsif down.include?("auth") || down.include?("reauth") || down.include?("forbidden") || down.include?("unauthorized") || down.include?("2fa") || down.include?("two-factor")- "auth"- elsif down.include?("429") || down.include?("rate limit")- "api"- else- "other"- end- register_error(message: msg, category: category)+ context = provider_error_context(error, connections)+ register_error(+ message: provider_error_message(error),+ category: provider_error_category(error),+ account_id: context[:account_id],+ name: context[:name]+ )endenddef handle_errors(errors)- error_messages = errors.map { |error| error.is_a?(String) ? error : (error[:description] || error[:message]) }.join(", ")+ error_messages = errors.map { |error| provider_error_message(error) }.join(", ")# Mark item as requiring update for authentication-related errors- needs_update = errors.any? do |error|- if error.is_a?(String)- error.downcase.include?("reauthenticate") || error.downcase.include?("authentication")- else- error[:code] == "auth_failure" || error[:code] == "token_expired" ||- error[:type] == "authentication_error"- end- end+ needs_update = errors.any? { |error| item_auth_error?(error) }if needs_updateRails.logger.warn("SimpleFin: marking item ##{simplefin_item.id} requires_update due to fatal auth error(s): #{error_messages}")@@ -1076,6 +1075,63 @@ class SimplefinItem::Importer)end+ def provider_error_message(error)+ return error if error.is_a?(String)++ error[:msg].presence || error[:description].presence || error[:message].presence || error[:error].presence || error.to_s+ end++ def provider_error_category(error)+ code = error.is_a?(String) ? "" : error[:code].to_s+ return "auth" if code.end_with?(".auth") || [ "auth_failure", "token_expired" ].include?(code)+ return "api" if code == "gen.api"++ message = provider_error_message(error).to_s.downcase+ if message.include?("timeout") || message.include?("timed out")+ "network"+ elsif message.include?("auth") || message.include?("reauth") || message.include?("forbidden") || message.include?("unauthorized") || message.include?("2fa") || message.include?("two-factor")+ "auth"+ elsif message.include?("429") || message.include?("rate limit")+ "api"+ else+ "other"+ end+ end++ def general_provider_error?(error)+ !error.is_a?(String) && error[:code].to_s.start_with?("gen.")+ end++ def partial_provider_response?(accounts_data)+ accounts_data[:errlist].present? || accounts_data[:errors].present? || accounts_data[:error].present?+ end++ def provider_error_context(error, connections)+ return {} if error.is_a?(String)++ code = error[:code].to_s+ if code.start_with?("act.")+ { account_id: error[:account_id] }+ elsif code.start_with?("con.")+ connection_id = error[:conn_id]+ connection = Array(connections).find { |candidate| candidate[:conn_id].to_s == connection_id.to_s }+ { name: connection&.dig(:name).presence || connection_id }+ else+ {}+ end+ end++ def item_auth_error?(error)+ if error.is_a?(String)+ message = error.downcase+ return message.include?("reauthenticate") || message.include?("authentication")+ end++ code = error[:code].to_s+ code == "gen.auth" || code == "auth_failure" || code == "token_expired" ||+ error[:type] == "authentication_error"+ end+# Classify exceptions into simple buckets for UI statsdef classify_error(e)msg = e.message.to_s.downcasediff --git a/test/models/provider/simplefin_test.rb b/test/models/provider/simplefin_test.rbindex 194c330378..5693c752ce 100644--- a/test/models/provider/simplefin_test.rb+++ b/test/models/provider/simplefin_test.rb@@ -135,6 +135,16 @@ class Provider::SimplefinTest < ActiveSupport::TestCase@provider.get_accounts(@access_url, pending: nil)end+ test "get_accounts requests protocol version 2" do+ mock_response = OpenStruct.new(code: 200, body: '{"accounts": []}')++ Provider::Simplefin.expects(:get)+ .with { |url| URI.parse(url).query.split("&").include?("version=2") }+ .returns(mock_response)++ @provider.get_accounts(@access_url)+ end+test "claim_access_url retries on network errors" dosetup_token = Base64.encode64("https://example.com/claim")mock_response = OpenStruct.new(code: 200, body: "https://example.com/access")diff --git a/test/models/simplefin_item/importer_errlist_test.rb b/test/models/simplefin_item/importer_errlist_test.rbnew file mode 100644index 0000000000..4eceea36e4--- /dev/null+++ b/test/models/simplefin_item/importer_errlist_test.rb@@ -0,0 +1,128 @@+require "test_helper"++class SimplefinItem::ImporterErrlistTest < ActiveSupport::TestCase+ setup do+ @family = families(:dylan_family)+ @item = SimplefinItem.create!(+ family: @family,+ name: "SF Conn",+ access_url: "https://example.com/access"+ )+ @sync = Sync.create!(syncable: @item)+ end++ test "records a v2 connection auth error from its code and message" do+ importer = importer_with(+ accounts: [ { id: "acct-1", name: "Checking" } ],+ connections: [ { conn_id: "conn-1", name: "My Bank" } ],+ errlist: [ { code: "con.auth", msg: "Action required", conn_id: "conn-1" } ]+ )++ result = importer.send(:fetch_accounts_data, start_date: 30.days.ago)++ assert_equal [ { id: "acct-1", name: "Checking" } ], result[:accounts]+ stats = @sync.reload.sync_stats+ assert_equal 1, stats.dig("error_buckets", "auth").to_i+ assert_equal "Action required", stats["errors"].first["message"]+ assert_equal "My Bank", stats["errors"].first["name"]+ assert_equal "good", @item.reload.status+ end++ test "records a v2 account error with its account id" do+ importer = importer_with(+ accounts: [ { id: "acct-1", name: "Checking" } ],+ errlist: [ { code: "act.failed", msg: "Account unavailable", account_id: "acct-2" } ]+ )++ importer.send(:fetch_accounts_data, start_date: 30.days.ago)++ error = @sync.reload.sync_stats["errors"].first+ assert_equal "acct-2", error["account_id"]+ assert_equal "Account unavailable", error["message"]+ end++ test "falls back from a blank v2 message to a legacy description" do+ importer = importer_with(+ accounts: [ { id: "acct-1", name: "Checking" } ],+ errlist: [ { code: "con.auth", msg: "", description: "Re-authenticate at My Bank", conn_id: "conn-1" } ]+ )++ importer.send(:fetch_accounts_data, start_date: 30.days.ago)++ assert_equal "Re-authenticate at My Bank", @sync.reload.sync_stats["errors"].first["message"]+ end++ test "connection auth without accounts fails without invalidating the access url" do+ importer = importer_with(+ accounts: [],+ errlist: [ { code: "con.auth", msg: "Action required", conn_id: "conn-1" } ]+ )++ assert_raises(Provider::Simplefin::SimplefinError) do+ importer.send(:fetch_accounts_data, start_date: 30.days.ago)+ end++ assert_equal "good", @item.reload.status+ end++ test "general auth without accounts invalidates the access url" do+ importer = importer_with(+ accounts: [],+ errlist: [ { code: "gen.auth", msg: "Credentials rejected" } ]+ )++ assert_raises(Provider::Simplefin::SimplefinError) do+ importer.send(:fetch_accounts_data, start_date: 30.days.ago)+ end++ assert_equal "requires_update", @item.reload.status+ end++ test "general auth with cached accounts still invalidates the access url" do+ importer = importer_with(+ accounts: [ { id: "acct-1", name: "Checking" } ],+ errlist: [ { code: "gen.auth", msg: "Credentials rejected" } ]+ )++ assert_raises(Provider::Simplefin::SimplefinError) do+ importer.send(:fetch_accounts_data, start_date: 30.days.ago)+ end++ assert_equal "requires_update", @item.reload.status+ end++ test "general api error with cached accounts is fatal without invalidating the access url" do+ importer = importer_with(+ accounts: [ { id: "acct-1", name: "Checking" } ],+ errlist: [ { code: "gen.api", msg: "Unsupported API request" } ]+ )++ assert_raises(Provider::Simplefin::SimplefinError) do+ importer.send(:fetch_accounts_data, start_date: 30.days.ago)+ end++ assert_equal "good", @item.reload.status+ end++ test "prefers errlist when a transitional server also returns legacy errors" do+ importer = importer_with(+ accounts: [ { id: "acct-1", name: "Checking" } ],+ errlist: [ { code: "con.auth", msg: "Structured message", conn_id: "conn-1" } ],+ errors: [ "Legacy duplicate" ]+ )++ importer.send(:fetch_accounts_data, start_date: 30.days.ago)++ errors = @sync.reload.sync_stats["errors"]+ assert_equal 1, errors.size+ assert_equal "Structured message", errors.first["message"]+ end++ private++ def importer_with(payload)+ provider = mock()+ provider.expects(:get_accounts).returns(payload)+ SimplefinItem::Importer.new(@item, simplefin_provider: provider, sync: @sync)+ end+enddiff --git a/test/models/simplefin_item/importer_orphan_prune_test.rb b/test/models/simplefin_item/importer_orphan_prune_test.rbindex e500481286..28c5fab308 100644--- a/test/models/simplefin_item/importer_orphan_prune_test.rb+++ b/test/models/simplefin_item/importer_orphan_prune_test.rb@@ -194,4 +194,32 @@ class SimplefinItem::ImporterOrphanPruneTest < ActiveSupport::TestCaseassert_nil @item.upstream_account_ids, "stale upstream_account_ids from a prior discovery must be cleared"end++ test "does not prune or record a complete inventory from partial discovery" do+ old_sfa = SimplefinAccount.create!(+ simplefin_item: @item,+ account_id: "ACT-old-id",+ name: "Old Account",+ currency: "USD",+ current_balance: 100,+ account_type: "checking"+ )++ mock_provider = mock()+ mock_provider.expects(:get_accounts).once.returns({+ accounts: [+ { id: "ACT-new-id", name: "New Account", balance: "200.00", currency: "USD", type: "checking" }+ ],+ errlist: [+ { code: "con.auth", msg: "Authentication required", conn_id: "CON-failed" }+ ]+ })++ importer = SimplefinItem::Importer.new(@item, simplefin_provider: mock_provider, sync: @sync)+ importer.send(:perform_account_discovery)++ assert_not_nil SimplefinAccount.find_by(id: old_sfa.id), "partial discovery must not prune omitted accounts"+ assert_not_nil @item.simplefin_accounts.find_by(account_id: "ACT-new-id"), "returned accounts should still import"+ assert_nil @item.upstream_account_ids, "partial discovery must not become the complete upstream inventory"+ endend