The personal finance app for everyone (by everyone)
Ruby
fix(transfers): prevent duplicate creation on double-submit (#3342)
GFR47c46843e1a1
diff --git a/app/controllers/transfers_controller.rb b/app/controllers/transfers_controller.rbindex 5a7f7e54eb..81a851f32a 100644--- a/app/controllers/transfers_controller.rb+++ b/app/controllers/transfers_controller.rb@@ -4,6 +4,8 @@ class TransfersController < ApplicationControllerbefore_action :set_transfer, only: %i[show destroy update update_tags mark_as_recurring]before_action :set_accounts, only: %i[new create]+ helper_method :new_transfer_idempotency_key+def new@transfer = Transfer.new@from_account_id = params[:from_account_id]@@ -43,7 +45,8 @@ class TransfersController < ApplicationControllerexchange_rate: transfer_params[:exchange_rate].presence&.to_d,source_fee_amount: transfer_params[:source_fee_amount],destination_fee_amount: transfer_params[:destination_fee_amount],- tag_ids: transfer_params[:tag_ids]+ tag_ids: transfer_params[:tag_ids],+ idempotency_key: submitted_idempotency_key).createif @transfer.persisted?@@ -61,6 +64,7 @@ class TransfersController < ApplicationController@transfer ||= Transfer.new@transfer.tag_ids = transfer_params[:tag_ids]@transfer.errors.add(:base, t(".exchange_rate_unavailable"))+ @from_account_id = transfer_params[:from_account_id]set_accounts@tags = Current.family.tags.alphabeticallyrender :new, status: :unprocessable_entity@@ -68,6 +72,15 @@ class TransfersController < ApplicationController@transfer ||= Transfer.new@transfer.tag_ids = transfer_params[:tag_ids]@transfer.errors.add(:date, t(".date_invalid"))+ @from_account_id = transfer_params[:from_account_id]+ set_accounts+ @tags = Current.family.tags.alphabetically+ render :new, status: :unprocessable_entity+ rescue Transfer::Creator::StaleIdempotencyKeyError+ @transfer ||= Transfer.new+ @transfer.tag_ids = transfer_params[:tag_ids]+ @transfer.errors.add(:base, t(".stale_form"))+ @from_account_id = transfer_params[:from_account_id]set_accounts@tags = Current.family.tags.alphabeticallyrender :new, status: :unprocessable_entity@@ -193,6 +206,23 @@ class TransfersController < ApplicationControllerparams.require(:transfer).permit(:from_account_id, :to_account_id, :amount, :date, :name, :excluded, :exchange_rate, :source_fee_amount, :destination_fee_amount, tag_ids: [])end+ # Anti-double-submit token: a random UUID rendered fresh on every "new+ # transfer" form load, echoed back on submit, only ever trusted to look+ # like something we could have generated (see+ # Transfer::Creator#find_existing_transfer for how it's used to+ # de-duplicate).+ UUID_FORMAT = /\A[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\z/i+ private_constant :UUID_FORMAT++ def submitted_idempotency_key+ key = params.dig(:transfer, :idempotency_key)+ key if key.is_a?(String) && key.match?(UUID_FORMAT)+ end++ def new_transfer_idempotency_key+ @new_transfer_idempotency_key ||= submitted_idempotency_key || SecureRandom.uuid+ end+def set_accounts@accounts = accessible_accounts.alphabeticallydiff --git a/app/models/transfer.rb b/app/models/transfer.rbindex 4bf3eda773..88afa2a9d1 100644--- a/app/models/transfer.rb+++ b/app/models/transfer.rb@@ -109,6 +109,13 @@ class Transfer < ApplicationRecordnext unless Transaction.exists?(transaction.id)begintransaction.update!(kind: "standard")+ # The entry survives this destroy (only the Transfer join row and+ # fee transactions go away), but its idempotency_key must not: a+ # later retry of the original create request looks up that key,+ # finds no Transfer anymore, and would otherwise hit the unique+ # index on the stale entry and raise instead of creating a new+ # transfer (see Transfer::Creator#find_existing_transfer).+ transaction.entry.update!(idempotency_key: nil) if transaction.entry&.idempotency_key.present?rescue ActiveRecord::RecordNotFoundrescue NoMethodErrornextdiff --git a/app/models/transfer/creator.rb b/app/models/transfer/creator.rbindex bf8b1ed071..8119c2c22f 100644--- a/app/models/transfer/creator.rb+++ b/app/models/transfer/creator.rb@@ -1,5 +1,11 @@class Transfer::Creator- def initialize(family:, source_account_id:, destination_account_id:, date:, amount:, exchange_rate: nil, source_fee_amount: nil, destination_fee_amount: nil, tag_ids: nil)+ # Raised when the submitted idempotency key already belongs to an entry,+ # but that entry's transfer doesn't match the current request (different+ # destination/amount/date) — i.e. a stale key from a cached form rather+ # than a genuine double-submit. See #find_existing_transfer.+ StaleIdempotencyKeyError = Class.new(StandardError)++ def initialize(family:, source_account_id:, destination_account_id:, date:, amount:, exchange_rate: nil, source_fee_amount: nil, destination_fee_amount: nil, tag_ids: nil, idempotency_key: nil)@family = family@source_account = family.accounts.find(source_account_id) # early throw if not found@destination_account = family.accounts.find(destination_account_id) # early throw if not found@@ -8,6 +14,7 @@ class Transfer::Creator@source_fee_amount = source_fee_amount.to_d@destination_fee_amount = destination_fee_amount.to_d@tag_ids = Array(tag_ids).reject(&:blank?)+ @idempotency_key = idempotency_keyif exchange_rate.present?rate_value = exchange_rate.to_d@@ -22,6 +29,15 @@ class Transfer::Creatorraise ArgumentError, "source_fee_amount must be non-negative" if source_fee_amount.negative?raise ArgumentError, "destination_fee_amount must be non-negative" if destination_fee_amount.negative?+ # Sequential double-submit guard: the form was already submitted+ # successfully once (double-click, browser retry, user reopening the+ # dialog after a slow response) and the first request already committed+ # by the time this one runs. Return the existing transfer instead of+ # creating a second, identical one.+ if idempotency_key && (existing_transfer = find_existing_transfer)+ return existing_transfer+ end+transfer = Transfer.new(inflow_transaction: inflow_transaction,outflow_transaction: outflow_transaction,@@ -29,7 +45,14 @@ class Transfer::Creatoramount: amount)- Transfer.transaction do+ # requires_new: true opens a savepoint rather than joining whatever+ # transaction the caller may already be in, so a RecordNotUnique below+ # only rolls back this block, not any outer transaction - keeping the+ # retry lookup in the rescue usable instead of hitting+ # PG::InFailedSqlTransaction (see Account::ReconciliationManager for the+ # same fix applied to valuations, and the CodeRabbit/Codex findings that+ # prompted it).+ Transfer.transaction(requires_new: true) doif source_fee_amount > 0transfer.fee_transactions << build_source_fee_transactionend@@ -44,10 +67,89 @@ class Transfer::Creatordestination_account.sync_latertransfer+ rescue ActiveRecord::RecordNotUnique+ # Concurrent-request backstop: two near-simultaneous submissions both+ # passed the pre-check above (neither saw the other's row yet) and both+ # reached #create. The partial unique index on entries(account_id,+ # idempotency_key) lets exactly one leg's INSERT win, which rolls back+ # this entire Transfer.transaction block (no half-created transfer left+ # behind). Return the winning transfer instead of creating a duplicate+ # or raising a raw DB error to the user.+ #+ # The INSERT hitting the unique index proves an entry with this key+ # already exists on source_account, but find_existing_transfer only+ # returns it when it matches the current request - so a nil here means+ # the key belongs to a *different*, stale request (e.g. a cached form+ # resubmitted with a new destination/amount/date), not a genuine retry.+ # Surface that distinctly instead of re-raising the raw DB error.+ existing_transfer = idempotency_key && find_existing_transfer+ raise StaleIdempotencyKeyError unless existing_transfer++ existing_transferendprivate- attr_reader :family, :source_account, :destination_account, :date, :amount, :exchange_rate, :source_fee_amount, :destination_fee_amount, :tag_ids+ attr_reader :family, :source_account, :destination_account, :date, :amount, :exchange_rate, :source_fee_amount, :destination_fee_amount, :tag_ids, :idempotency_key++ # Scoped to source_account + idempotency_key so it only ever finds a+ # transfer this same key could plausibly refer to, but the key alone+ # isn't enough: a stale hidden field (Turbo Drive cache, reopened+ # dialog) can resubmit an old key for a request that's since changed+ # destination/amount/date. Verifying those fields against the request+ # keeps a genuinely different transfer from being silently discarded+ # in favor of returning the old one.+ def find_existing_transfer+ transfer = source_account.entries.find_by(idempotency_key: idempotency_key)&.entryable&.transfer+ return nil unless transfer+ return nil unless matches_request?(transfer)++ transfer+ end++ # Compares against every persisted effect of #create, not just accounts+ # and date/amount - a retry with the same key but a different+ # exchange_rate or fee would otherwise be reported as "success" while+ # silently keeping the old inflow amount and fee entries.+ #+ # inflow_converted_amount re-applies the current request's exchange_rate+ # (or re-fetches the rate for the same date, which is cached/stable) to+ # compare against what's actually persisted, rather than trying to+ # recover the original request's exchange_rate from stored state (it+ # isn't persisted anywhere - only its effect on the inflow amount is).+ # A rate that's no longer available on retry means this isn't a+ # same-request retry either, so treat that as a mismatch too and let the+ # normal create path surface the real Money::ConversionError.+ def matches_request?(transfer)+ outflow_entry = transfer.outflow_transaction.entry+ inflow_entry = transfer.inflow_transaction.entry++ outflow_entry.account_id == source_account.id &&+ inflow_entry.account_id == destination_account.id &&+ outflow_entry.date == date &&+ outflow_entry.amount == amount &&+ inflow_entry.amount == inflow_converted_amount * -1 &&+ transfer.derived_source_fee_amount == source_fee_amount &&+ transfer.derived_destination_fee_amount == destination_fee_amount+ rescue Money::ConversionError+ false+ end++ # Every leg gets a role-specific suffix except the outflow (find_existing_transfer+ # looks it up by the bare key). This matters because the unique index is+ # scoped per account_id, and the form doesn't prevent selecting the same+ # account as both source and destination - without distinct suffixes,+ # the inflow (and a fee leg sharing its primary leg's account) would+ # collide with another leg under that same account instead of with a+ # genuine duplicate submission. Deliberately its own column, not+ # external_id/source - see+ # db/migrate/20260902180400_add_idempotency_key_to_entries.rb for why+ # reusing those provider-linkage fields here would be wrong.+ def entry_idempotency_attrs(leg: :outflow)+ return {} unless idempotency_key++ key = leg == :outflow ? idempotency_key : "#{idempotency_key}-#{leg}"+ { idempotency_key: key }+ enddef apply_tags!(transfer)resolved_ids = family.tags.where(id: tag_ids).pluck(:id)@@ -71,6 +173,7 @@ class Transfer::Creatordate: date,name: name,user_modified: true,+ **entry_idempotency_attrs(leg: :outflow)))end@@ -92,6 +195,7 @@ class Transfer::Creatordate: date,name: name,user_modified: true,+ **entry_idempotency_attrs(leg: :inflow)))end@@ -106,6 +210,7 @@ class Transfer::Creatorcurrency: source_account.currency,date: date,name: "Transfer fee — #{name_prefix} to #{destination_account.name}",+ **entry_idempotency_attrs(leg: :source_fee)))end@@ -120,6 +225,7 @@ class Transfer::Creatorcurrency: destination_account.currency,date: date,name: "Transfer fee — #{name_prefix} from #{source_account.name}",+ **entry_idempotency_attrs(leg: :destination_fee)))enddiff --git a/app/views/transfers/_form.html.erb b/app/views/transfers/_form.html.erbindex 0dbb22e7b0..740345717e 100644--- a/app/views/transfers/_form.html.erb+++ b/app/views/transfers/_form.html.erb@@ -7,6 +7,12 @@</div><% end %>+ <%# Anti-double-submit token: a fresh UUID per page load, echoed back on+ submit. TransfersController#create / Transfer::Creator use it to+ recognize a repeat submission (double-click, retry, or a genuine+ concurrent race) and avoid creating a duplicate transfer. %>+ <%= hidden_field_tag "transfer[idempotency_key]", new_transfer_idempotency_key %>+<%# Hide expense/income tabs when creating a transfer involving an investment or crypto account. %><% show_type_tabs = true %><% account_ids = [] %>diff --git a/config/locales/views/transfers/de.yml b/config/locales/views/transfers/de.ymlindex a7dd616b82..8f0cb9ca75 100644--- a/config/locales/views/transfers/de.yml+++ b/config/locales/views/transfers/de.yml@@ -6,6 +6,7 @@ de:exchange_rate_unavailable: Kein Wechselkurs für die gewählten Währungen und dasDatum verfügbardate_invalid: ist ungültig+ stale_form: Dieses Formular wurde bereits mit anderen Angaben übermittelt. Bitte lade die Seite neu und versuche es erneut.destroy:success: Überweisung entferntform:diff --git a/config/locales/views/transfers/en.yml b/config/locales/views/transfers/en.ymlindex 1bd194f747..b039ac3bfa 100644--- a/config/locales/views/transfers/en.yml+++ b/config/locales/views/transfers/en.yml@@ -5,6 +5,7 @@ en:success: Transfer createdexchange_rate_unavailable: Exchange rate unavailable for selected currencies and datedate_invalid: is invalid+ stale_form: This form was already submitted with different details. Please refresh the page and try again.destroy:success: Transfer removedform:diff --git a/test/controllers/transfers_controller_test.rb b/test/controllers/transfers_controller_test.rbindex 07983a0b84..94b2d9cbfa 100644--- a/test/controllers/transfers_controller_test.rb+++ b/test/controllers/transfers_controller_test.rb@@ -25,6 +25,271 @@ class TransfersControllerTest < ActionDispatch::IntegrationTestendend+ test "resubmitting the same idempotency key does not create a duplicate transfer" do+ idempotency_key = SecureRandom.uuid+ params = {+ transfer: {+ from_account_id: accounts(:depository).id,+ to_account_id: accounts(:credit_card).id,+ date: Date.current,+ amount: 100,+ name: "Test Transfer",+ idempotency_key: idempotency_key+ }+ }++ assert_difference "Transfer.count", 1 do+ assert_difference "Entry.count", 2 do+ post transfers_url, params: params+ end+ end+ first_transfer = Transfer.order(:created_at).last++ # Simulates a double-click or a browser retry: same form, same+ # idempotency key, submitted again after the first request already+ # completed and committed.+ assert_no_difference [ "Transfer.count", "Entry.count" ] do+ post transfers_url, params: params+ end+ assert_redirected_to transactions_path+ end++ test "the idempotency key does not mark either leg as provider-linked" do+ # Regression test: the key must not be stored in external_id/source+ # (Entry#linked? = external_id.present?), or an ordinary manual transfer+ # would incorrectly look provider-synced.+ post transfers_url, params: {+ transfer: {+ from_account_id: accounts(:depository).id,+ to_account_id: accounts(:credit_card).id,+ date: Date.current,+ amount: 100,+ name: "Test Transfer",+ source_fee_amount: 3,+ idempotency_key: SecureRandom.uuid+ }+ }++ transfer = Transfer.order(:created_at).last+ [ transfer.outflow_transaction.entry, transfer.inflow_transaction.entry, transfer.fee_transactions.first.entry ].each do |entry|+ assert_not entry.linked?+ assert_nil entry.external_id+ assert_nil entry.source+ end+ end++ test "each leg gets a distinct idempotency key so fee legs don't collide with their primary leg" do+ # Regression test: the outflow/source-fee share source_account, and the+ # inflow/destination-fee share destination_account. The unique index is+ # scoped per account_id, so without role-specific suffixes a fee leg+ # would collide with its primary leg under the same idempotency key.+ post transfers_url, params: {+ transfer: {+ from_account_id: accounts(:depository).id,+ to_account_id: accounts(:credit_card).id,+ date: Date.current,+ amount: 100,+ name: "Test Transfer",+ source_fee_amount: 2,+ destination_fee_amount: 3,+ idempotency_key: SecureRandom.uuid+ }+ }++ transfer = Transfer.order(:created_at).last+ keys = [+ transfer.outflow_transaction.entry.idempotency_key,+ transfer.inflow_transaction.entry.idempotency_key,+ transfer.fee_transactions.map { |t| t.entry.idempotency_key }+ ].flatten++ assert_equal keys.uniq.length, keys.length+ assert keys.all?(&:present?)+ end++ test "handles a genuine concurrent double-submit without raising or duplicating" do+ idempotency_key = SecureRandom.uuid+ from_account = accounts(:depository)+ to_account = accounts(:credit_card)++ # Simulates the race: another request with the same idempotency key wins+ # and commits its transfer in the window between our pre-check (which+ # therefore still sees nothing, hence the first `nil`) and our own+ # Transfer#save! (which then hits the real partial unique index on+ # entries(account_id, idempotency_key) and raises RecordNotUnique,+ # exactly like the DB would under real concurrent requests). The rescue+ # then re-runs the same lookup, this time finding the winner.+ winning_transfer = Transfer::Creator.new(+ family: users(:family_admin).family,+ source_account_id: from_account.id,+ destination_account_id: to_account.id,+ date: Date.current,+ amount: 100,+ idempotency_key: idempotency_key+ ).create+ Transfer::Creator.any_instance.stubs(:find_existing_transfer).returns(nil, winning_transfer)+ Transfer.any_instance.stubs(:save!).raises(ActiveRecord::RecordNotUnique.new("duplicate key value violates unique constraint"))++ assert_no_difference [ "Transfer.count", "Entry.count" ] do+ post transfers_url, params: {+ transfer: {+ from_account_id: from_account.id,+ to_account_id: to_account.id,+ date: Date.current,+ amount: 100,+ name: "Test Transfer",+ idempotency_key: idempotency_key+ }+ }+ end++ assert_redirected_to transactions_path+ end++ test "a RecordNotUnique with no matching transfer is not silently swallowed" do+ idempotency_key = SecureRandom.uuid++ # Defensive-branch coverage: if the unique index ever rejects an insert+ # for a reason other than "another request with this exact idempotency+ # key already won," we must not pretend it succeeded - it should+ # surface as a stale-form error instead of a raw DB exception.+ Transfer::Creator.any_instance.stubs(:find_existing_transfer).returns(nil)+ Transfer.any_instance.stubs(:save!).raises(ActiveRecord::RecordNotUnique.new("duplicate key value violates unique constraint"))++ assert_no_difference [ "Transfer.count", "Entry.count" ] do+ post transfers_url, params: {+ transfer: {+ from_account_id: accounts(:depository).id,+ to_account_id: accounts(:credit_card).id,+ date: Date.current,+ amount: 100,+ name: "Test Transfer",+ idempotency_key: idempotency_key+ }+ }+ end++ assert_response :unprocessable_entity+ end++ test "reusing a key for a genuinely different request does not silently return the old transfer" do+ idempotency_key = SecureRandom.uuid+ from_account = accounts(:depository)+ to_account = accounts(:credit_card)+ other_destination = accounts(:other_liability)++ assert_difference "Transfer.count", 1 do+ post transfers_url, params: {+ transfer: {+ from_account_id: from_account.id,+ to_account_id: to_account.id,+ date: Date.current,+ amount: 100,+ name: "Test Transfer",+ idempotency_key: idempotency_key+ }+ }+ end++ # Simulates a stale hidden field (cached page / reopened dialog) still+ # carrying the first request's key while the user changed the+ # destination account before resubmitting.+ assert_no_difference [ "Transfer.count", "Entry.count" ] do+ post transfers_url, params: {+ transfer: {+ from_account_id: from_account.id,+ to_account_id: other_destination.id,+ date: Date.current,+ amount: 100,+ name: "Test Transfer",+ idempotency_key: idempotency_key+ }+ }+ end++ assert_response :unprocessable_entity+ end++ test "reusing a key with a different fee does not silently return the old transfer" do+ idempotency_key = SecureRandom.uuid+ from_account = accounts(:depository)+ to_account = accounts(:credit_card)++ assert_difference "Transfer.count", 1 do+ post transfers_url, params: {+ transfer: {+ from_account_id: from_account.id,+ to_account_id: to_account.id,+ date: Date.current,+ amount: 100,+ name: "Test Transfer",+ idempotency_key: idempotency_key+ }+ }+ end++ # Same accounts/date/amount/key as the first request, but a fee was+ # added before resubmitting - the persisted effect differs, so this+ # must not be reported as a successful retry of the fee-less transfer.+ assert_no_difference [ "Transfer.count", "Entry.count" ] do+ post transfers_url, params: {+ transfer: {+ from_account_id: from_account.id,+ to_account_id: to_account.id,+ date: Date.current,+ amount: 100,+ name: "Test Transfer",+ source_fee_amount: 5,+ idempotency_key: idempotency_key+ }+ }+ end++ assert_response :unprocessable_entity+ end++ test "reusing a key with a different exchange rate does not silently return the old transfer" do+ idempotency_key = SecureRandom.uuid+ usd_account = accounts(:depository)+ eur_account = users(:family_admin).family.accounts.create!(+ name: "EUR Account",+ balance: 1000,+ currency: "EUR",+ accountable: Depository.new+ )++ assert_difference "Transfer.count", 1 do+ post transfers_url, params: {+ transfer: {+ from_account_id: usd_account.id,+ to_account_id: eur_account.id,+ date: Date.current,+ amount: 100,+ exchange_rate: 0.9,+ idempotency_key: idempotency_key+ }+ }+ end++ # Same accounts/date/amount/key, but a different exchange rate - the+ # persisted inflow amount would differ, so this must not be reported as+ # a successful retry of the first, differently-converted transfer.+ assert_no_difference [ "Transfer.count", "Entry.count" ] do+ post transfers_url, params: {+ transfer: {+ from_account_id: usd_account.id,+ to_account_id: eur_account.id,+ date: Date.current,+ amount: 100,+ exchange_rate: 0.5,+ idempotency_key: idempotency_key+ }+ }+ end++ assert_response :unprocessable_entity+ end+test "can create transfer with custom exchange rate" dousd_account = accounts(:depository)eur_account = users(:family_admin).family.accounts.create!(diff --git a/test/models/transfer_test.rb b/test/models/transfer_test.rbindex 2368671ab2..0b4354edc5 100644--- a/test/models/transfer_test.rb+++ b/test/models/transfer_test.rb@@ -14,6 +14,38 @@ class TransferTest < ActiveSupport::TestCaseendend+ test "destroy! clears the idempotency key so a retried request can create a new transfer" do+ idempotency_key = SecureRandom.uuid++ transfer = Transfer::Creator.new(+ family: families(:dylan_family),+ source_account_id: accounts(:depository).id,+ destination_account_id: accounts(:credit_card).id,+ date: Date.current,+ amount: 100,+ idempotency_key: idempotency_key+ ).create++ transfer.destroy!++ assert_nil transfer.outflow_transaction.entry.reload.idempotency_key+ assert_nil transfer.inflow_transaction.entry.reload.idempotency_key++ # A retry of the original create request (e.g. the user resubmits after+ # rejecting/undoing the first transfer) must not find a stale entry with+ # this key and raise RecordNotUnique - it should create a fresh transfer.+ assert_difference "Transfer.count", 1 do+ Transfer::Creator.new(+ family: families(:dylan_family),+ source_account_id: accounts(:depository).id,+ destination_account_id: accounts(:credit_card).id,+ date: Date.current,+ amount: 100,+ idempotency_key: idempotency_key+ ).create+ end+ end+test "transfer has different accounts, opposing amounts, and within 4 days of each other" dooutflow_entry = create_transaction(date: 1.day.ago.to_date, account: accounts(:depository), amount: 500)inflow_entry = create_transaction(date: Date.current, account: accounts(:credit_card), amount: -500)