Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

fix(enable-banking): respect ASPSP consent duration instead of hardcoding 90 days (#3038)

GFR316317e085f8
diff --git a/app/jobs/data_cleaner_job.rb b/app/jobs/data_cleaner_job.rb
index becf0fba5e..70e05e86a1 100644
--- a/app/jobs/data_cleaner_job.rb
+++ b/app/jobs/data_cleaner_job.rb
@@ -4,6 +4,7 @@ class DataCleanerJob < ApplicationJob
def perform
clean_old_merchant_associations
clean_expired_archived_exports
+ clean_stale_enable_banking_psu_ips
end
private
@@ -21,4 +22,22 @@ class DataCleanerJob < ApplicationJob
Rails.logger.info("DataCleanerJob: Deleted #{deleted_count} expired archived exports") if deleted_count > 0
end
+
+ # Iterated (rather than a single update_all) so each cleared item can be
+ # logged with its family attached, making the cleanup visible per-family
+ # in /settings/debug instead of only in Docker/Sidekiq logs.
+ def clean_stale_enable_banking_psu_ips
+ EnableBankingItem.with_stale_psu_ip.find_each do |item|
+ item.update!(last_psu_ip: nil)
+
+ DebugLogEntry.capture(
+ category: "background_jobs",
+ level: "info",
+ message: "Cleared stale Enable Banking last_psu_ip",
+ source: self.class.name,
+ family: item.family,
+ metadata: { enable_banking_item_id: item.id }
+ )
+ end
+ end
end
diff --git a/app/models/enable_banking_item.rb b/app/models/enable_banking_item.rb
index 8916946fec..130ecfbae7 100644
--- a/app/models/enable_banking_item.rb
+++ b/app/models/enable_banking_item.rb
@@ -27,6 +27,25 @@ class EnableBankingItem < ApplicationRecord
scope :ordered, -> { order(created_at: :desc) }
scope :needs_update, -> { where(status: :requires_update) }
+ # Nullify last_psu_ip once it's no longer needed for provider sync — either the
+ # consent session has actually expired, or (for items that never completed
+ # authorization, so session_expires_at is nil) once the ASPSP-accepted consent
+ # duration we stored at request time (requested_consent_valid_until) has
+ # elapsed, or — only if that wasn't recorded either — once the configured
+ # fallback window has elapsed since the record was last touched. Checking
+ # requested_consent_valid_until first prevents retaining the PSU IP past a
+ # shorter duration the ASPSP actually accepted (it can be less than the
+ # configured ceiling) for authorizations that never reached session creation.
+ scope :with_stale_psu_ip, -> {
+ fallback_cutoff = Rails.configuration.x.enable_banking.consent_days.days.ago
+ where.not(last_psu_ip: nil).where(
+ "(session_expires_at IS NOT NULL AND session_expires_at <= :now) OR " \
+ "(session_expires_at IS NULL AND requested_consent_valid_until IS NOT NULL AND requested_consent_valid_until <= :now) OR " \
+ "(session_expires_at IS NULL AND requested_consent_valid_until IS NULL AND updated_at <= :fallback_cutoff)",
+ now: Time.current, fallback_cutoff: fallback_cutoff
+ )
+ }
+
def credentials_configured?
application_id.present? && client_certificate.present? && country_code.present?
end
@@ -43,8 +62,6 @@ class EnableBankingItem < ApplicationRecord
!session_valid?
end
- # TODO: implement data retention policy for last_psu_ip (GDPR/CCPA — nullify after session expiry or 90 days)
-
validate :psu_type_in_aspsp_types
def psu_type_in_aspsp_types
@@ -108,7 +125,8 @@ class EnableBankingItem < ApplicationRecord
attributes = {
authorization_id: result[:authorization_id],
- aspsp_name: aspsp_name
+ aspsp_name: aspsp_name,
+ requested_consent_valid_until: result[:requested_valid_until]
}
attributes[:psu_type] = validated_psu_type if validated_psu_type.present?
@@ -149,6 +167,7 @@ class EnableBankingItem < ApplicationRecord
session_id: result[:session_id],
session_expires_at: parse_session_expiry(result),
authorization_id: nil, # Clear the authorization ID
+ requested_consent_valid_until: nil, # Only needed as a fallback until the session is established
status: :good
)
@@ -330,7 +349,8 @@ class EnableBankingItem < ApplicationRecord
update!(
session_id: nil,
session_expires_at: nil,
- authorization_id: nil
+ authorization_id: nil,
+ last_psu_ip: nil
)
end
end
@@ -383,15 +403,20 @@ class EnableBankingItem < ApplicationRecord
end
def parse_session_expiry(session_result)
+ # Prefer the duration actually accepted by the ASPSP during start_authorization
+ # (which may be shorter than the configured ceiling, e.g. after a fallback retry)
+ # over the global default, so session_valid? doesn't outlive the real consent.
+ default_expiry = requested_consent_valid_until || Rails.configuration.x.enable_banking.consent_days.days.from_now
+
if session_result[:access].present? && session_result[:access][:valid_until].present?
parsed = Time.zone.parse(session_result[:access][:valid_until])
- parsed || 90.days.from_now
+ parsed || default_expiry
else
- 90.days.from_now
+ default_expiry
end
rescue ArgumentError, TypeError => e
Rails.logger.warn "EnableBankingItem #{id} - Failed to parse session expiry: #{e.message}"
- 90.days.from_now
+ default_expiry
end
def import_accounts_from_session(accounts_data)
diff --git a/app/models/provider/enable_banking.rb b/app/models/provider/enable_banking.rb
index f231a9363c..3fd1e5808c 100644
--- a/app/models/provider/enable_banking.rb
+++ b/app/models/provider/enable_banking.rb
@@ -11,6 +11,12 @@ class Provider::EnableBanking
# suggesting a corrected date_from in the response payload.
FALLBACK_TRANSACTIONS_DATE_FROM_DAYS = [ 89, 60, 30 ].freeze
+ # Progressive fallback windows (days) for retrying an authorization request when
+ # an ASPSP rejects the requested consent duration (e.g. Trade Republic caps at
+ # exactly 90 days). Mirrors FALLBACK_TRANSACTIONS_DATE_FROM_DAYS's proven pattern.
+ CONSENT_FALLBACK_DAYS = [ 180, 90, 45, 30 ].freeze
+ CONSENT_SAFETY_MARGIN_SECONDS = 60 # shaved off every attempt to guard against clock/network drift
+
headers "User-Agent" => "Sure Finance Enable Banking Client"
default_options.merge!({ timeout: 120 }.merge(httparty_ssl_options))
@@ -42,7 +48,8 @@ class Provider::EnableBanking
# @param redirect_url [String] URL to redirect user back to after auth
# @param state [String, nil] State parameter to pass through
# @param psu_type [String] "personal" or "business"
- # @param maximum_consent_validity [Integer, nil] Max consent duration in seconds from ASPSP (nil = use 90 days)
+ # @param maximum_consent_validity [Integer, nil] Max consent duration in seconds from ASPSP
+ # (nil = use configured default, currently 180 days, see ENABLE_BANKING_CONSENT_DAYS)
# @param language [String, nil] Two-letter language code (e.g. "fr", "en")
# @param auth_method [String, nil] Name of a specific authentication method to use (from the ASPSP's
# auth_methods list). Required to drive DECOUPLED/EMBEDDED banks that expose several methods; when nil
@@ -50,34 +57,31 @@ class Provider::EnableBanking
# @return [Hash] Contains :url and :authorization_id
def start_authorization(aspsp_name:, aspsp_country:, redirect_url:, state: nil,
psu_type: "personal", maximum_consent_validity: nil, language: nil, auth_method: nil)
- max_seconds = maximum_consent_validity ? [ maximum_consent_validity, 1 ].max : 90.days.to_i
- valid_until = [ Time.current + max_seconds.seconds, Time.current + 90.days ].min
+ last_error = nil
+
+ consent_seconds_ladder(maximum_consent_validity).each do |seconds|
+ valid_until = Time.current + seconds.seconds
+ body = build_authorization_body(
+ aspsp_name: aspsp_name, aspsp_country: aspsp_country, redirect_url: redirect_url,
+ state: state, psu_type: psu_type, language: language, auth_method: auth_method,
+ valid_until: valid_until
+ )
- body = {
- access: {
- valid_until: valid_until.iso8601,
- balances: true,
- transactions: true
- },
- aspsp: {
- name: aspsp_name,
- country: aspsp_country
- },
- state: state,
- redirect_url: redirect_url,
- psu_type: psu_type
- }
- body[:language] = language if language.present?
- body[:auth_method] = auth_method if auth_method.present?
- body = body.compact
+ response = self.class.post(
+ "#{BASE_URL}/auth",
+ headers: auth_headers.merge("Content-Type" => "application/json"),
+ body: body.to_json
+ )
- response = self.class.post(
- "#{BASE_URL}/auth",
- headers: auth_headers.merge("Content-Type" => "application/json"),
- body: body.to_json
- )
+ begin
+ return handle_response(response).merge(requested_valid_until: valid_until)
+ rescue EnableBankingError => e
+ raise unless e.wrong_consent_validity?
+ last_error = e
+ end
+ end
- handle_response(response)
+ raise last_error
rescue SocketError, Net::OpenTimeout, Net::ReadTimeout => e
raise EnableBankingError.new("Exception during POST request: #{e.message}", :request_failed)
end
@@ -235,6 +239,55 @@ class Provider::EnableBanking
.find { |candidate| current.nil? || candidate > current }
end
+ # Builds the ladder of consent durations (seconds) to try, most-preferred first:
+ # 1. The ASPSP's own advertised limit (authoritative) if present and sane,
+ # capped defensively at our own configured ceiling.
+ # 2. Progressively shorter fallback rungs (only ones strictly shorter than the
+ # first, so the ladder always makes forward progress and terminates).
+ # Every rung is shaved by a small safety margin so client/server clock drift
+ # and network latency can never push the *actual* requested duration over the
+ # rung's exact boundary (root cause of #2857).
+ def consent_seconds_ladder(maximum_consent_validity)
+ cap_seconds = Rails.configuration.x.enable_banking.consent_days.days.to_i
+ aspsp_seconds = normalized_consent_seconds(maximum_consent_validity)
+
+ primary = [ aspsp_seconds || cap_seconds, cap_seconds ].min
+ fallback_seconds = CONSENT_FALLBACK_DAYS.map(&:days).map(&:to_i).select { |s| s < primary }
+
+ ([ primary ] + fallback_seconds).map { |s| s - consent_safety_margin(s) }.uniq
+ end
+
+ def consent_safety_margin(seconds)
+ [ CONSENT_SAFETY_MARGIN_SECONDS, seconds - 1 ].min
+ end
+
+ def normalized_consent_seconds(value)
+ seconds = Integer(value)
+ seconds.positive? ? seconds : nil
+ rescue TypeError, ArgumentError
+ nil
+ end
+
+ def build_authorization_body(aspsp_name:, aspsp_country:, redirect_url:, state:, psu_type:, language:, auth_method:, valid_until:)
+ body = {
+ access: {
+ valid_until: valid_until.iso8601,
+ balances: true,
+ transactions: true
+ },
+ aspsp: {
+ name: aspsp_name,
+ country: aspsp_country
+ },
+ state: state,
+ redirect_url: redirect_url,
+ psu_type: psu_type
+ }
+ body[:language] = language if language.present?
+ body[:auth_method] = auth_method if auth_method.present?
+ body.compact
+ end
+
def safe_psu_headers(headers)
headers.except("Authorization", :Authorization, "Accept", :Accept, "Content-Type", :"Content-Type")
end
@@ -339,6 +392,17 @@ class Provider::EnableBanking
response_data[:error] == "WRONG_TRANSACTIONS_PERIOD" || response_data[:code] == "PERIOD_INVALID"
end
+ # WRONG_REQUEST_PARAMETERS is a generic error code shared by several unrelated
+ # validation failures (e.g. a bad redirect_url, handled separately by the
+ # controller). Match on the message text so we only retry with a shorter
+ # consent window for the specific rejection this ladder is meant to recover
+ # from, instead of silently masking other validation errors.
+ def wrong_consent_validity?
+ error_type == :validation_error && response_data.is_a?(Hash) &&
+ response_data[:error] == "WRONG_REQUEST_PARAMETERS" &&
+ response_data[:message].to_s.match?(/consent validity/i)
+ end
+
def corrected_date_from
detail = response_data.is_a?(Hash) ? response_data[:detail] : nil
return nil unless detail.is_a?(Hash)
diff --git a/config/initializers/enable_banking.rb b/config/initializers/enable_banking.rb
new file mode 100644
index 0000000000..1a2f9b3558
--- /dev/null
+++ b/config/initializers/enable_banking.rb
@@ -0,0 +1,13 @@
+Rails.application.configure do
+ config.x.enable_banking ||= ActiveSupport::OrderedOptions.new
+
+ # Ceiling for requested consent duration (days). Used as the top rung of the
+ # fallback ladder when an ASPSP doesn't advertise maximum_consent_validity,
+ # and as a defensive cap against an implausibly large ASPSP-reported value.
+ # Enable Banking's own default became 180 days in Oct 2025; the EU SCA
+ # renewal window for account-information access was extended from 90 to
+ # 180 days for the same reason. Set ENABLE_BANKING_CONSENT_DAYS to override.
+ raw_configured_days = ENV["ENABLE_BANKING_CONSENT_DAYS"].presence
+ configured_days = raw_configured_days.to_i if raw_configured_days&.match?(/\A\d+\z/)
+ config.x.enable_banking.consent_days = (configured_days && configured_days.positive?) ? configured_days : 180
+end
diff --git a/db/migrate/20260920000001_add_requested_consent_valid_until_to_enable_banking_items.rb b/db/migrate/20260920000001_add_requested_consent_valid_until_to_enable_banking_items.rb
new file mode 100644
index 0000000000..8851a9b4b3
--- /dev/null
+++ b/db/migrate/20260920000001_add_requested_consent_valid_until_to_enable_banking_items.rb
@@ -0,0 +1,5 @@
+class AddRequestedConsentValidUntilToEnableBankingItems < ActiveRecord::Migration[8.1]
+ def change
+ add_column :enable_banking_items, :requested_consent_valid_until, :datetime
+ end
+end
diff --git a/db/migrate/20260920000002_add_stale_psu_ip_indexes_to_enable_banking_items.rb b/db/migrate/20260920000002_add_stale_psu_ip_indexes_to_enable_banking_items.rb
new file mode 100644
index 0000000000..9762a9f7fc
--- /dev/null
+++ b/db/migrate/20260920000002_add_stale_psu_ip_indexes_to_enable_banking_items.rb
@@ -0,0 +1,20 @@
+class AddStalePsuIpIndexesToEnableBankingItems < ActiveRecord::Migration[8.1]
+ disable_ddl_transaction!
+
+ def change
+ # Support the with_stale_psu_ip scope's two branches without scanning the
+ # whole table: items with an expired session, and items that never
+ # completed authorization (session_expires_at IS NULL) falling back to
+ # updated_at. Both are partial on last_psu_ip IS NOT NULL since the scope
+ # always filters on that first.
+ add_index :enable_banking_items, :session_expires_at,
+ where: "last_psu_ip IS NOT NULL",
+ name: "index_enable_banking_items_on_session_expires_at_for_stale_ip",
+ algorithm: :concurrently
+
+ add_index :enable_banking_items, :updated_at,
+ where: "last_psu_ip IS NOT NULL AND session_expires_at IS NULL",
+ name: "index_enable_banking_items_on_updated_at_for_stale_ip",
+ algorithm: :concurrently
+ end
+end
diff --git a/db/migrate/20260920000004_add_requested_consent_valid_until_index_to_enable_banking_items.rb b/db/migrate/20260920000004_add_requested_consent_valid_until_index_to_enable_banking_items.rb
new file mode 100644
index 0000000000..2106b1aa9b
--- /dev/null
+++ b/db/migrate/20260920000004_add_requested_consent_valid_until_index_to_enable_banking_items.rb
@@ -0,0 +1,14 @@
+class AddRequestedConsentValidUntilIndexToEnableBankingItems < ActiveRecord::Migration[8.1]
+ disable_ddl_transaction!
+
+ def change
+ # Supports the with_stale_psu_ip scope's new middle branch: items that never
+ # completed authorization (session_expires_at IS NULL) but do have an
+ # ASPSP-accepted consent duration on record, which takes priority over the
+ # updated_at fallback.
+ add_index :enable_banking_items, :requested_consent_valid_until,
+ where: "last_psu_ip IS NOT NULL AND session_expires_at IS NULL",
+ name: "index_enable_banking_items_on_requested_consent_for_stale_ip",
+ algorithm: :concurrently
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index f18e132f1a..21f0919ad8 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -685,6 +685,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_09_22_230000) do
t.string "psu_type"
t.jsonb "raw_institution_payload"
t.jsonb "raw_payload"
+ t.datetime "requested_consent_valid_until"
t.boolean "scheduled_for_deletion", default: false
t.datetime "session_expires_at"
t.string "session_id"
@@ -692,7 +693,10 @@ ActiveRecord::Schema[8.1].define(version: 2026_09_22_230000) do
t.date "sync_start_date"
t.datetime "updated_at", null: false
t.index ["family_id"], name: "index_enable_banking_items_on_family_id"
+ t.index ["requested_consent_valid_until"], name: "index_enable_banking_items_on_requested_consent_for_stale_ip", where: "((last_psu_ip IS NOT NULL) AND (session_expires_at IS NULL))"
+ t.index ["session_expires_at"], name: "index_enable_banking_items_on_session_expires_at_for_stale_ip", where: "(last_psu_ip IS NOT NULL)"
t.index ["status"], name: "index_enable_banking_items_on_status"
+ t.index ["updated_at"], name: "index_enable_banking_items_on_updated_at_for_stale_ip", where: "((last_psu_ip IS NOT NULL) AND (session_expires_at IS NULL))"
end
create_table "entries", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
diff --git a/test/jobs/data_cleaner_job_test.rb b/test/jobs/data_cleaner_job_test.rb
new file mode 100644
index 0000000000..c00368964f
--- /dev/null
+++ b/test/jobs/data_cleaner_job_test.rb
@@ -0,0 +1,27 @@
+require "test_helper"
+
+class DataCleanerJobTest < ActiveSupport::TestCase
+ test "clears last_psu_ip on Enable Banking items with an expired session" do
+ expired = EnableBankingItem.create!(
+ family: families(:dylan_family), name: "Expired", country_code: "DE",
+ application_id: "app", client_certificate: "cert",
+ last_psu_ip: "1.2.3.4", session_id: "sess", session_expires_at: 1.day.ago
+ )
+
+ DataCleanerJob.perform_now
+
+ assert_nil expired.reload.last_psu_ip
+ end
+
+ test "keeps last_psu_ip on Enable Banking items with a valid session" do
+ active = EnableBankingItem.create!(
+ family: families(:dylan_family), name: "Active", country_code: "DE",
+ application_id: "app", client_certificate: "cert",
+ last_psu_ip: "1.2.3.4", session_id: "sess", session_expires_at: 1.day.from_now
+ )
+
+ DataCleanerJob.perform_now
+
+ assert_equal "1.2.3.4", active.reload.last_psu_ip
+ end
+end
diff --git a/test/models/enable_banking_item_test.rb b/test/models/enable_banking_item_test.rb
index 83e1011197..80b025a88d 100644
--- a/test/models/enable_banking_item_test.rb
+++ b/test/models/enable_banking_item_test.rb
@@ -103,4 +103,135 @@ class EnableBankingItemTest < ActiveSupport::TestCase
assert_equal original.to_i, @item.reload.session_expires_at.to_i
end
+
+ test "parse_session_expiry falls back to the configured consent_days when valid_until is missing" do
+ original = Rails.configuration.x.enable_banking.consent_days
+ Rails.configuration.x.enable_banking.consent_days = 120
+
+ travel_to Time.zone.parse("2026-01-01 12:00:00") do
+ expiry = @item.send(:parse_session_expiry, { access: {} })
+
+ assert_equal 120.days.from_now.to_i, expiry.to_i
+ end
+ ensure
+ Rails.configuration.x.enable_banking.consent_days = original
+ end
+
+ test "parse_session_expiry prefers the requested consent duration over the configured ceiling when valid_until is missing" do
+ original = Rails.configuration.x.enable_banking.consent_days
+ Rails.configuration.x.enable_banking.consent_days = 180
+
+ travel_to Time.zone.parse("2026-01-01 12:00:00") do
+ accepted_valid_until = 60.days.from_now
+ @item.requested_consent_valid_until = accepted_valid_until
+
+ expiry = @item.send(:parse_session_expiry, { access: {} })
+
+ assert_equal accepted_valid_until.to_i, expiry.to_i
+ end
+ ensure
+ Rails.configuration.x.enable_banking.consent_days = original
+ end
+
+ test "with_stale_psu_ip matches items whose session has expired" do
+ expired = EnableBankingItem.create!(
+ family: families(:dylan_family), name: "Expired", country_code: "DE",
+ application_id: "app", client_certificate: "cert",
+ last_psu_ip: "1.2.3.4", session_id: "sess", session_expires_at: 1.day.ago
+ )
+
+ assert_includes EnableBankingItem.with_stale_psu_ip, expired
+ end
+
+ test "with_stale_psu_ip excludes items with a still-valid session" do
+ active = EnableBankingItem.create!(
+ family: families(:dylan_family), name: "Active", country_code: "DE",
+ application_id: "app", client_certificate: "cert",
+ last_psu_ip: "1.2.3.4", session_id: "sess", session_expires_at: 1.day.from_now
+ )
+
+ assert_not_includes EnableBankingItem.with_stale_psu_ip, active
+ end
+
+ test "with_stale_psu_ip matches abandoned authorizations once the configured window elapses" do
+ abandoned = EnableBankingItem.create!(
+ family: families(:dylan_family), name: "Abandoned", country_code: "DE",
+ application_id: "app", client_certificate: "cert", last_psu_ip: "1.2.3.4"
+ )
+ abandoned.update_column(:updated_at, (Rails.configuration.x.enable_banking.consent_days + 1).days.ago)
+
+ assert_includes EnableBankingItem.with_stale_psu_ip, abandoned
+ end
+
+ test "with_stale_psu_ip matches abandoned authorizations whose accepted consent duration has passed, even before the configured window elapses" do
+ abandoned = EnableBankingItem.create!(
+ family: families(:dylan_family), name: "Abandoned short consent", country_code: "DE",
+ application_id: "app", client_certificate: "cert", last_psu_ip: "1.2.3.4",
+ requested_consent_valid_until: 1.day.ago
+ )
+
+ assert_includes EnableBankingItem.with_stale_psu_ip, abandoned
+ end
+
+ test "with_stale_psu_ip excludes abandoned authorizations whose accepted consent duration hasn't passed yet" do
+ abandoned = EnableBankingItem.create!(
+ family: families(:dylan_family), name: "Abandoned still within consent", country_code: "DE",
+ application_id: "app", client_certificate: "cert", last_psu_ip: "1.2.3.4",
+ requested_consent_valid_until: 1.day.from_now
+ )
+ abandoned.update_column(:updated_at, (Rails.configuration.x.enable_banking.consent_days + 1).days.ago)
+
+ assert_not_includes EnableBankingItem.with_stale_psu_ip, abandoned
+ end
+
+ test "with_stale_psu_ip excludes items without a stored last_psu_ip" do
+ clean = EnableBankingItem.create!(
+ family: families(:dylan_family), name: "Clean", country_code: "DE",
+ application_id: "app", client_certificate: "cert",
+ session_id: "sess", session_expires_at: 1.day.ago
+ )
+
+ assert_not_includes EnableBankingItem.with_stale_psu_ip, clean
+ end
+
+ test "revoke_session clears last_psu_ip along with the session" do
+ item = EnableBankingItem.create!(
+ family: families(:dylan_family), name: "Revoked", country_code: "DE",
+ application_id: "app", client_certificate: "cert",
+ last_psu_ip: "1.2.3.4", session_id: "sess", session_expires_at: 1.day.from_now,
+ authorization_id: "auth"
+ )
+ provider = mock("enable_banking_provider")
+ provider.expects(:delete_session).with(session_id: "sess")
+ item.stubs(:enable_banking_provider).returns(provider)
+
+ item.revoke_session
+ item.reload
+
+ assert_nil item.session_id
+ assert_nil item.session_expires_at
+ assert_nil item.authorization_id
+ assert_nil item.last_psu_ip
+ end
+
+ test "revoke_session clears last_psu_ip even when the provider raises" do
+ item = EnableBankingItem.create!(
+ family: families(:dylan_family), name: "Revoked despite provider error", country_code: "DE",
+ application_id: "app", client_certificate: "cert",
+ last_psu_ip: "1.2.3.4", session_id: "sess", session_expires_at: 1.day.from_now,
+ authorization_id: "auth"
+ )
+ provider = mock("enable_banking_provider")
+ provider.expects(:delete_session).with(session_id: "sess")
+ .raises(Provider::EnableBanking::EnableBankingError.new("boom"))
+ item.stubs(:enable_banking_provider).returns(provider)
+
+ item.revoke_session
+ item.reload
+
+ assert_nil item.session_id
+ assert_nil item.session_expires_at
+ assert_nil item.authorization_id
+ assert_nil item.last_psu_ip
+ end
end
diff --git a/test/models/provider/enable_banking_test.rb b/test/models/provider/enable_banking_test.rb
index cac58affcc..3b7fbc91cd 100644
--- a/test/models/provider/enable_banking_test.rb
+++ b/test/models/provider/enable_banking_test.rb
@@ -211,6 +211,218 @@ class Provider::EnableBankingTest < ActiveSupport::TestCase
assert_not captured_body.key?("auth_method")
end
+
+ test "start_authorization requests up to the configured ceiling when the ASPSP reports no limit" do
+ captured_body = nil
+ response = OpenStruct.new(
+ code: 200,
+ body: { url: "https://api.enablebanking.com/auth/abc", authorization_id: "auth_1" }.to_json
+ )
+
+ Provider::EnableBanking.expects(:post).once.with do |_url, options|
+ captured_body = JSON.parse(options[:body])
+ true
+ end.returns(response)
+
+ travel_to Time.zone.parse("2026-01-01 12:00:00") do
+ @provider.start_authorization(
+ aspsp_name: "ING-DiBa AG",
+ aspsp_country: "DE",
+ redirect_url: "https://app.example.com/callback"
+ )
+
+ expected = Time.current + 180.days - 60.seconds
+ assert_equal expected.iso8601, captured_body["access"]["valid_until"]
+ end
+ end
+
+ test "start_authorization respects an ASPSP limit below the configured ceiling" do
+ captured_body = nil
+ response = OpenStruct.new(
+ code: 200,
+ body: { url: "https://api.enablebanking.com/auth/abc", authorization_id: "auth_1" }.to_json
+ )
+
+ Provider::EnableBanking.expects(:post).once.with do |_url, options|
+ captured_body = JSON.parse(options[:body])
+ true
+ end.returns(response)
+
+ travel_to Time.zone.parse("2026-01-01 12:00:00") do
+ @provider.start_authorization(
+ aspsp_name: "ING-DiBa AG",
+ aspsp_country: "DE",
+ redirect_url: "https://app.example.com/callback",
+ maximum_consent_validity: 60.days.to_i
+ )
+
+ expected = Time.current + 60.days - 60.seconds
+ assert_equal expected.iso8601, captured_body["access"]["valid_until"]
+ end
+ end
+
+ test "start_authorization caps an ASPSP limit above the configured ceiling" do
+ captured_body = nil
+ response = OpenStruct.new(
+ code: 200,
+ body: { url: "https://api.enablebanking.com/auth/abc", authorization_id: "auth_1" }.to_json
+ )
+
+ Provider::EnableBanking.expects(:post).once.with do |_url, options|
+ captured_body = JSON.parse(options[:body])
+ true
+ end.returns(response)
+
+ travel_to Time.zone.parse("2026-01-01 12:00:00") do
+ @provider.start_authorization(
+ aspsp_name: "ING-DiBa AG",
+ aspsp_country: "DE",
+ redirect_url: "https://app.example.com/callback",
+ maximum_consent_validity: 400.days.to_i
+ )
+
+ expected = Time.current + 180.days - 60.seconds
+ assert_equal expected.iso8601, captured_body["access"]["valid_until"]
+ end
+ end
+
+ test "start_authorization treats invalid maximum_consent_validity values as absent" do
+ [ 0, -100, "abc", nil ].each do |bad_value|
+ captured_body = nil
+ response = OpenStruct.new(
+ code: 200,
+ body: { url: "https://api.enablebanking.com/auth/abc", authorization_id: "auth_1" }.to_json
+ )
+
+ Provider::EnableBanking.expects(:post).once.with do |_url, options|
+ captured_body = JSON.parse(options[:body])
+ true
+ end.returns(response)
+
+ travel_to Time.zone.parse("2026-01-01 12:00:00") do
+ @provider.start_authorization(
+ aspsp_name: "ING-DiBa AG",
+ aspsp_country: "DE",
+ redirect_url: "https://app.example.com/callback",
+ maximum_consent_validity: bad_value
+ )
+
+ expected = Time.current + 180.days - 60.seconds
+ assert_equal expected.iso8601, captured_body["access"]["valid_until"]
+ end
+ end
+ end
+
+ test "start_authorization falls back to a shorter window when the ASPSP rejects the requested consent duration" do
+ # Simulates the Trade Republic case (#2857): the ASPSP advertises exactly 90
+ # days but still rejects the first (margin-adjusted) attempt.
+ rejected_response = OpenStruct.new(
+ code: 422,
+ body: {
+ code: 422,
+ message: "ASPSP does not support consent validity more than 7776000 seconds in the future",
+ error: "WRONG_REQUEST_PARAMETERS",
+ detail: nil
+ }.to_json
+ )
+ success_response = OpenStruct.new(
+ code: 200,
+ body: { url: "https://api.enablebanking.com/auth/abc", authorization_id: "auth_1" }.to_json
+ )
+
+ captured_bodies = []
+ Provider::EnableBanking.expects(:post).twice.with do |_url, options|
+ captured_bodies << JSON.parse(options[:body])
+ true
+ end.returns(rejected_response, success_response)
+
+ result = @provider.start_authorization(
+ aspsp_name: "Trade Republic",
+ aspsp_country: "DE",
+ redirect_url: "https://app.example.com/callback",
+ maximum_consent_validity: 90.days.to_i
+ )
+
+ assert_equal "auth_1", result[:authorization_id]
+ first_valid_until = Time.iso8601(captured_bodies[0]["access"]["valid_until"])
+ second_valid_until = Time.iso8601(captured_bodies[1]["access"]["valid_until"])
+ assert second_valid_until < first_valid_until
+ end
+
+ test "start_authorization raises after exhausting the fallback ladder" do
+ rejected_response = OpenStruct.new(
+ code: 422,
+ body: {
+ message: "ASPSP does not support consent validity more than 7776000 seconds in the future",
+ error: "WRONG_REQUEST_PARAMETERS"
+ }.to_json
+ )
+
+ Provider::EnableBanking.expects(:post).times(3).returns(rejected_response, rejected_response, rejected_response)
+
+ error = assert_raises Provider::EnableBanking::EnableBankingError do
+ @provider.start_authorization(
+ aspsp_name: "Trade Republic",
+ aspsp_country: "DE",
+ redirect_url: "https://app.example.com/callback",
+ maximum_consent_validity: 90.days.to_i
+ )
+ end
+
+ assert error.wrong_consent_validity?
+ end
+
+ test "start_authorization does not retry on an unrelated WRONG_REQUEST_PARAMETERS error" do
+ rejected_response = OpenStruct.new(
+ code: 422,
+ body: {
+ message: "redirect_url is not a valid URL",
+ error: "WRONG_REQUEST_PARAMETERS"
+ }.to_json
+ )
+
+ Provider::EnableBanking.expects(:post).once.returns(rejected_response)
+
+ error = assert_raises Provider::EnableBanking::EnableBankingError do
+ @provider.start_authorization(
+ aspsp_name: "ING-DiBa AG",
+ aspsp_country: "DE",
+ redirect_url: "not-a-url"
+ )
+ end
+
+ assert_not error.wrong_consent_validity?
+ end
+
+ test "start_authorization honors an overridden consent_days configuration" do
+ original = Rails.configuration.x.enable_banking.consent_days
+ Rails.configuration.x.enable_banking.consent_days = 90
+
+ captured_body = nil
+ response = OpenStruct.new(
+ code: 200,
+ body: { url: "https://api.enablebanking.com/auth/abc", authorization_id: "auth_1" }.to_json
+ )
+
+ Provider::EnableBanking.expects(:post).once.with do |_url, options|
+ captured_body = JSON.parse(options[:body])
+ true
+ end.returns(response)
+
+ travel_to Time.zone.parse("2026-01-01 12:00:00") do
+ @provider.start_authorization(
+ aspsp_name: "ING-DiBa AG",
+ aspsp_country: "DE",
+ redirect_url: "https://app.example.com/callback"
+ )
+
+ expected = Time.current + 90.days - 60.seconds
+ assert_equal expected.iso8601, captured_body["access"]["valid_until"]
+ end
+ ensure
+ Rails.configuration.x.enable_banking.consent_days = original
+ end
+
test "bad request errors expose parsed response data" do
response = OpenStruct.new(
code: 400,