Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Fix Wise incoming transfers by implementing Strong Customer Authentication (#3391)

Igor Oliveira05a787330da3
diff --git a/app/controllers/wise_items_controller.rb b/app/controllers/wise_items_controller.rb
index 3026bb06ee..7963f5eca1 100644
--- a/app/controllers/wise_items_controller.rb
+++ b/app/controllers/wise_items_controller.rb
@@ -1,7 +1,7 @@
# frozen_string_literal: true
class WiseItemsController < ApplicationController
- before_action :set_wise_item, only: [ :show, :edit, :update, :destroy, :sync, :setup_accounts, :complete_account_setup ]
+ before_action :set_wise_item, only: [ :show, :edit, :update, :destroy, :sync, :setup_accounts, :complete_account_setup, :generate_sca_keypair ]
before_action :require_admin!, except: [ :index ]
def index
@@ -136,6 +136,18 @@ class WiseItemsController < ApplicationController
@wise_accounts = @wise_item.wise_accounts.unlinked
end
+ # Generates a fresh SCA keypair for this item. The private key is stored
+ # (encrypted); the public key is derived from it on every render so the user
+ # can register it with Wise. Regenerating invalidates the previous keypair.
+ def generate_sca_keypair
+ @wise_item.generate_sca_keypair!
+ render_provider_panel_success(t(".success"))
+ rescue => e
+ Rails.logger.error "WiseItemsController#generate_sca_keypair - #{e.class}: #{e.message}"
+ @wise_item.errors.add(:base, t(".failed"))
+ render_provider_panel_error
+ end
+
def complete_account_setup
wise_account_id = params[:wise_account_id]
wise_account = @wise_item.wise_accounts.find_by(id: wise_account_id)
diff --git a/app/models/provider/wise.rb b/app/models/provider/wise.rb
index 6b3af322f9..2bfb67ac24 100644
--- a/app/models/provider/wise.rb
+++ b/app/models/provider/wise.rb
@@ -13,11 +13,18 @@ class Provider::Wise
headers "User-Agent" => "Sure Finance Wise Client"
default_options.merge!({ timeout: 120 }.merge(httparty_ssl_options))
- attr_reader :token, :base_url
+ # Wise header carrying the one-time-token challenge on a 403 that requires
+ # Strong Customer Authentication (SCA), and the header used to submit the
+ # signed response.
+ SCA_CHALLENGE_HEADER = "x-2fa-approval"
+ SCA_SIGNATURE_HEADER = "X-Signature"
- def initialize(token, base_url: LIVE_BASE_URL)
+ attr_reader :token, :base_url, :sca_private_key
+
+ def initialize(token, base_url: LIVE_BASE_URL, sca_private_key: nil)
@token = token
@base_url = base_url
+ @sca_private_key = sca_private_key
end
def get_me
@@ -93,12 +100,17 @@ class Provider::Wise
private
- def get(path, query: {})
+ def get(path, query: {}, sca_headers: {})
response = self.class.get(
"#{base_url}#{path}",
- headers: auth_headers,
+ headers: auth_headers.merge(sca_headers),
query: query.presence
)
+
+ if sca_retry?(response, already_retried: sca_headers.present?)
+ return get(path, query: query, sca_headers: sca_approval_headers(response))
+ end
+
handle_response(response)
rescue WiseError
raise
@@ -108,6 +120,33 @@ class Provider::Wise
raise WiseError.new("Unexpected error: #{e.message}", :request_failed)
end
+ # Wise's balance-statement endpoint (and other sensitive endpoints) require
+ # Strong Customer Authentication: a 403 carrying a one-time-token challenge
+ # in SCA_CHALLENGE_HEADER, which must be signed with an RSA private key the
+ # user has registered with Wise and echoed back on a retry. Retries at most
+ # once per request to avoid looping if the key is missing or rejected.
+ def sca_retry?(response, already_retried:)
+ return false if already_retried
+ return false unless response.code == 403
+ sca_private_key.present? && sca_challenge_token(response).present?
+ end
+
+ def sca_challenge_token(response)
+ response.headers[SCA_CHALLENGE_HEADER]
+ end
+
+ def sca_approval_headers(response)
+ challenge = sca_challenge_token(response)
+ { SCA_CHALLENGE_HEADER => challenge, SCA_SIGNATURE_HEADER => sign_sca_challenge(challenge) }
+ end
+
+ def sign_sca_challenge(challenge)
+ key = OpenSSL::PKey::RSA.new(sca_private_key)
+ Base64.strict_encode64(key.sign(OpenSSL::Digest::SHA256.new, challenge))
+ rescue OpenSSL::PKey::RSAError => e
+ raise WiseError.new("Invalid SCA private key: #{e.message}", :sca_key_invalid)
+ end
+
def auth_headers
{
"Authorization" => "Bearer #{token}",
diff --git a/app/models/provider/wise_adapter.rb b/app/models/provider/wise_adapter.rb
index 05c28bc23e..e920141e30 100644
--- a/app/models/provider/wise_adapter.rb
+++ b/app/models/provider/wise_adapter.rb
@@ -30,7 +30,7 @@ class Provider::WiseAdapter < Provider::Base
item = resolve_wise_item(family, wise_item_id)
return nil unless item&.credentials_configured?
- Provider::Wise.new(item.token.to_s.strip, base_url: Rails.configuration.x.wise.base_url)
+ Provider::Wise.new(item.token.to_s.strip, base_url: Rails.configuration.x.wise.base_url, sca_private_key: item.sca_private_key)
end
def sync_path
diff --git a/app/models/wise_item.rb b/app/models/wise_item.rb
index 7684f1e6c6..f6d4bed51d 100644
--- a/app/models/wise_item.rb
+++ b/app/models/wise_item.rb
@@ -9,6 +9,7 @@ class WiseItem < ApplicationRecord
if encryption_ready?
encrypts :token, deterministic: true
encrypts :raw_payload
+ encrypts :sca_private_key
end
validates :name, :profile_id, :profile_type, presence: true
@@ -122,6 +123,32 @@ class WiseItem < ApplicationRecord
token.to_s.strip.present?
end
+ # True only when there's a private key AND it actually parses -- a stored
+ # key that's corrupted or unparsable (e.g. an encryption misconfig or a
+ # manual DB edit) should fall back to the "not configured" UI state rather
+ # than rendering a blank public key box.
+ def sca_configured?
+ sca_public_key.present?
+ end
+
+ # Generates a new RSA keypair for Wise's Strong Customer Authentication (SCA)
+ # flow, used to sign the one-time-token challenge on the balance-statement
+ # endpoint. The private key stays here (encrypted at rest); the public key
+ # must be registered with Wise by the user (Settings > API tokens > Public keys).
+ def generate_sca_keypair!
+ key = OpenSSL::PKey::RSA.generate(2048)
+ update!(sca_private_key: key.to_pem)
+ sca_public_key
+ end
+
+ def sca_public_key
+ return nil unless sca_private_key.present?
+
+ OpenSSL::PKey::RSA.new(sca_private_key).public_key.to_pem
+ rescue OpenSSL::PKey::RSAError
+ nil
+ end
+
def sync_status_summary
total = total_accounts_count
linked = linked_accounts_count
@@ -155,7 +182,7 @@ class WiseItem < ApplicationRecord
def wise_provider
return nil unless credentials_configured?
- Provider::Wise.new(token.to_s.strip, base_url: Rails.configuration.x.wise.base_url)
+ Provider::Wise.new(token.to_s.strip, base_url: Rails.configuration.x.wise.base_url, sca_private_key: sca_private_key)
end
private
diff --git a/app/models/wise_item/importer.rb b/app/models/wise_item/importer.rb
index 221dbadbde..8c5fc9e372 100644
--- a/app/models/wise_item/importer.rb
+++ b/app/models/wise_item/importer.rb
@@ -79,7 +79,14 @@ class WiseItem::Importer
# Used in WiseEntry::Processor to distinguish expenses (targetAccount != recipientId)
# from incomes (targetAccount == recipientId).
def fetch_borderless_accounts
+ trace_wise_fetch(operation: "borderless_accounts", status: "started", level: "info")
result = wise_provider.get_borderless_accounts(wise_item.profile_id)
+ trace_wise_fetch(
+ operation: "borderless_accounts",
+ status: "completed",
+ level: "info",
+ received_record_count: Array(result).size
+ )
Array(result).each_with_object({}) do |ba, map|
borderless_id = ba["id"]
recipient_id = ba["recipientId"]
@@ -88,7 +95,7 @@ class WiseItem::Importer
end
end
rescue => e
- Rails.logger.warn "WiseItem::Importer - Could not fetch borderless accounts (#{e.message})"
+ trace_wise_fetch(operation: "borderless_accounts", status: "failed", level: "warn", error: e)
{}
end
@@ -141,8 +148,17 @@ class WiseItem::Importer
cursor = nil
loop do
+ trace_wise_fetch(operation: "activities", status: "started", level: "info", cursor: cursor, page_size: 100)
result = with_rate_limit_retry { wise_provider.get_activities(wise_item.profile_id, cursor: cursor, size: 100) }
batch = Array(result["activities"])
+ trace_wise_fetch(
+ operation: "activities",
+ status: "completed",
+ level: "info",
+ cursor: cursor,
+ received_record_count: batch.size,
+ next_cursor_present: result["cursor"].present?
+ )
break if batch.empty?
old_ones = batch.select { |a| parse_transfer_date(a["createdOn"]) < cutoff }
@@ -157,10 +173,10 @@ class WiseItem::Importer
activities.uniq { |a| a["id"] }
rescue Provider::Wise::WiseError => e
- Rails.logger.warn "WiseItem::Importer - Could not fetch activities (#{e.message})"
+ trace_wise_fetch(operation: "activities", status: "failed", level: "warn", error: e, cursor: cursor)
[]
rescue => e
- Rails.logger.warn "WiseItem::Importer - Unexpected error fetching activities: #{e.message}"
+ trace_wise_fetch(operation: "activities", status: "failed", level: "warn", error: e, cursor: cursor)
[]
end
@@ -172,8 +188,16 @@ class WiseItem::Importer
limit = 100
loop do
+ trace_wise_fetch(operation: "transfers", status: "started", level: "info", offset: offset, page_size: limit)
page = with_rate_limit_retry { wise_provider.get_transfers(wise_item.profile_id, limit: limit, offset: offset) }
batch = Array(page.is_a?(Hash) ? page["content"] : page)
+ trace_wise_fetch(
+ operation: "transfers",
+ status: "completed",
+ level: "info",
+ offset: offset,
+ received_record_count: batch.size
+ )
break if batch.empty?
# Wise returns transfers newest-first; stop once we're past the cutoff.
@@ -188,16 +212,21 @@ class WiseItem::Importer
Rails.logger.info "WiseItem::Importer - Fetched #{transfers.size} transfers for profile #{wise_item.profile_id}"
transfers
rescue Provider::Wise::WiseError => e
- Rails.logger.warn "WiseItem::Importer - Could not fetch transfers (#{e.message})"
+ trace_wise_fetch(operation: "transfers", status: "failed", level: "warn", error: e, offset: offset)
[]
rescue => e
- Rails.logger.warn "WiseItem::Importer - Unexpected error fetching transfers: #{e.message}"
+ trace_wise_fetch(operation: "transfers", status: "failed", level: "warn", error: e, offset: offset)
[]
end
# Fetches statement rows for STANDARD balances. Legacy transfer snapshots
- # are retained and only backfilled with statements older than their oldest
- # transfer, avoiding duplicate imports during the migration.
+ # are retained; outgoing statement rows dated on/after the oldest legacy
+ # transfer are dropped since transfers already captured that side (see
+ # #legacy_overlap_outgoing_row?), while incoming rows there are kept so
+ # money the legacy fallback could never capture (external payments) gets
+ # backfilled -- at the cost of occasionally re-importing the credit leg of
+ # a historical internal conversion transfers also already captured (see
+ # #legacy_overlap_outgoing_row? for why that trade-off is intentional).
def fetch_statements
@statement_fetch_attempted_accounts = []
@statement_fetch_failed_accounts = []
@@ -209,6 +238,8 @@ class WiseItem::Importer
legacy = existing.select do |transaction|
transaction["wise_statement"].blank? && !jar_activity?(transaction)
end
+ legacy_cutoff = legacy.filter_map { |transaction| parse_transaction_date(transaction) }.min
+
start_date =
if existing.any? { |transaction| transaction["wise_statement"].present? } &&
sync_start_date.blank? && wise_item.sync_start_date.blank? && wise_item.last_synced_at.present?
@@ -221,14 +252,17 @@ class WiseItem::Importer
end
end_date = Date.current
- if legacy.any?
- oldest = legacy.filter_map { |transaction| parse_transaction_date(transaction) }.min
- end_date = oldest - 1.day if oldest
- end
-
next if start_date > end_date
@statement_fetch_attempted_accounts << wise_account.id
+ trace_wise_fetch(
+ operation: "balance_statement",
+ status: "started",
+ level: "info",
+ wise_account: wise_account,
+ start_date: start_date,
+ end_date: end_date
+ )
rows = wise_provider.get_balance_statements(
wise_item.profile_id,
wise_account.balance_id,
@@ -236,20 +270,54 @@ class WiseItem::Importer
start_date: start_date,
end_date: end_date
)
- result[wise_account.id] = Array(rows).map { |row| row.merge("wise_statement" => true) }
+ received_row_count = Array(rows).size
+ rows = Array(rows).reject { |row| legacy_overlap_outgoing_row?(row, legacy_cutoff) }
+ trace_wise_fetch(
+ operation: "balance_statement",
+ status: "completed",
+ level: "info",
+ wise_account: wise_account,
+ received_row_count: received_row_count,
+ stored_row_count: rows.size
+ )
+ result[wise_account.id] = rows.map { |row| row.merge("wise_statement" => true) }
rescue Provider::Wise::WiseError => e
@statement_fetch_failed_accounts << wise_account.id
- capture_statement_error(wise_account, e, level: "warn")
- Rails.logger.warn "WiseItem::Importer - Could not fetch statements for wise_account #{wise_account.id} (#{e.message})"
+ trace_wise_fetch(operation: "balance_statement", status: "failed", level: "warn", wise_account: wise_account, error: e)
result[wise_account.id] = []
rescue => e
@statement_fetch_failed_accounts << wise_account.id
- capture_statement_error(wise_account, e, level: "warn")
- Rails.logger.warn "WiseItem::Importer - Unexpected error fetching statements for wise_account #{wise_account.id}: #{e.message}"
+ trace_wise_fetch(operation: "balance_statement", status: "failed", level: "warn", wise_account: wise_account, error: e)
result[wise_account.id] = []
end
end
+ # The legacy /v1/transfers fallback captured outgoing money unconditionally,
+ # plus the incoming leg of any internal cross-currency conversion between
+ # the profile's own balances (transfers where this balance is the target).
+ # So an outgoing statement row (Wise reports debits as non-positive) dated
+ # on/after the oldest legacy transfer already has a legacy counterpart and
+ # would double-book it.
+ #
+ # An incoming row in that same window *could* be the credit leg of one of
+ # those internal conversions (also already covered) rather than a genuine
+ # external payment -- but nothing short of an endpoint-proven correlation
+ # id can tell the two apart without risk of a false match, and silently
+ # dropping a real external payment is a worse failure than an occasional
+ # visible, user-correctable duplicate for a historical conversion. So
+ # incoming rows are always kept here; #legacy_transfer_import_needed?
+ # instead bounds the exposure by stopping the transfer fallback (and with
+ # it, any *new* double-booking) as soon as an account's statements prove
+ # to work.
+ def legacy_overlap_outgoing_row?(row, legacy_cutoff)
+ return false unless legacy_cutoff
+
+ date = parse_transaction_date(row)
+ return false unless date && date >= legacy_cutoff
+
+ row.dig("amount", "value").to_d <= 0
+ end
+
# Statements are only "unavailable" when every attempted standard balance
# request failed (e.g. the token lacks statement access). Successful
# requests that return zero rows are normal — quiet incremental syncs must
@@ -261,14 +329,21 @@ class WiseItem::Importer
attempted.any? && (attempted - failed).empty?
end
- # The transfer endpoint remains a compatibility fallback for tokens that
- # cannot access statements and for accounts imported before statement rows
- # were supported.
+ # The transfer endpoint remains a compatibility fallback only until an
+ # account's statements are proven to work: once a statement row has
+ # landed for an account, statements alone cover both directions of money
+ # movement going forward, so re-fetching transfers would only re-invite
+ # double-booking new internal conversions (see #legacy_overlap_outgoing_row?)
+ # for no benefit.
def legacy_transfer_import_needed?
wise_item.wise_accounts.any? do |wise_account|
- !wise_account.jar? && Array(wise_account.raw_transactions_payload).any? do |transaction|
- transaction["wise_statement"].blank? && !jar_activity?(transaction)
- end
+ next false if wise_account.jar?
+
+ payload = Array(wise_account.raw_transactions_payload)
+ has_legacy = payload.any? { |transaction| transaction["wise_statement"].blank? && !jar_activity?(transaction) }
+ has_statement = payload.any? { |transaction| transaction["wise_statement"].present? }
+
+ has_legacy && !has_statement
end
end
@@ -294,13 +369,24 @@ class WiseItem::Importer
wise_account.upsert_wise_transactions_snapshot!(jar_activities)
transactions_imported += jar_activities.size
else
- account_transfers = transfers.select do |t|
- t["sourceCurrency"] == wise_account.currency ||
- t["targetCurrency"] == wise_account.currency
- end
account_statements = statements[wise_account.id] || []
existing_legacy = Array(wise_account.raw_transactions_payload).reject { |transaction| transaction["wise_statement"].present? }
existing_statements = Array(wise_account.raw_transactions_payload).select { |transaction| transaction["wise_statement"].present? }
+ # `transfers` is fetched profile-wide as soon as ANY account still
+ # needs the legacy fallback (see #legacy_transfer_import_needed?),
+ # so it can contain movements for a currency this specific account
+ # already covers via its own statements. Only apply it here if this
+ # account hasn't migrated yet -- otherwise the same movement would
+ # be merged twice under different keys (see #merge_transaction_payloads).
+ account_transfers =
+ if existing_statements.any?
+ []
+ else
+ transfers.select do |t|
+ t["sourceCurrency"] == wise_account.currency ||
+ t["targetCurrency"] == wise_account.currency
+ end
+ end
# Also include INTERBALANCE activities so the standard account shows outflows to the JAR.
interbalance = activities.select { |a| activity_for_account?(a, wise_account) }
payload = merge_transaction_payloads(
@@ -337,19 +423,33 @@ class WiseItem::Importer
WiseActivity::Processor::JAR_ACTIVITY_TYPES.include?(transaction["type"])
end
- def capture_statement_error(wise_account, error, level:)
+ def trace_wise_fetch(operation:, status:, level:, wise_account: nil, error: nil, **metadata)
+ message = "WiseItem::Importer - Wise #{operation} fetch #{status}"
+ message = "#{message} for wise_account #{wise_account.id}" if wise_account
+ message = "#{message}: #{error.message}" if error
+
+ Rails.logger.public_send(level, message)
DebugLogEntry.capture(
- category: "provider_sync_error",
+ category: error ? "provider_sync_error" : "provider_sync",
level: level,
- message: "WiseItem::Importer - Failed to fetch statement for wise_account #{wise_account.id}: #{error.message}",
+ message: message,
source: self.class.name,
provider_key: "wise",
family: wise_item.family,
- account_provider: wise_account.account_provider,
- metadata: { wise_account_id: wise_account.id, error_class: error.class.name }
+ account_provider: wise_account&.account_provider,
+ metadata: {
+ wise_item_id: wise_item.id,
+ operation: operation,
+ wise_account_id: wise_account&.id,
+ balance_id: wise_account&.balance_id,
+ currency: wise_account&.currency,
+ sca_private_key_configured: wise_item.sca_private_key.present?,
+ error_class: error&.class&.name,
+ error_type: error&.respond_to?(:error_type) ? error.error_type : nil
+ }.compact.merge(metadata)
)
- rescue => capture_error
- Rails.logger.warn "WiseItem::Importer - Failed to capture statement error: #{capture_error.message}"
+ rescue => trace_error
+ Rails.logger.warn "WiseItem::Importer - Failed to capture statement trace: #{trace_error.message}"
end
# Routes an activity to the given WiseAccount.
diff --git a/app/models/wise_item/syncer.rb b/app/models/wise_item/syncer.rb
index d72f6a27c6..a77f31c4da 100644
--- a/app/models/wise_item/syncer.rb
+++ b/app/models/wise_item/syncer.rb
@@ -41,6 +41,7 @@ class WiseItem::Syncer
mark_import_started(sync)
process_results = wise_item.process_accounts
sync_errors.concat(result_failure_errors(process_results, category: :account_processing_error, message_key: :account_processing_failed))
+ capture_transaction_processing_summary(process_results)
wise_item.link_jar_transfers!
@@ -112,6 +113,36 @@ class WiseItem::Syncer
[ sync_error(category, message_key, count: failed) ]
end
+ def capture_transaction_processing_summary(results)
+ account_results = Array(results)
+ transaction_results = account_results.filter_map { |result| result[:result] if result.is_a?(Hash) }
+ failed_accounts = account_results.count { |result| result.is_a?(Hash) && result[:success] == false }
+ imported = transaction_results.sum { |result| result[:imported].to_i }
+ skipped = transaction_results.sum { |result| result[:skipped].to_i }
+ failed = transaction_results.sum { |result| result[:failed].to_i } + failed_accounts
+ level = failed.positive? ? "warn" : "info"
+ message = "WiseItem::Syncer - Transaction processing completed: #{imported} imported, #{skipped} skipped, #{failed} failed"
+
+ Rails.logger.public_send(level, message)
+ DebugLogEntry.capture(
+ category: failed.positive? ? "provider_sync_error" : "provider_sync",
+ level: level,
+ message: message,
+ source: self.class.name,
+ provider_key: "wise",
+ family: wise_item.family,
+ metadata: {
+ wise_item_id: wise_item.id,
+ processed_account_count: account_results.size,
+ imported_transaction_count: imported,
+ skipped_transaction_count: skipped,
+ failed_transaction_count: failed
+ }
+ )
+ rescue => e
+ Rails.logger.warn "WiseItem::Syncer - Failed to capture transaction processing summary: #{e.message}"
+ end
+
def sync_error(category, message_key, **options)
{
message: I18n.t("wise_items.syncer.#{message_key}", **options),
diff --git a/app/views/settings/providers/_wise_panel.html.erb b/app/views/settings/providers/_wise_panel.html.erb
index a6730963f3..c76f1ab47e 100644
--- a/app/views/settings/providers/_wise_panel.html.erb
+++ b/app/views/settings/providers/_wise_panel.html.erb
@@ -59,6 +59,38 @@
) %>
</div>
+ <div class="p-3 rounded-md bg-container-inset space-y-2">
+ <p class="text-sm font-medium text-primary"><%= t("wise_items.provider_panel.sca.title") %></p>
+ <p class="text-xs text-secondary"><%= t("wise_items.provider_panel.sca.description") %></p>
+
+ <% if item.sca_configured? %>
+ <p class="text-xs text-secondary"><%= t("wise_items.provider_panel.sca.public_key_label") %></p>
+ <div class="bg-container rounded-lg p-3 border border-primary" data-controller="clipboard" data-clipboard-copied-text-value="<%= t("wise_items.provider_panel.sca.copied") %>">
+ <div class="flex flex-col items-start gap-2">
+ <code class="font-mono text-xs text-primary break-all whitespace-pre-wrap" data-clipboard-target="source"><%= item.sca_public_key %></code>
+ <%= render DS::Button.new(
+ text: t("wise_items.provider_panel.sca.copy"),
+ variant: "ghost",
+ size: :sm,
+ icon: "copy",
+ data: { action: "clipboard#copy" }
+ ) %>
+ </div>
+ </div>
+ <p class="text-xs text-secondary"><%= t("wise_items.provider_panel.sca.registered_help_html").html_safe %></p>
+ <% end %>
+
+ <%= render DS::Button.new(
+ text: item.sca_configured? ? t("wise_items.provider_panel.sca.regenerate") : t("wise_items.provider_panel.sca.generate"),
+ icon: "key-round",
+ variant: :outline,
+ size: :sm,
+ href: generate_sca_keypair_wise_item_path(item),
+ method: :post,
+ confirm: item.sca_configured? ? t("wise_items.provider_panel.sca.regenerate_confirm") : nil
+ ) %>
+ </div>
+
<%= styled_form_with model: item,
url: wise_item_path(item),
scope: :wise_item,
diff --git a/config/locales/views/wise_items/en.yml b/config/locales/views/wise_items/en.yml
index 15acafb657..f989acaa40 100644
--- a/config/locales/views/wise_items/en.yml
+++ b/config/locales/views/wise_items/en.yml
@@ -85,6 +85,16 @@ en:
open_tokens: "Go to Settings → Connect and manage apps → Developer tools → API tokens"
create_token: "Create a new personal API token with read-only access"
copy_token_html: "Copy the token and paste it below. Sure uses it only to sync your balances and transactions."
+ sca:
+ title: Strong Customer Authentication (SCA)
+ description: Wise requires a signed one-time-token challenge to read full transaction statements, including incoming payments. Generate a keypair here and register the public key with Wise to enable this.
+ public_key_label: Public key (PEM)
+ registered_help_html: "Register this key with Wise: Settings → Connect and manage apps → Developer tools → Public keys → Add public key."
+ copy: Copy
+ copied: Copied!
+ generate: Generate keypair
+ regenerate: Regenerate keypair
+ regenerate_confirm: "This generates a new keypair. Wise will keep accepting the previous public key until you remove it yourself in your Wise account — Sure has no way to revoke it remotely. You'll need to register the new public key with Wise before statements can sync again. Continue?"
provider_connection:
default_name: Wise
default_description: Connect your Wise multi-currency account
@@ -152,3 +162,6 @@ en:
not_found: Wise balance not found.
success: Account created and linked successfully.
failed: Failed to create account. Please try again.
+ generate_sca_keypair:
+ success: New SCA keypair generated. Register the public key with Wise to finish enabling it.
+ failed: Failed to generate a new SCA keypair. Please try again.
diff --git a/config/routes.rb b/config/routes.rb
index 65dd81d6dd..5c312077d6 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -62,6 +62,7 @@ Rails.application.routes.draw do
post :sync
get :setup_accounts
post :complete_account_setup
+ post :generate_sca_keypair
end
end
diff --git a/db/migrate/20260904201444_add_sca_private_key_to_wise_items.rb b/db/migrate/20260904201444_add_sca_private_key_to_wise_items.rb
new file mode 100644
index 0000000000..d15027e4f6
--- /dev/null
+++ b/db/migrate/20260904201444_add_sca_private_key_to_wise_items.rb
@@ -0,0 +1,5 @@
+class AddScaPrivateKeyToWiseItems < ActiveRecord::Migration[7.2]
+ def change
+ add_column :wise_items, :sca_private_key, :text
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index a7283fa73e..241769b765 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -10,7 +10,7 @@
#
# It's strongly recommended that you check this file into your version control system.
-ActiveRecord::Schema[8.1].define(version: 2026_09_02_180400) do
+ActiveRecord::Schema[8.1].define(version: 2026_09_04_201444) do
# These are extensions that must be enabled in order to support this database
enable_extension "pg_catalog.plpgsql"
enable_extension "pgcrypto"
@@ -2570,6 +2570,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_09_02_180400) do
t.string "profile_id", null: false
t.string "profile_type", null: false
t.jsonb "raw_payload"
+ t.text "sca_private_key"
t.boolean "scheduled_for_deletion", default: false, null: false
t.string "status", default: "good", null: false
t.datetime "sync_start_date"
diff --git a/test/controllers/wise_items_controller_test.rb b/test/controllers/wise_items_controller_test.rb
index eef886bce0..0698f95227 100644
--- a/test/controllers/wise_items_controller_test.rb
+++ b/test/controllers/wise_items_controller_test.rb
@@ -121,6 +121,24 @@ class WiseItemsControllerTest < ActionDispatch::IntegrationTest
assert_redirected_to settings_providers_path
end
+ test "generate_sca_keypair stores a keypair on the item" do
+ assert_nil @wise_item.sca_private_key
+
+ post generate_sca_keypair_wise_item_url(@wise_item)
+
+ assert_redirected_to accounts_path
+ assert @wise_item.reload.sca_configured?
+ end
+
+ test "generate_sca_keypair replaces a previously generated keypair" do
+ @wise_item.generate_sca_keypair!
+ previous_key = @wise_item.sca_private_key
+
+ post generate_sca_keypair_wise_item_url(@wise_item)
+
+ assert_not_equal previous_key, @wise_item.reload.sca_private_key
+ end
+
test "link_profiles redirects to providers when the session token cannot be decrypted" do
Provider::Wise.any_instance.stubs(:get_profiles).returns(@valid_profiles)
post wise_items_url, params: { wise_item: { token: "live_token_abc" } }
diff --git a/test/models/provider/wise_adapter_test.rb b/test/models/provider/wise_adapter_test.rb
new file mode 100644
index 0000000000..b4b217d84a
--- /dev/null
+++ b/test/models/provider/wise_adapter_test.rb
@@ -0,0 +1,43 @@
+require "test_helper"
+
+class Provider::WiseAdapterTest < ActiveSupport::TestCase
+ setup do
+ @family = families(:dylan_family)
+ @wise_item = wise_items(:one)
+ end
+
+ test "build_provider threads sca_private_key through to Provider::Wise" do
+ key = OpenSSL::PKey::RSA.new(2048).to_pem
+ @wise_item.update!(sca_private_key: key)
+
+ provider = Provider::WiseAdapter.build_provider(family: @family, wise_item_id: @wise_item.id)
+
+ assert_instance_of Provider::Wise, provider
+ assert_equal @wise_item.token, provider.token
+ assert_equal key, provider.sca_private_key
+ end
+
+ test "build_provider passes a nil sca_private_key when no keypair is configured" do
+ provider = Provider::WiseAdapter.build_provider(family: @family, wise_item_id: @wise_item.id)
+
+ assert_instance_of Provider::Wise, provider
+ assert_nil provider.sca_private_key
+ end
+
+ test "build_provider resolves the family's most recent active item when wise_item_id is omitted" do
+ provider = Provider::WiseAdapter.build_provider(family: @family)
+
+ assert_instance_of Provider::Wise, provider
+ assert_equal @wise_item.token, provider.token
+ end
+
+ test "build_provider returns nil without a family" do
+ assert_nil Provider::WiseAdapter.build_provider(family: nil)
+ end
+
+ test "build_provider returns nil when credentials are not configured" do
+ @wise_item.update_column(:token, "")
+
+ assert_nil Provider::WiseAdapter.build_provider(family: @family, wise_item_id: @wise_item.id)
+ end
+end
diff --git a/test/models/provider/wise_test.rb b/test/models/provider/wise_test.rb
index 53ad8e2695..f9d8174608 100644
--- a/test/models/provider/wise_test.rb
+++ b/test/models/provider/wise_test.rb
@@ -53,6 +53,45 @@ class Provider::WiseTest < ActiveSupport::TestCase
assert_equal [], result
end
+ test "signs the SCA challenge and retries once when a private key is configured" do
+ key = OpenSSL::PKey::RSA.new(2048)
+ provider = Provider::Wise.new("test_token", base_url: "https://api.wise.com", sca_private_key: key.to_pem)
+
+ challenge = "one-time-token-abc"
+ expected_signature = Base64.strict_encode64(key.sign(OpenSSL::Digest::SHA256.new, challenge))
+
+ Provider::Wise.expects(:get)
+ .with { |_url, options| options[:headers]["x-2fa-approval"].nil? }
+ .returns(fake_response(code: 403, headers: { "x-2fa-approval" => challenge }))
+ Provider::Wise.expects(:get)
+ .with { |_url, options|
+ options[:headers]["x-2fa-approval"] == challenge &&
+ options[:headers]["X-Signature"] == expected_signature
+ }
+ .returns(fake_response(code: 200, body: '{"ok":true}'))
+
+ result = provider.send(:get, "/v1/profiles/1/balance-statements/2/statement.json")
+
+ assert_equal({ "ok" => true }, result)
+ end
+
+ test "does not retry a 403 when no SCA private key is configured" do
+ Provider::Wise.expects(:get).once.returns(fake_response(code: 403, headers: { "x-2fa-approval" => "abc" }))
+
+ error = assert_raises(Provider::Wise::WiseError) { @provider.send(:get, "/v1/me") }
+ assert_equal :access_forbidden, error.error_type
+ end
+
+ test "does not loop forever if the signed retry still fails" do
+ key = OpenSSL::PKey::RSA.new(2048)
+ provider = Provider::Wise.new("test_token", base_url: "https://api.wise.com", sca_private_key: key.to_pem)
+
+ Provider::Wise.expects(:get).twice.returns(fake_response(code: 403, headers: { "x-2fa-approval" => "abc" }))
+
+ error = assert_raises(Provider::Wise::WiseError) { provider.send(:get, "/v1/me") }
+ assert_equal :access_forbidden, error.error_type
+ end
+
test "retries a rate-limited window without restarting earlier windows" do
error = Provider::Wise::WiseError.new("rate limited", :rate_limited)
@provider.stubs(:sleep)
@@ -71,4 +110,12 @@ class Provider::WiseTest < ActiveSupport::TestCase
assert_equal [], result
end
+
+ private
+
+ FakeResponse = Struct.new(:code, :body, :headers)
+
+ def fake_response(code:, body: "{}", headers: {})
+ FakeResponse.new(code, body, headers)
+ end
end
diff --git a/test/models/wise_item/importer_test.rb b/test/models/wise_item/importer_test.rb
index ee15acac69..50249d4648 100644
--- a/test/models/wise_item/importer_test.rb
+++ b/test/models/wise_item/importer_test.rb
@@ -254,12 +254,22 @@ class WiseItem::ImporterTest < ActiveSupport::TestCase
]
provider = FakeWiseProvider.new(transfers: transfers, raise_on: { get_balance_statements: "forbidden" })
- result = WiseItem::Importer.new(@wise_item, wise_provider: provider).import
+ result = nil
+ assert_difference -> { DebugLogEntry.where(provider_key: "wise", category: "provider_sync_error").count }, 1 do
+ result = WiseItem::Importer.new(@wise_item, wise_provider: provider).import
+ end
assert result[:success]
assert_includes provider.calls, :get_transfers
account = @wise_item.wise_accounts.find_by(currency: "EUR")
assert_equal 1, account.raw_transactions_payload.size
+
+ entry = DebugLogEntry.where(provider_key: "wise", category: "provider_sync_error").recent.first
+ assert_equal "WiseItem::Importer", entry.source
+ assert_equal @wise_item.id, entry.metadata["wise_item_id"]
+ assert_equal false, entry.metadata["sca_private_key_configured"]
+ assert_equal "Provider::Wise::WiseError", entry.metadata["error_class"]
+ assert_equal "fetch_failed", entry.metadata["error_type"]
end
test "surfaces partial statement fetch failures without the transfer fallback" do
@@ -284,6 +294,158 @@ class WiseItem::ImporterTest < ActiveSupport::TestCase
refute_includes provider.calls, :get_transfers
end
+ test "backfills incoming statement rows into the window already covered by legacy transfers" do
+ @wise_item.wise_accounts.create!(
+ balance_id: "10000001",
+ name: "Wise EUR",
+ currency: "EUR",
+ raw_payload: { "type" => "STANDARD" },
+ raw_transactions_payload: [
+ {
+ "id" => 1,
+ "sourceCurrency" => "EUR",
+ "targetCurrency" => "EUR",
+ "sourceValue" => 100.0,
+ "targetValue" => 100.0,
+ "status" => "outgoing_payment_sent",
+ "created" => "2024-01-10"
+ }
+ ]
+ )
+ statements = [
+ { "date" => "2024-01-15T10:00:00Z", "amount" => { "value" => "-50.00", "currency" => "EUR" }, "referenceNumber" => "st-outgoing-in-window" },
+ { "date" => "2024-01-20T10:00:00Z", "amount" => { "value" => "6780.00", "currency" => "EUR" }, "referenceNumber" => "st-incoming-in-window" },
+ { "date" => "2024-01-05T10:00:00Z", "amount" => { "value" => "20.00", "currency" => "EUR" }, "referenceNumber" => "st-before-window" }
+ ]
+ provider = FakeWiseProvider.new(statements: statements)
+
+ WiseItem::Importer.new(@wise_item, wise_provider: provider).import
+
+ account = @wise_item.wise_accounts.find_by(currency: "EUR")
+ refs = account.raw_transactions_payload.filter_map { |t| t["referenceNumber"] }
+
+ assert_includes refs, "st-incoming-in-window"
+ assert_includes refs, "st-before-window"
+ refute_includes refs, "st-outgoing-in-window"
+ end
+
+ test "keeps an incoming statement row that coincidentally shares its date and amount with a legacy transfer" do
+ # A same-day, same-amount external payment must never be dropped just
+ # because it looks like it could be the credit leg of a prior internal
+ # conversion -- silently losing a real transaction is worse than an
+ # occasional visible duplicate (see legacy_overlap_outgoing_row?).
+ @wise_item.wise_accounts.create!(
+ balance_id: "10000001",
+ name: "Wise EUR",
+ currency: "EUR",
+ raw_payload: { "type" => "STANDARD", "recipient_id" => 99999001 },
+ raw_transactions_payload: [
+ {
+ "id" => 10,
+ "targetAccount" => 99999001,
+ "sourceCurrency" => "USD",
+ "targetCurrency" => "EUR",
+ "sourceValue" => 500.0,
+ "targetValue" => 450.0,
+ "status" => "incoming_payment_received",
+ "created" => "2024-02-01"
+ }
+ ]
+ )
+ statements = [
+ { "date" => "2024-02-01T09:00:00Z", "amount" => { "value" => "450.00", "currency" => "EUR" }, "referenceNumber" => "st-same-date-and-amount" }
+ ]
+ provider = FakeWiseProvider.new(statements: statements)
+
+ WiseItem::Importer.new(@wise_item, wise_provider: provider).import
+
+ account = @wise_item.wise_accounts.find_by(currency: "EUR")
+ refs = account.raw_transactions_payload.filter_map { |t| t["referenceNumber"] }
+
+ assert_includes refs, "st-same-date-and-amount"
+ end
+
+ test "stops fetching legacy transfers once an account has a successful statement row" do
+ @wise_item.wise_accounts.create!(
+ balance_id: "10000001",
+ name: "Wise EUR",
+ currency: "EUR",
+ raw_payload: { "type" => "STANDARD" },
+ raw_transactions_payload: [
+ {
+ "id" => 1,
+ "sourceCurrency" => "EUR",
+ "targetCurrency" => "EUR",
+ "sourceValue" => 100.0,
+ "targetValue" => 100.0,
+ "status" => "outgoing_payment_sent",
+ "created" => "2024-01-10"
+ },
+ {
+ "wise_statement" => true,
+ "date" => "2024-01-20",
+ "amount" => { "value" => "10.0", "currency" => "EUR" },
+ "referenceNumber" => "already-migrated"
+ }
+ ]
+ )
+ provider = FakeWiseProvider.new(statements: [])
+
+ WiseItem::Importer.new(@wise_item, wise_provider: provider).import
+
+ refute_includes provider.calls, :get_transfers
+ end
+
+ test "does not merge the profile-wide transfer fallback into an account that already migrated to statements" do
+ balances = [
+ { "id" => "10000001", "amount" => { "value" => 1000.0, "currency" => "EUR" }, "type" => "STANDARD" },
+ { "id" => "10000002", "amount" => { "value" => 500.0, "currency" => "USD" }, "type" => "STANDARD" }
+ ]
+ eur_account = @wise_item.wise_accounts.create!(
+ balance_id: "10000001",
+ name: "Wise EUR",
+ currency: "EUR",
+ raw_payload: { "type" => "STANDARD" },
+ raw_transactions_payload: [
+ {
+ "wise_statement" => true,
+ "date" => "2024-01-20",
+ "amount" => { "value" => "10.0", "currency" => "EUR" },
+ "referenceNumber" => "already-migrated-eur"
+ }
+ ]
+ )
+ @wise_item.wise_accounts.create!(
+ balance_id: "10000002",
+ name: "Wise USD",
+ currency: "USD",
+ raw_payload: { "type" => "STANDARD" },
+ raw_transactions_payload: [
+ {
+ "id" => 5,
+ "sourceCurrency" => "USD",
+ "targetCurrency" => "USD",
+ "sourceValue" => 20.0,
+ "targetValue" => 20.0,
+ "status" => "outgoing_payment_sent",
+ "created" => "2024-01-05"
+ }
+ ]
+ )
+ # USD still needs the legacy fallback, so transfers get fetched profile-wide --
+ # including this EUR-currency row, which must not land on the already-migrated
+ # EUR account.
+ transfers = [ build_transfer(id: 99, source_currency: "EUR", target_currency: "EUR", target_account: 9999) ]
+ provider = FakeWiseProvider.new(balances: balances, transfers: transfers, statement_fail_balance_ids: [ "10000002" ])
+
+ WiseItem::Importer.new(@wise_item, wise_provider: provider).import
+
+ eur_account.reload
+ assert_includes provider.calls, :get_transfers
+ refute_includes eur_account.raw_transactions_payload.filter_map { |t| t["id"] }, 99
+ assert_includes eur_account.raw_transactions_payload.filter_map { |t| t["referenceNumber"] }, "already-migrated-eur"
+ end
+
test "keeps transfer cutoff incremental after the first sync when full history is enabled" do
@wise_item.update!(import_all_history: true)
@wise_item.wise_accounts.create!(
diff --git a/test/models/wise_item_test.rb b/test/models/wise_item_test.rb
index b913e5e705..6a9ad4af36 100644
--- a/test/models/wise_item_test.rb
+++ b/test/models/wise_item_test.rb
@@ -44,6 +44,38 @@ class WiseItemTest < ActiveSupport::TestCase
AccountProvider.create!(account: @jar_sure_account, provider: @jar_account)
end
+ # SCA keypair
+
+ test "sca_configured? is false without a private key" do
+ assert_not @wise_item.sca_configured?
+ assert_nil @wise_item.sca_public_key
+ end
+
+ test "sca_configured? is false when the stored private key is corrupted" do
+ @wise_item.update_column(:sca_private_key, "not a real PEM")
+
+ assert_nil @wise_item.sca_public_key
+ assert_not @wise_item.sca_configured?
+ end
+
+ test "generate_sca_keypair! stores a private key and returns a matching public key" do
+ public_pem = @wise_item.generate_sca_keypair!
+
+ assert @wise_item.sca_configured?
+ assert_includes public_pem, "PUBLIC KEY"
+ assert_equal public_pem, @wise_item.sca_public_key
+
+ private_key = OpenSSL::PKey::RSA.new(@wise_item.sca_private_key)
+ assert_equal private_key.public_key.to_pem, public_pem
+ end
+
+ test "generate_sca_keypair! replaces a previously generated key" do
+ first_public_key = @wise_item.generate_sca_keypair!
+ second_public_key = @wise_item.generate_sca_keypair!
+
+ assert_not_equal first_public_key, second_public_key
+ end
+
# link_jar_transfers!
test "links matching interbalance inflow and outflow entries as a Transfer" do