Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Block SimpleFIN URLs that target internal addresses (#4194)

GFR36287e8ed2cb
diff --git a/app/controllers/simplefin_items_controller.rb b/app/controllers/simplefin_items_controller.rb
index 26db18302f..d3f52a7614 100644
--- a/app/controllers/simplefin_items_controller.rb
+++ b/app/controllers/simplefin_items_controller.rb
@@ -22,9 +22,9 @@ class SimplefinItemsController < ApplicationController
return render_error(t(".errors.blank_token"), context: :edit) if setup_token.blank?
begin
- # Validate token shape early so the user gets immediate feedback.
- claim_url = Base64.decode64(setup_token)
- URI.parse(claim_url)
+ # Validate the token's claim URL (shape and address) early so the user
+ # gets immediate feedback; the job claims it later.
+ Provider::Simplefin.new.validate_setup_token!(setup_token)
# Updating a SimpleFin connection can involve network retries/backoff and account import.
# Do it asynchronously so web requests aren't blocked by retry sleeps.
@@ -46,6 +46,8 @@ class SimplefinItemsController < ApplicationController
error_message = case e.error_type
when :token_compromised
t(".errors.token_compromised")
+ when :invalid_url
+ t(".errors.invalid_token")
else
t(".errors.update_failed", message: e.message)
end
@@ -78,6 +80,8 @@ class SimplefinItemsController < ApplicationController
error_message = case e.error_type
when :token_compromised
t(".errors.token_compromised")
+ when :invalid_url
+ t(".errors.invalid_token")
else
t(".errors.create_failed", message: e.message)
end
diff --git a/app/jobs/simplefin_connection_update_job.rb b/app/jobs/simplefin_connection_update_job.rb
index db4593762e..7a71bd8005 100644
--- a/app/jobs/simplefin_connection_update_job.rb
+++ b/app/jobs/simplefin_connection_update_job.rb
@@ -4,9 +4,19 @@ class SimplefinConnectionUpdateJob < ApplicationJob
# Disable automatic retries for this job since the setup token is single-use.
# If the token claim succeeds but sync fails, retrying would fail at claim.
discard_on Provider::Simplefin::SimplefinError do |job, error|
+ args = job.arguments.first
Rails.logger.error(
"SimplefinConnectionUpdateJob discarded: #{error.class} - #{error.message} " \
- "(family_id=#{job.arguments.first[:family_id]}, item_id=#{job.arguments.first[:old_simplefin_item_id]})"
+ "(family_id=#{args[:family_id]}, item_id=#{args[:old_simplefin_item_id]})"
+ )
+ DebugLogEntry.capture(
+ category: "provider_sync",
+ level: "error",
+ message: "SimpleFIN reconnect failed: #{error.message}",
+ source: "SimplefinConnectionUpdateJob",
+ family_id: args[:family_id],
+ provider_key: "simplefin",
+ metadata: { simplefin_item_id: args[:old_simplefin_item_id], error_type: error.error_type }
)
end
diff --git a/app/models/provider/simplefin.rb b/app/models/provider/simplefin.rb
index 7cf7b514b5..14e78b4398 100644
--- a/app/models/provider/simplefin.rb
+++ b/app/models/provider/simplefin.rb
@@ -27,24 +27,72 @@ class Provider::Simplefin
EOFError
].freeze
+ # Address ranges for the SimpleFIN URL check (see ensure_allowed_url!).
+ # Always blocked besides link-local: unspecified, multicast and reserved
+ # addresses, and cloud metadata endpoints outside the link-local range
+ # (AWS IPv6 in fc00::/7, Alibaba Cloud in the CGNAT range).
+ ALWAYS_BLOCKED_NETWORKS = %w[
+ 0.0.0.0/8 224.0.0.0/4 240.0.0.0/4 ::/128 ff00::/8
+ fd00:ec2::254/128 100.100.100.200/32
+ ].map { |range| IPAddr.new(range) }.freeze
+ # Blocked on managed instances besides loopback and private ranges:
+ # carrier-grade NAT, IETF protocol assignments and benchmarking ranges.
+ MANAGED_BLOCKED_NETWORKS = %w[100.64.0.0/10 192.0.0.0/24 198.18.0.0/15].map { |range| IPAddr.new(range) }.freeze
+ # IPv6 ranges that carry an IPv4 address, checked like that IPv4 address.
+ NAT64_NETWORK = IPAddr.new("64:ff9b::/96")
+ IPV4_TRANSLATED_NETWORK = IPAddr.new("::ffff:0:0:0/96")
+ SIX_TO_FOUR_NETWORK = IPAddr.new("2002::/16")
+ IPV4_COMPATIBLE_NETWORK = IPAddr.new("::/96")
+
+ # Connects to the address that ensure_allowed_url! checked instead of
+ # resolving the host a second time, so DNS rebinding cannot swap in an
+ # internal address. TLS (SNI, certificate) and the Host header still use
+ # the hostname. Through an HTTP proxy, https requests are pinned too
+ # (Net::HTTP sends CONNECT to the pinned address); plain http requests
+ # skip the proxy (see guarded_request_options).
+ class PinnedConnectionAdapter < HTTParty::ConnectionAdapter
+ def connection
+ http = super
+ pinned_address = options.dig(:connection_adapter_options, :ipaddr)
+ http.ipaddr = pinned_address if pinned_address
+ http
+ end
+ end
+
def initialize
end
+ # Checks a setup token's claim URL without claiming it, so callers that
+ # claim later (in a job) can reject a bad token right away.
+ def validate_setup_token!(setup_token)
+ ensure_allowed_url!(Base64.decode64(setup_token))
+ nil
+ rescue SocketError
+ raise SimplefinError.new("SimpleFIN host could not be resolved", :network_error)
+ end
+
def claim_access_url(setup_token)
# Decode the base64 setup token to get the claim URL
claim_url = Base64.decode64(setup_token)
# Use retry logic for transient network failures during token claim
# Claim should be fast; keep request-path latency bounded.
- # Use self.class.post to inherit class-level SSL and timeout defaults
- response = with_retries("POST /claim", max_retries: 1, backoff: false) do
- self.class.post(claim_url, timeout: 15)
+ # Use self.class.post to inherit class-level SSL and timeout defaults.
+ # The setup token is user input, so it must not point the server at
+ # internal services (cloud metadata, localhost, private networks).
+ response = with_retries("POST /claim", max_retries: 1, backoff: false) do |attempt|
+ self.class.post(claim_url, timeout: 15, **guarded_request_options(claim_url, attempt: attempt))
end
case response.code
when 200
- # The response body contains the access URL with embedded credentials
- response.body.strip
+ # The response body contains the access URL with embedded credentials.
+ # It comes from the same untrusted bridge. The token is used up now, so
+ # only check what needs no DNS lookup; a transient lookup failure must not
+ # lose the URL. get_accounts runs the full check before every request.
+ access_url = response.body.strip
+ ensure_allowed_url!(access_url, resolve: false)
+ access_url
when 403
raise SimplefinError.new("Setup token may be compromised, expired, or already used", :token_compromised)
else
@@ -79,8 +127,9 @@ class Provider::Simplefin
# The access URL already contains HTTP Basic Auth credentials
# Use retry logic with exponential backoff for transient network failures
# Use self.class.get to inherit class-level SSL and timeout defaults
- response = with_retries("GET /accounts") do
- self.class.get(accounts_url)
+ # The stored access URL came from the bridge; re-check it on every request.
+ response = with_retries("GET /accounts") do |attempt|
+ self.class.get(accounts_url, **guarded_request_options(access_url, attempt: attempt))
end
case response.code
@@ -88,7 +137,7 @@ class Provider::Simplefin
JSON.parse(response.body, symbolize_names: true)
when 400
Rails.logger.error "SimpleFin API: Bad request - #{response.body}"
- raise SimplefinError.new("Bad request to SimpleFin API: #{response.body}", :bad_request)
+ raise SimplefinError.new("Bad request to SimpleFin API", :bad_request)
when 403
raise SimplefinError.new("Access URL is no longer valid", :access_forbidden)
when 402
@@ -101,13 +150,13 @@ class Provider::Simplefin
raise SimplefinError.new("SimpleFin server error (#{response.code}). Please try again later.", :server_error)
else
Rails.logger.error "SimpleFin API: Unexpected response - Code: #{response.code}, Body: #{response.body}"
- raise SimplefinError.new("Failed to fetch accounts: #{response.code} #{response.message} - #{response.body}", :fetch_failed)
+ raise SimplefinError.new("Failed to fetch accounts: #{response.code} #{response.message}", :fetch_failed)
end
end
def get_info(base_url)
# Use self.class.get to inherit class-level SSL and timeout defaults
- response = self.class.get("#{base_url}/info")
+ response = self.class.get("#{base_url}/info", **guarded_request_options(base_url))
case response.code
when 200
@@ -127,6 +176,95 @@ class Provider::Simplefin
end
private
+ # Checks the URL, then pins the connection to one of the checked
+ # addresses; each retry moves on to the next one, like the resolver
+ # fallback of an unpinned connection. No redirects: a redirect target
+ # would bypass the check. A proxy would resolve a plain http host itself,
+ # so plain http (self-hosted only) connects directly.
+ def guarded_request_options(url, attempt: 0)
+ addresses = ensure_allowed_url!(url)
+ options = {
+ follow_redirects: false,
+ connection_adapter: PinnedConnectionAdapter,
+ connection_adapter_options: { ipaddr: addresses[attempt % addresses.size] }
+ }
+ options[:http_proxyaddr] = nil if URI.parse(url.to_s).scheme == "http"
+ options
+ end
+
+ # Link-local covers cloud metadata endpoints (169.254.169.254) and is
+ # never a valid bridge address. Managed instances additionally block
+ # loopback and private networks; self-hosters may run a bridge on their
+ # own network, so those stay allowed there.
+ #
+ # Returns the checked addresses, IPv4 first. With resolve: false only an
+ # IP literal host is checked. A failed lookup raises SocketError, so
+ # with_retries retries it and reports :network_error, not :invalid_url.
+ def ensure_allowed_url!(url, resolve: true)
+ uri = URI.parse(url.to_s)
+ raise SimplefinError.new("SimpleFIN URL must use http or https", :invalid_url) unless uri.is_a?(URI::HTTP) && uri.host.present?
+ raise SimplefinError.new("SimpleFIN URL must use https", :invalid_url) if managed_mode? && uri.scheme != "https"
+
+ addresses = resolve ? resolve_addresses(uri.hostname) : ip_literal_addresses(uri.hostname)
+ raise SocketError, "SimpleFIN host could not be resolved" if resolve && addresses.empty?
+
+ if addresses.any? { |address| disallowed_address?(address) }
+ raise SimplefinError.new("SimpleFIN URL points to a disallowed network address", :invalid_url)
+ end
+
+ # IPv4-mapped IPv6 addresses connect as plain IPv4. Prefer IPv4: many
+ # self-hosted Docker setups have no IPv6 route.
+ addresses.map { |address| normalize_address(address) }.uniq
+ .sort_by.with_index { |address, index| [ IPAddr.new(address).ipv4? ? 0 : 1, index ] }
+ rescue URI::InvalidURIError
+ raise SimplefinError.new("SimpleFIN URL is invalid", :invalid_url)
+ end
+
+ # Uses the system resolver, like the HTTP request itself (mDNS, hosts file).
+ def resolve_addresses(host)
+ Addrinfo.getaddrinfo(host, nil, nil, :STREAM).map(&:ip_address).uniq
+ end
+
+ def normalize_address(address)
+ ip = IPAddr.new(address)
+ ip.ipv4_mapped? ? ip.native.to_s : address
+ end
+
+ def ip_literal_addresses(host)
+ IPAddr.new(host)
+ [ host ]
+ rescue IPAddr::InvalidAddressError
+ []
+ end
+
+ def disallowed_address?(address)
+ ip = embedded_ipv4(IPAddr.new(address))
+ return true if ip.link_local? || ALWAYS_BLOCKED_NETWORKS.any? { |network| network.include?(ip) }
+ return false unless managed_mode?
+
+ ip.loopback? || ip.private? || MANAGED_BLOCKED_NETWORKS.any? { |network| network.include?(ip) }
+ rescue IPAddr::InvalidAddressError
+ true
+ end
+
+ # IPv4-mapped, IPv4-compatible, NAT64 and 6to4 addresses reach the IPv4
+ # address they carry, so they are checked as that address.
+ def embedded_ipv4(ip)
+ return ip unless ip.ipv6?
+ return ip.native if ip.ipv4_mapped?
+
+ if NAT64_NETWORK.include?(ip) || IPV4_TRANSLATED_NETWORK.include?(ip) || (IPV4_COMPATIBLE_NETWORK.include?(ip) && ip.to_i > 1)
+ IPAddr.new(ip.to_i & 0xffff_ffff, Socket::AF_INET)
+ elsif SIX_TO_FOUR_NETWORK.include?(ip)
+ IPAddr.new((ip.to_i >> 80) & 0xffff_ffff, Socket::AF_INET)
+ else
+ ip
+ end
+ end
+
+ def managed_mode?
+ Rails.application.config.app_mode.managed?
+ end
# Execute a block with retry logic and exponential backoff for transient network errors.
# This helps handle temporary network issues that cause autosync failures while
@@ -135,7 +273,7 @@ class Provider::Simplefin
retries = 0
begin
- yield
+ yield retries
rescue *RETRYABLE_ERRORS => e
retries += 1
diff --git a/app/models/simplefin_item/importer.rb b/app/models/simplefin_item/importer.rb
index 422f4c6158..aacfa4c74a 100644
--- a/app/models/simplefin_item/importer.rb
+++ b/app/models/simplefin_item/importer.rb
@@ -715,6 +715,20 @@ class SimplefinItem::Importer
if e.error_type == :access_forbidden
simplefin_item.update!(status: :requires_update)
raise e
+ elsif e.error_type == :invalid_url
+ # The stored access URL fails the address check; only a new setup
+ # token can fix it, so ask the user to reconnect.
+ simplefin_item.update!(status: :requires_update)
+ DebugLogEntry.capture(
+ category: "provider_sync",
+ level: "warn",
+ message: "SimpleFIN access URL rejected: #{e.message}",
+ source: self.class.name,
+ family: simplefin_item.family,
+ provider_key: "simplefin",
+ metadata: { simplefin_item_id: simplefin_item.id, error_type: e.error_type }
+ )
+ raise e
else
raise e
end
diff --git a/test/controllers/simplefin_items_controller_test.rb b/test/controllers/simplefin_items_controller_test.rb
index 5835a52582..51ec5b6a57 100644
--- a/test/controllers/simplefin_items_controller_test.rb
+++ b/test/controllers/simplefin_items_controller_test.rb
@@ -11,6 +11,8 @@ class SimplefinItemsControllerTest < ActionDispatch::IntegrationTest
name: "Test Connection",
access_url: "https://example.com/test_access"
)
+ # Setup tokens are checked before the claim job runs; keep tests off DNS.
+ Provider::Simplefin.any_instance.stubs(:resolve_addresses).returns([ "93.184.216.34" ])
end
@@ -209,6 +211,17 @@ class SimplefinItemsControllerTest < ActionDispatch::IntegrationTest
assert_equal "SimpleFIN connection updated.", flash[:notice]
end
+ test "update rejects a token whose claim URL targets a disallowed address" do
+ @simplefin_item.update!(status: :requires_update)
+ token = Base64.strict_encode64("http://169.254.169.254/latest/meta-data/")
+ SimplefinConnectionUpdateJob.expects(:perform_later).never
+
+ patch simplefin_item_url(@simplefin_item), params: { simplefin_item: { setup_token: token } }
+
+ assert_response :unprocessable_entity
+ assert_includes response.body, ERB::Util.html_escape(I18n.t("simplefin_items.update.errors.invalid_token"))
+ end
+
test "should handle update with invalid token" do
@simplefin_item.update!(status: :requires_update)
@@ -253,6 +266,17 @@ class SimplefinItemsControllerTest < ActionDispatch::IntegrationTest
assert_includes response.body, I18n.t("simplefin_items.create.errors.blank_token")
end
+ test "create with a token that is not an http url shows the invalid token message" do
+ token = Base64.strict_encode64("file:///etc/passwd")
+
+ assert_no_difference "SimplefinItem.count" do
+ post simplefin_items_url, params: { simplefin_item: { setup_token: token } }
+ end
+
+ assert_response :unprocessable_entity
+ assert_includes response.body, ERB::Util.html_escape(I18n.t("simplefin_items.create.errors.invalid_token"))
+ end
+
test "should update simplefin item access_url in place preserving account linkages" do
@simplefin_item.update!(status: :requires_update)
original_item_id = @simplefin_item.id
@@ -301,6 +325,7 @@ class SimplefinItemsControllerTest < ActionDispatch::IntegrationTest
# Mock only the external API calls
mock_provider = mock()
+ mock_provider.stubs(:validate_setup_token!)
mock_provider.expects(:claim_access_url).with(token).returns("https://example.com/new_access")
Provider::Simplefin.expects(:new).returns(mock_provider).at_least_once
@@ -362,6 +387,7 @@ class SimplefinItemsControllerTest < ActionDispatch::IntegrationTest
# Mock only the external API calls
mock_provider = mock()
+ mock_provider.stubs(:validate_setup_token!)
mock_provider.expects(:claim_access_url).with(token).returns("https://example.com/new_access")
Provider::Simplefin.expects(:new).returns(mock_provider).at_least_once
diff --git a/test/jobs/simplefin_connection_update_job_test.rb b/test/jobs/simplefin_connection_update_job_test.rb
new file mode 100644
index 0000000000..1f5bbdb66d
--- /dev/null
+++ b/test/jobs/simplefin_connection_update_job_test.rb
@@ -0,0 +1,21 @@
+require "test_helper"
+
+class SimplefinConnectionUpdateJobTest < ActiveJob::TestCase
+ setup do
+ @family = families(:dylan_family)
+ @item = SimplefinItem.create!(family: @family, name: "Reconnect Test", access_url: "https://example.com/access")
+ end
+
+ test "a rejected setup token is discarded and logged for support" do
+ SimplefinItem.any_instance.expects(:update_access_url!)
+ .raises(Provider::Simplefin::SimplefinError.new("SimpleFIN URL points to a disallowed network address", :invalid_url))
+
+ assert_difference -> { DebugLogEntry.where(provider_key: "simplefin", family: @family).count }, 1 do
+ SimplefinConnectionUpdateJob.perform_now(family_id: @family.id, old_simplefin_item_id: @item.id, setup_token: "token")
+ end
+
+ entry = DebugLogEntry.where(provider_key: "simplefin").order(:created_at).last
+ assert_equal "invalid_url", entry.metadata["error_type"]
+ assert_not_includes entry.message, "token"
+ end
+end
diff --git a/test/models/provider/simplefin_test.rb b/test/models/provider/simplefin_test.rb
index 5693c752ce..8f0f3d481a 100644
--- a/test/models/provider/simplefin_test.rb
+++ b/test/models/provider/simplefin_test.rb
@@ -4,6 +4,7 @@ class Provider::SimplefinTest < ActiveSupport::TestCase
setup do
@provider = Provider::Simplefin.new
@access_url = "https://example.com/simplefin/access"
+ @provider.stubs(:resolve_addresses).returns([ "93.184.216.34" ])
end
test "retries on Net::ReadTimeout and succeeds on retry" do
@@ -184,4 +185,304 @@ class Provider::SimplefinTest < ActiveSupport::TestCase
assert delay <= Provider::Simplefin::MAX_RETRY_DELAY,
"Delay should be capped at MAX_RETRY_DELAY (#{Provider::Simplefin::MAX_RETRY_DELAY}s)"
end
+
+ test "claim_access_url rejects setup tokens pointing at link-local metadata addresses" do
+ @provider.stubs(:resolve_addresses).with("169.254.169.254").returns([ "169.254.169.254" ])
+ Provider::Simplefin.expects(:post).never
+
+ error = assert_raises(Provider::Simplefin::SimplefinError) do
+ @provider.claim_access_url(Base64.strict_encode64("http://169.254.169.254/latest/meta-data/"))
+ end
+
+ assert_equal :invalid_url, error.error_type
+ end
+
+ test "claim_access_url rejects hosts that resolve to a link-local address" do
+ @provider.stubs(:resolve_addresses).with("metadata.example.test").returns([ "169.254.169.254" ])
+ Provider::Simplefin.expects(:post).never
+
+ error = assert_raises(Provider::Simplefin::SimplefinError) do
+ @provider.claim_access_url(Base64.strict_encode64("https://metadata.example.test/claim"))
+ end
+
+ assert_equal :invalid_url, error.error_type
+ end
+
+ test "claim_access_url rejects the AWS IPv6 metadata address when self-hosted" do
+ @provider.stubs(:resolve_addresses).with("metadata6.example.test").returns([ "fd00:ec2::254" ])
+ Provider::Simplefin.expects(:post).never
+
+ with_self_hosting do
+ error = assert_raises(Provider::Simplefin::SimplefinError) do
+ @provider.claim_access_url(Base64.strict_encode64("http://metadata6.example.test/latest"))
+ end
+
+ assert_equal :invalid_url, error.error_type
+ end
+ end
+
+ test "claim_access_url rejects non-http schemes" do
+ Provider::Simplefin.expects(:post).never
+
+ error = assert_raises(Provider::Simplefin::SimplefinError) do
+ @provider.claim_access_url(Base64.strict_encode64("file:///etc/passwd"))
+ end
+
+ assert_equal :invalid_url, error.error_type
+ end
+
+ test "claim_access_url allows private bridge addresses when self-hosted" do
+ @provider.stubs(:resolve_addresses).with("bridge.lan").returns([ "192.168.1.20" ])
+ Provider::Simplefin.expects(:post).returns(OpenStruct.new(code: 200, body: "http://user:[email protected]/simplefin"))
+
+ with_self_hosting do
+ assert_equal "http://user:[email protected]/simplefin",
+ @provider.claim_access_url(Base64.strict_encode64("http://bridge.lan/simplefin/claim/abc"))
+ end
+ end
+
+ test "claim_access_url rejects private and loopback addresses on managed instances" do
+ Rails.configuration.stubs(:app_mode).returns("managed".inquiry)
+ Provider::Simplefin.expects(:post).never
+
+ {
+ "bridge.lan" => "192.168.1.20", "localhost" => "127.0.0.1", "v6.lan" => "fd00::1",
+ "cgnat.example.test" => "100.64.0.1", "bench.example.test" => "198.18.0.1"
+ }.each do |host, address|
+ @provider.stubs(:resolve_addresses).with(host).returns([ address ])
+
+ error = assert_raises(Provider::Simplefin::SimplefinError, "#{host} should be rejected") do
+ @provider.claim_access_url(Base64.strict_encode64("https://#{host}/claim"))
+ end
+
+ assert_equal :invalid_url, error.error_type
+ end
+ end
+
+ test "claim_access_url requires https on managed instances" do
+ Rails.configuration.stubs(:app_mode).returns("managed".inquiry)
+ Provider::Simplefin.expects(:post).never
+
+ error = assert_raises(Provider::Simplefin::SimplefinError) do
+ @provider.claim_access_url(Base64.strict_encode64("http://bridge.simplefin.org/claim"))
+ end
+
+ assert_equal :invalid_url, error.error_type
+ end
+
+ test "claim_access_url rejects an access URL pointing at a disallowed address" do
+ @provider.stubs(:resolve_addresses).with("169.254.169.254").returns([ "169.254.169.254" ])
+ Provider::Simplefin.expects(:post).returns(OpenStruct.new(code: 200, body: "http://169.254.169.254/latest"))
+
+ error = assert_raises(Provider::Simplefin::SimplefinError) do
+ @provider.claim_access_url(Base64.strict_encode64("https://example.com/claim"))
+ end
+
+ assert_equal :invalid_url, error.error_type
+ end
+
+ test "claim_access_url keeps the claimed access URL without resolving its host" do
+ Provider::Simplefin.expects(:post).returns(OpenStruct.new(code: 200, body: "https://user:[email protected]/simplefin"))
+ @provider.expects(:resolve_addresses).with("flaky.example.test").never
+
+ assert_equal "https://user:[email protected]/simplefin",
+ @provider.claim_access_url(Base64.strict_encode64("https://example.com/claim"))
+ end
+
+ test "claim_access_url does not follow redirects" do
+ Provider::Simplefin.expects(:post).with("https://example.com/claim", has_entry(follow_redirects: false))
+ .returns(OpenStruct.new(code: 200, body: "https://example.com/access"))
+
+ @provider.claim_access_url(Base64.strict_encode64("https://example.com/claim"))
+ end
+
+ test "get_accounts does not echo the response body in error messages" do
+ Provider::Simplefin.expects(:get).returns(OpenStruct.new(code: 418, message: "I'm a teapot", body: "internal-secret"))
+
+ error = assert_raises(Provider::Simplefin::SimplefinError) { @provider.get_accounts(@access_url) }
+
+ assert_not_includes error.message, "internal-secret"
+ end
+
+ test "get_accounts rejects a stored access URL pointing at a disallowed address" do
+ @provider.stubs(:resolve_addresses).with("169.254.169.254").returns([ "169.254.169.254" ])
+ Provider::Simplefin.expects(:get).never
+
+ error = assert_raises(Provider::Simplefin::SimplefinError) do
+ @provider.get_accounts("http://user:[email protected]/simplefin")
+ end
+
+ assert_equal :invalid_url, error.error_type
+ end
+
+ test "get_accounts does not follow redirects" do
+ Provider::Simplefin.expects(:get).with("#{@access_url}/accounts?version=2", has_entry(follow_redirects: false))
+ .returns(OpenStruct.new(code: 200, body: '{"accounts": []}'))
+
+ @provider.get_accounts(@access_url)
+ end
+
+ test "get_info rejects a base URL pointing at a disallowed address" do
+ @provider.stubs(:resolve_addresses).with("169.254.169.254").returns([ "169.254.169.254" ])
+ Provider::Simplefin.expects(:get).never
+
+ error = assert_raises(Provider::Simplefin::SimplefinError) do
+ @provider.get_info("http://169.254.169.254/simplefin")
+ end
+
+ assert_equal :invalid_url, error.error_type
+ end
+
+ test "get_info does not follow redirects" do
+ Provider::Simplefin.expects(:get).with("https://example.com/simplefin/info", has_entry(follow_redirects: false))
+ .returns(OpenStruct.new(code: 200, body: "1.0\n"))
+
+ assert_equal [ "1.0" ], @provider.get_info("https://example.com/simplefin")
+ end
+
+ test "an unresolvable host raises a network error, not an invalid url" do
+ @provider.stubs(:sleep)
+ @provider.stubs(:resolve_addresses).with("flaky.example.test").raises(SocketError, "getaddrinfo: Name or service not known")
+ Provider::Simplefin.expects(:get).never
+
+ error = assert_raises(Provider::Simplefin::SimplefinError) do
+ @provider.get_accounts("https://user:[email protected]/simplefin")
+ end
+
+ assert_equal :network_error, error.error_type
+ end
+
+ test "a transient DNS failure during sync is retried" do
+ @provider.stubs(:sleep)
+ @provider.stubs(:resolve_addresses).with("example.com")
+ .raises(SocketError, "getaddrinfo: Temporary failure in name resolution").then.returns([ "93.184.216.34" ])
+ Provider::Simplefin.expects(:get).once.returns(OpenStruct.new(code: 200, body: '{"accounts": []}'))
+
+ assert_equal({ accounts: [] }, @provider.get_accounts(@access_url))
+ end
+
+ test "rejects IPv6 addresses that carry a blocked IPv4 address" do
+ Provider::Simplefin.expects(:get).never
+
+ with_self_hosting do
+ [ "::ffff:169.254.169.254", "64:ff9b::a9fe:a9fe", "::ffff:0:a9fe:a9fe", "2002:a9fe:a9fe::1", "::a9fe:a9fe" ].each do |address|
+ @provider.stubs(:resolve_addresses).with("wrapped.example.test").returns([ address ])
+
+ error = assert_raises(Provider::Simplefin::SimplefinError, "#{address} should be rejected") do
+ @provider.get_accounts("https://wrapped.example.test/simplefin")
+ end
+
+ assert_equal :invalid_url, error.error_type
+ end
+ end
+ end
+
+ test "rejects multicast and reserved addresses when self-hosted" do
+ Provider::Simplefin.expects(:get).never
+
+ with_self_hosting do
+ [ "224.0.0.1", "255.255.255.255", "ff02::1" ].each do |address|
+ @provider.stubs(:resolve_addresses).with("odd.example.test").returns([ address ])
+
+ error = assert_raises(Provider::Simplefin::SimplefinError, "#{address} should be rejected") do
+ @provider.get_accounts("https://odd.example.test/simplefin")
+ end
+
+ assert_equal :invalid_url, error.error_type
+ end
+ end
+ end
+
+ test "connects to the checked address, preferring IPv4" do
+ @provider.stubs(:resolve_addresses).with("example.com").returns([ "2606:2800:220:1::1", "93.184.216.34" ])
+ Provider::Simplefin.expects(:get).with(
+ "#{@access_url}/accounts?version=2",
+ has_entries(
+ connection_adapter: Provider::Simplefin::PinnedConnectionAdapter,
+ connection_adapter_options: { ipaddr: "93.184.216.34" }
+ )
+ ).returns(OpenStruct.new(code: 200, body: '{"accounts": []}'))
+
+ @provider.get_accounts(@access_url)
+ end
+
+ test "the pinned connection adapter connects to the given address" do
+ http = Provider::Simplefin::PinnedConnectionAdapter.new(
+ URI("https://example.com/simplefin"),
+ connection_adapter_options: { ipaddr: "93.184.216.34" }
+ ).connection
+
+ assert_equal "93.184.216.34", http.ipaddr
+ assert_equal "example.com", http.address
+ end
+
+ test "rejects the Alibaba Cloud metadata address when self-hosted" do
+ @provider.stubs(:resolve_addresses).with("meta.example.test").returns([ "100.100.100.200" ])
+ Provider::Simplefin.expects(:get).never
+
+ with_self_hosting do
+ error = assert_raises(Provider::Simplefin::SimplefinError) do
+ @provider.get_accounts("https://meta.example.test/simplefin")
+ end
+
+ assert_equal :invalid_url, error.error_type
+ end
+ end
+
+ test "connects to an IPv4-mapped address as plain IPv4" do
+ @provider.stubs(:resolve_addresses).with("example.com").returns([ "::ffff:93.184.216.34" ])
+ Provider::Simplefin.expects(:get).with(
+ "#{@access_url}/accounts?version=2", has_entry(connection_adapter_options: { ipaddr: "93.184.216.34" })
+ ).returns(OpenStruct.new(code: 200, body: '{"accounts": []}'))
+
+ @provider.get_accounts(@access_url)
+ end
+
+ test "a retry connects to the next checked address" do
+ @provider.stubs(:sleep)
+ @provider.stubs(:resolve_addresses).with("example.com").returns([ "93.184.216.34", "93.184.216.35" ])
+ sequence = sequence("addresses")
+ Provider::Simplefin.expects(:get).with(anything, has_entry(connection_adapter_options: { ipaddr: "93.184.216.34" }))
+ .in_sequence(sequence).raises(Errno::ECONNREFUSED)
+ Provider::Simplefin.expects(:get).with(anything, has_entry(connection_adapter_options: { ipaddr: "93.184.216.35" }))
+ .in_sequence(sequence).returns(OpenStruct.new(code: 200, body: '{"accounts": []}'))
+
+ assert_equal({ accounts: [] }, @provider.get_accounts(@access_url))
+ end
+
+ test "plain http requests bypass a proxy so the pinned address is used" do
+ @provider.stubs(:resolve_addresses).with("bridge.lan").returns([ "192.168.1.20" ])
+ Provider::Simplefin.expects(:get).with(anything, has_entry(http_proxyaddr: nil))
+ .returns(OpenStruct.new(code: 200, body: '{"accounts": []}'))
+
+ with_self_hosting { @provider.get_accounts("http://user:[email protected]/simplefin") }
+ end
+
+ test "https requests keep the configured proxy" do
+ Provider::Simplefin.expects(:get).with(anything, Not(has_key(:http_proxyaddr)))
+ .returns(OpenStruct.new(code: 200, body: '{"accounts": []}'))
+
+ @provider.get_accounts(@access_url)
+ end
+
+ test "validate_setup_token! rejects disallowed claim URLs without claiming" do
+ @provider.stubs(:resolve_addresses).with("169.254.169.254").returns([ "169.254.169.254" ])
+ Provider::Simplefin.expects(:post).never
+
+ error = assert_raises(Provider::Simplefin::SimplefinError) do
+ @provider.validate_setup_token!(Base64.strict_encode64("http://169.254.169.254/claim"))
+ end
+
+ assert_equal :invalid_url, error.error_type
+ end
+
+ test "validate_setup_token! reports an unresolvable host as a network error" do
+ @provider.stubs(:resolve_addresses).with("flaky.example.test").raises(SocketError, "getaddrinfo failed")
+
+ error = assert_raises(Provider::Simplefin::SimplefinError) do
+ @provider.validate_setup_token!(Base64.strict_encode64("https://flaky.example.test/claim"))
+ end
+
+ assert_equal :network_error, error.error_type
+ end
end
diff --git a/test/models/simplefin_item/importer_test.rb b/test/models/simplefin_item/importer_test.rb
index a4e67f98ef..78c0a667c0 100644
--- a/test/models/simplefin_item/importer_test.rb
+++ b/test/models/simplefin_item/importer_test.rb
@@ -139,6 +139,22 @@ class SimplefinItem::ImporterTest < ActiveSupport::TestCase
assert_equal [ "simplefin_false" ], account.entries.where(excluded: false).pluck(:name)
end
+ test "a rejected access URL marks the item for reconnection and logs it" do
+ provider = mock
+ provider.expects(:get_accounts).raises(
+ Provider::Simplefin::SimplefinError.new("SimpleFIN URL points to a disallowed network address", :invalid_url)
+ )
+ importer = SimplefinItem::Importer.new(@item, simplefin_provider: provider)
+
+ assert_difference -> { DebugLogEntry.where(provider_key: "simplefin", family: @family).count }, 1 do
+ assert_raises(Provider::Simplefin::SimplefinError) do
+ importer.send(:fetch_accounts_data, start_date: nil, pending: false)
+ end
+ end
+
+ assert @item.reload.requires_update?
+ end
+
private
def create_pending_entry(account, name, provider, pending, amount)