From 5b1e40d986589e6cc8ef8de0bb4c0c5c8e3a5a28 Mon Sep 17 00:00:00 2001 From: david ruiz Date: Thu, 5 Nov 2026 10:38:58 +0100 Subject: [PATCH 1/5] build path upgrade --- lib/checkout_sdk/apm/bacs/bacs_client.rb | 7 +- .../apm/previous/sepa/sepa_client.rb | 13 +-- lib/checkout_sdk/checkout_utils.rb | 27 ++++++ lib/checkout_sdk/client.rb | 9 +- .../instruments/instruments_client.rb | 7 +- .../payments/setups/payment_setups_client.rb | 8 ++ spec/checkout_sdk/checkout_utils_spec.rb | 46 +++++++++ spec/checkout_sdk/client_spec.rb | 97 +++++++++++++++++++ .../setups/payment_setups_client_spec.rb | 21 ++++ 9 files changed, 221 insertions(+), 14 deletions(-) create mode 100644 spec/checkout_sdk/client_spec.rb diff --git a/lib/checkout_sdk/apm/bacs/bacs_client.rb b/lib/checkout_sdk/apm/bacs/bacs_client.rb index ad4bd01..ea512a8 100644 --- a/lib/checkout_sdk/apm/bacs/bacs_client.rb +++ b/lib/checkout_sdk/apm/bacs/bacs_client.rb @@ -5,8 +5,9 @@ module Apm # Bacs Direct Debit client. class BacsClient < Client APMS = 'apms' - BACS_NOTIFICATIONS = 'bacs/notifications' - private_constant :APMS, :BACS_NOTIFICATIONS + BACS = 'bacs' + NOTIFICATIONS = 'notifications' + private_constant :APMS, :BACS, :NOTIFICATIONS # @param [ApiClient] api_client # @param [CheckoutConfiguration] configuration @@ -20,7 +21,7 @@ def initialize(api_client, configuration) # @param [Hash, BacsNotificationRequest] bacs_notification_request # @return [Hash] the BacsNotificationResponse, carrying event_id. def send_notification(bacs_notification_request) - api_client.invoke_post(build_path(APMS, BACS_NOTIFICATIONS), + api_client.invoke_post(build_path(APMS, BACS, NOTIFICATIONS), sdk_authorization, bacs_notification_request) end diff --git a/lib/checkout_sdk/apm/previous/sepa/sepa_client.rb b/lib/checkout_sdk/apm/previous/sepa/sepa_client.rb index 32e12a4..183c607 100644 --- a/lib/checkout_sdk/apm/previous/sepa/sepa_client.rb +++ b/lib/checkout_sdk/apm/previous/sepa/sepa_client.rb @@ -5,10 +5,11 @@ module Previous module Apm class SepaClient < Client APMS = 'apms' - SEPA_MANDATES = 'sepa/mandates' + SEPA = 'sepa' + MANDATES = 'mandates' PPRO = 'ppro' CANCEL = 'cancel' - private_constant :APMS, :SEPA_MANDATES, :PPRO, :CANCEL + private_constant :APMS, :SEPA, :MANDATES, :PPRO, :CANCEL # @param [ApiClient] api_client # @param [CheckoutConfiguration] configuration @@ -18,22 +19,22 @@ def initialize(api_client, configuration) # @param mandate_id [String] def get_mandate(mandate_id) - api_client.invoke_get(build_path(SEPA_MANDATES, mandate_id), sdk_authorization) + api_client.invoke_get(build_path(SEPA, MANDATES, mandate_id), sdk_authorization) end # @param mandate_id [String] def cancel_mandate(mandate_id) - api_client.invoke_post(build_path(SEPA_MANDATES, mandate_id, CANCEL), sdk_authorization) + api_client.invoke_post(build_path(SEPA, MANDATES, mandate_id, CANCEL), sdk_authorization) end # @param mandate_id [String] def get_mandate_via_ppro(mandate_id) - api_client.invoke_get(build_path(APMS, PPRO, SEPA_MANDATES, mandate_id), sdk_authorization) + api_client.invoke_get(build_path(APMS, PPRO, SEPA, MANDATES, mandate_id), sdk_authorization) end # @param mandate_id [String] def cancel_mandate_via_ppro(mandate_id) - api_client.invoke_post(build_path(APMS, PPRO, SEPA_MANDATES, mandate_id, CANCEL), sdk_authorization) + api_client.invoke_post(build_path(APMS, PPRO, SEPA, MANDATES, mandate_id, CANCEL), sdk_authorization) end end end diff --git a/lib/checkout_sdk/checkout_utils.rb b/lib/checkout_sdk/checkout_utils.rb index 9be9c75..b45519d 100644 --- a/lib/checkout_sdk/checkout_utils.rb +++ b/lib/checkout_sdk/checkout_utils.rb @@ -52,6 +52,33 @@ def self.error_message(prefix, body, include_text_body: false) "#{prefix} Details: #{escape_control_characters(details)}." end + INVALID_PATH_SEGMENTS = ['', '.', '..'].freeze + private_constant :INVALID_PATH_SEGMENTS + + # Encodes a value as one RFC 3986 path segment. Every byte of its UTF-8 form outside the + # unreserved set (A-Z, a-z, 0-9, "-", ".", "_", "~") is percent-encoded, so the value always + # stays a single segment of the request path. + # + # @param [String, Symbol, Integer] value + # @return [String] + # @raise [CheckoutArgumentException] when the value is nil, empty, "." or ".." + def self.encode_path_segment(value) + text = value.nil? ? '' : value.to_s + if INVALID_PATH_SEGMENTS.include?(text) + raise CheckoutArgumentException, "Invalid path segment: it must not be nil, empty, '.' or '..'" + end + + utf8_bytes(text).gsub(/[^A-Za-z0-9\-._~]/n) { |byte| format('%%%02X', byte.ord) } + .force_encoding(Encoding::UTF_8) + end + + def self.utf8_bytes(text) + text.encode(Encoding::UTF_8).b + rescue EncodingError + text.b + end + private_class_method :utf8_bytes + # Returns a copy of the Faraday error, of the same class and with the same backtrace and wrapped # exception, that keeps only the response status, headers and body and whose message names the # method and URL without the query string. Errors without a response are returned unchanged. diff --git a/lib/checkout_sdk/client.rb b/lib/checkout_sdk/client.rb index 9d62e44..def837b 100644 --- a/lib/checkout_sdk/client.rb +++ b/lib/checkout_sdk/client.rb @@ -23,9 +23,14 @@ def initialize(api_client, configuration, authorization_type) @configuration = configuration end - # @param [Array] args + # Joins the arguments into a request path. Each argument is one path segment and is + # percent-encoded, so it never adds segments, a query or a fragment. + # + # @param [Array] args + # @return [String] + # @raise [CheckoutArgumentException] when an argument is nil, empty, "." or ".." def build_path(*args) - args.join('/') + args.map { |segment| CheckoutUtils.encode_path_segment(segment) }.join('/') end # @return [TrueClass, FalseClass] diff --git a/lib/checkout_sdk/instruments/instruments_client.rb b/lib/checkout_sdk/instruments/instruments_client.rb index c4927f2..18d6489 100644 --- a/lib/checkout_sdk/instruments/instruments_client.rb +++ b/lib/checkout_sdk/instruments/instruments_client.rb @@ -3,8 +3,9 @@ module CheckoutSdk module Instruments class InstrumentsClient < BaseInstrumentsClient - VALIDATION = 'validation/bank-accounts' - private_constant :VALIDATION + VALIDATION = 'validation' + BANK_ACCOUNTS = 'bank-accounts' + private_constant :VALIDATION, :BANK_ACCOUNTS # @param [ApiClient] api_client # @param [CheckoutConfiguration] configuration @@ -29,7 +30,7 @@ def update(instrument_id, update_instrument_request) # @param [String] currency {CheckoutSdk::Common::Currency} # @param [Hash, BankAccountFieldQuery] bank_account_field_query def get_bank_account_field_formatting(country, currency, bank_account_field_query) - api_client.invoke_get(build_path(VALIDATION, country, currency), + api_client.invoke_get(build_path(VALIDATION, BANK_ACCOUNTS, country, currency), sdk_authorization(CheckoutSdk::AuthorizationType::OAUTH), bank_account_field_query) end diff --git a/lib/checkout_sdk/payments/setups/payment_setups_client.rb b/lib/checkout_sdk/payments/setups/payment_setups_client.rb index 791836f..223c860 100644 --- a/lib/checkout_sdk/payments/setups/payment_setups_client.rb +++ b/lib/checkout_sdk/payments/setups/payment_setups_client.rb @@ -8,6 +8,8 @@ class PaymentSetupsClient < Client PAYMENTS_PATH = 'payments' SETUPS_PATH = 'setups' CONFIRM_PATH = 'confirm' + PAYMENT_METHOD_NAME_PATTERN = /\A[a-z0-9_]+\z/i.freeze + private_constant :PAYMENT_METHOD_NAME_PATTERN # @param [ApiClient] api_client # @param [CheckoutConfiguration] configuration @@ -248,7 +250,13 @@ def get_payment_setup(id) # :schemes (supported card scheme names; Google Pay never lists cartes_bancaires) and card # details :last4, :bin, :scheme (Strings) and :expires_on (date-time); instrument returns the # read-only :type (String) and :action (:type, "set_instrument"). + # @raise [CheckoutArgumentException] when payment_method_name is not a payment method name + # (letters, digits and underscores), or id is nil or empty def confirm_payment_setup(id, payment_method_name) + unless PAYMENT_METHOD_NAME_PATTERN.match?(payment_method_name.to_s) + raise CheckoutArgumentException, 'Invalid payment method name' + end + api_client.invoke_post( build_path(PAYMENTS_PATH, SETUPS_PATH, id, CONFIRM_PATH, payment_method_name), sdk_authorization diff --git a/spec/checkout_sdk/checkout_utils_spec.rb b/spec/checkout_sdk/checkout_utils_spec.rb index ba32655..6119e24 100644 --- a/spec/checkout_sdk/checkout_utils_spec.rb +++ b/spec/checkout_sdk/checkout_utils_spec.rb @@ -3,6 +3,52 @@ RSpec.describe CheckoutSdk::CheckoutUtils do let(:backslash) { '\\' } + describe '.encode_path_segment' do + it 'keeps unreserved characters unchanged' do + value = 'AZaz09-._~' + expect(described_class.encode_path_segment(value)).to eq(value) + end + + it 'percent-encodes reserved characters with upper-case hex' do + expect(described_class.encode_path_segment('a/b?c#d%e f;g:h@i&j=k+l')) + .to eq('a%2Fb%3Fc%23d%25e%20f%3Bg%3Ah%40i%26j%3Dk%2Bl') + end + + it 'percent-encodes non-ASCII text as UTF-8 bytes' do + expect(described_class.encode_path_segment('é€')).to eq('%C3%A9%E2%82%AC') + end + + it 'percent-encodes text in another encoding as UTF-8 bytes' do + expect(described_class.encode_path_segment('é'.encode(Encoding::ISO_8859_1))).to eq('%C3%A9') + end + + it 'percent-encodes control characters' do + expect(described_class.encode_path_segment("a\r\nb\u0000")).to eq('a%0D%0Ab%00') + end + + it 'keeps dots that are not a whole segment' do + expect(described_class.encode_path_segment('...')).to eq('...') + expect(described_class.encode_path_segment('a..b')).to eq('a..b') + end + + it 'converts Integer and Symbol values' do + expect(described_class.encode_path_segment(42)).to eq('42') + expect(described_class.encode_path_segment(:files)).to eq('files') + end + + it 'returns a UTF-8 string' do + expect(described_class.encode_path_segment('é').encoding).to eq(Encoding::UTF_8) + end + + [nil, '', '.', '..', :'..'].each do |value| + it "raises CheckoutArgumentException for #{value.inspect}" do + expect { described_class.encode_path_segment(value) } + .to raise_error(CheckoutSdk::CheckoutArgumentException, + "Invalid path segment: it must not be nil, empty, '.' or '..'") + end + end + end + describe '.loggable_path' do it 'keeps a plain path unchanged' do expect(described_class.loggable_path('payments/pay_123/captures')).to eq('payments/pay_123/captures') diff --git a/spec/checkout_sdk/client_spec.rb b/spec/checkout_sdk/client_spec.rb new file mode 100644 index 0000000..c9bc9a2 --- /dev/null +++ b/spec/checkout_sdk/client_spec.rb @@ -0,0 +1,97 @@ +# frozen_string_literal: true + +RSpec.describe CheckoutSdk::Client do + let(:configuration) { double('configuration') } + let(:client) { CheckoutSdk::Client.send(:new, double('api_client'), configuration, 'SECRET_KEY') } + + def build_path(*args) + client.send(:build_path, *args) + end + + describe '#build_path' do + it 'joins plain segments with a slash' do + expect(build_path('payments', 'pay_123', 'captures')).to eq('payments/pay_123/captures') + end + + it 'keeps every argument as a single segment' do + expect(build_path('payments', '../x')).to eq('payments/..%2Fx') + expect(build_path('payments', '../../../x/y')).to eq('payments/..%2F..%2F..%2Fx%2Fy') + end + + it 'encodes query and fragment delimiters' do + expect(build_path('payments', 'a?b#c')).to eq('payments/a%3Fb%23c') + end + + it 'accepts Integer and Symbol segments' do + expect(build_path('reports', 123, :files)).to eq('reports/123/files') + end + + [nil, '', '.', '..'].each do |value| + it "raises CheckoutArgumentException for #{value.inspect}" do + expect { build_path('payments', value) }.to raise_error(CheckoutSdk::CheckoutArgumentException) + end + end + end + + describe 'request path on the wire' do + let(:requests) { [] } + let(:api) do + stubs = Faraday::Adapter::Test::Stubs.new do |stub| + %i[get post].each do |verb| + stub.send(verb, /.*/) do |env| + requests << env.url + [200, { 'Content-Type' => 'application/json' }, '{}'] + end + end + end + http_client = Faraday.new { |f| f.adapter :test, stubs } + CheckoutSdk.builder.static_keys + .with_secret_key('sk_sbox_m73dzbpy7cf3gfd46xr4yj5xo4e') + .with_environment(CheckoutSdk::Environment.sandbox) + .with_environment_subdomain('abc123') + .with_http_client(http_client) + .with_multipart_http_client(http_client) + .with_logger(Logger.new(StringIO.new)) + .build + end + + it 'keeps an identifier inside its own segment' do + api.payments_setups.confirm_payment_setup('../../x', 'klarna') + expect(requests.map(&:path)).to eq(['/payments/setups/..%2F..%2Fx/confirm/klarna']) + end + + it 'sends no query or fragment taken from an identifier' do + api.payments.get_payment_details('a?b#c') + url = requests.first + expect(url.path).to eq('/payments/a%3Fb%23c') + expect(url.query).to be_nil + expect(url.fragment).to be_nil + end + + it 'raises before any request for an invalid payment method name' do + expect { api.payments_setups.confirm_payment_setup('ps_x', '../../x/y') } + .to raise_error(CheckoutSdk::CheckoutArgumentException) + expect(requests).to be_empty + end + + it 'raises before any request for an empty identifier' do + expect { api.payments.get_payment_details('') }.to raise_error(CheckoutSdk::CheckoutArgumentException) + expect(requests).to be_empty + end + end + + describe 'paths built from several constant segments' do + let(:api_client) { double('api_client') } + let(:credentials) { double('credentials', get_authorization: 'auth') } + + before { allow(configuration).to receive(:credentials).and_return(credentials) } + + it 'keeps the bank account field formatting path' do + instruments = CheckoutSdk::Instruments::InstrumentsClient.new(api_client, configuration) + query = double('query') + expect(api_client).to receive(:invoke_get) + .with('validation/bank-accounts/GB/GBP', 'auth', query).and_return('response') + expect(instruments.get_bank_account_field_formatting('GB', 'GBP', query)).to eq('response') + end + end +end diff --git a/spec/checkout_sdk/payments/setups/payment_setups_client_spec.rb b/spec/checkout_sdk/payments/setups/payment_setups_client_spec.rb index ac78ee7..ddff19c 100644 --- a/spec/checkout_sdk/payments/setups/payment_setups_client_spec.rb +++ b/spec/checkout_sdk/payments/setups/payment_setups_client_spec.rb @@ -67,6 +67,27 @@ .with('payments/setups/ps_1/confirm/cashapp', 'secret_key').and_return('response') expect(client.confirm_payment_setup('ps_1', 'cashapp')).to eq('response') end + + it 'accepts names with underscores and digits, any case, or a Symbol' do + { 'alipay_cn' => 'alipay_cn', 'p24' => 'p24', 'Card' => 'Card', klarna: 'klarna' }.each do |name, segment| + expect(api_client_mock).to receive(:invoke_post) + .with("payments/setups/ps_1/confirm/#{segment}", 'secret_key').and_return('response') + expect(client.confirm_payment_setup('ps_1', name)).to eq('response') + end + end + + [nil, '', 'a/b', '../x', 'a?b', 'a#b', 'a b', 'a.b', 'a-b'].each do |name| + it "raises CheckoutArgumentException for #{name.inspect} without sending a request" do + expect(api_client_mock).not_to receive(:invoke_post) + expect { client.confirm_payment_setup('ps_1', name) } + .to raise_error(CheckoutSdk::CheckoutArgumentException, 'Invalid payment method name') + end + end + + it 'raises CheckoutArgumentException for an empty id without sending a request' do + expect(api_client_mock).not_to receive(:invoke_post) + expect { client.confirm_payment_setup('', 'klarna') }.to raise_error(CheckoutSdk::CheckoutArgumentException) + end end describe '#create_payment_setup with billing_descriptor, presentment_details and terminal' do From 1bbc88d2e2063260c874ea96acfce35912eece47 Mon Sep 17 00:00:00 2001 From: david ruiz Date: Thu, 5 Nov 2026 11:24:46 +0100 Subject: [PATCH 2/5] encode_path_segment upgrade + tests --- README.md | 4 ++ lib/checkout_sdk/checkout_utils.rb | 25 +++++++---- lib/checkout_sdk/client.rb | 3 +- .../payments/setups/payment_setups_client.rb | 2 +- spec/checkout_sdk/checkout_utils_spec.rb | 31 +++++++++----- spec/checkout_sdk/client_spec.rb | 42 +++++++++++++++---- 6 files changed, 78 insertions(+), 29 deletions(-) diff --git a/README.md b/README.md index 9c8a71e..597169b 100644 --- a/README.md +++ b/README.md @@ -151,6 +151,10 @@ All the API responses that do not fall in the 2** status codes will cause a `Che exception encapsulates the `http_metadata` and a map of `error_details`, if available. +Identifiers passed to client methods (for example a payment id) are sent as single, percent-encoded path +segments: pass them unencoded. A `CheckoutSdk::CheckoutArgumentException` is raised before any request is sent +when an identifier is `nil`, empty, `.` or `..`, or contains `/`, `\` or a control character. + ## Custom Http Client Ruby SDK supports your own configuration for `http client` using `Faraday::Connection` object, you can pass diff --git a/lib/checkout_sdk/checkout_utils.rb b/lib/checkout_sdk/checkout_utils.rb index b45519d..12446a9 100644 --- a/lib/checkout_sdk/checkout_utils.rb +++ b/lib/checkout_sdk/checkout_utils.rb @@ -53,23 +53,32 @@ def self.error_message(prefix, body, include_text_body: false) end INVALID_PATH_SEGMENTS = ['', '.', '..'].freeze - private_constant :INVALID_PATH_SEGMENTS + FORBIDDEN_PATH_SEGMENT_BYTES = %r{[/\\\x00-\x1F\x7F]}n.freeze + INVALID_PATH_SEGMENT_MESSAGE = "Invalid path segment: it must not be nil, empty, '.' or '..', " \ + "and must not contain '/', '\\' or control characters" + private_constant :INVALID_PATH_SEGMENTS, :FORBIDDEN_PATH_SEGMENT_BYTES, :INVALID_PATH_SEGMENT_MESSAGE # Encodes a value as one RFC 3986 path segment. Every byte of its UTF-8 form outside the # unreserved set (A-Z, a-z, 0-9, "-", ".", "_", "~") is percent-encoded, so the value always - # stays a single segment of the request path. + # stays a single segment of the request path. Values are validated after conversion to UTF-8, + # whatever their original encoding. # # @param [String, Symbol, Integer] value # @return [String] - # @raise [CheckoutArgumentException] when the value is nil, empty, "." or ".." + # @raise [CheckoutArgumentException] when the value is nil, empty, "." or "..", contains "/", + # "\" or a control character, or its to_s does not return a String def self.encode_path_segment(value) text = value.nil? ? '' : value.to_s - if INVALID_PATH_SEGMENTS.include?(text) - raise CheckoutArgumentException, "Invalid path segment: it must not be nil, empty, '.' or '..'" - end + raise CheckoutArgumentException, INVALID_PATH_SEGMENT_MESSAGE unless text.is_a?(String) + + bytes = utf8_bytes(text) + raise CheckoutArgumentException, INVALID_PATH_SEGMENT_MESSAGE if FORBIDDEN_PATH_SEGMENT_BYTES.match?(bytes) + + encoded = bytes.gsub(/[^A-Za-z0-9\-._~]/n) { |byte| format('%%%02X', byte.ord) } + .force_encoding(Encoding::UTF_8) + raise CheckoutArgumentException, INVALID_PATH_SEGMENT_MESSAGE if INVALID_PATH_SEGMENTS.include?(encoded) - utf8_bytes(text).gsub(/[^A-Za-z0-9\-._~]/n) { |byte| format('%%%02X', byte.ord) } - .force_encoding(Encoding::UTF_8) + encoded end def self.utf8_bytes(text) diff --git a/lib/checkout_sdk/client.rb b/lib/checkout_sdk/client.rb index def837b..a82cddc 100644 --- a/lib/checkout_sdk/client.rb +++ b/lib/checkout_sdk/client.rb @@ -28,7 +28,8 @@ def initialize(api_client, configuration, authorization_type) # # @param [Array] args # @return [String] - # @raise [CheckoutArgumentException] when an argument is nil, empty, "." or ".." + # @raise [CheckoutArgumentException] when an argument is nil, empty, "." or "..", or contains "/", + # "\" or a control character def build_path(*args) args.map { |segment| CheckoutUtils.encode_path_segment(segment) }.join('/') end diff --git a/lib/checkout_sdk/payments/setups/payment_setups_client.rb b/lib/checkout_sdk/payments/setups/payment_setups_client.rb index 223c860..9e7f3a1 100644 --- a/lib/checkout_sdk/payments/setups/payment_setups_client.rb +++ b/lib/checkout_sdk/payments/setups/payment_setups_client.rb @@ -251,7 +251,7 @@ def get_payment_setup(id) # details :last4, :bin, :scheme (Strings) and :expires_on (date-time); instrument returns the # read-only :type (String) and :action (:type, "set_instrument"). # @raise [CheckoutArgumentException] when payment_method_name is not a payment method name - # (letters, digits and underscores), or id is nil or empty + # (letters, digits and underscores), or id is not a valid path segment (see Client#build_path) def confirm_payment_setup(id, payment_method_name) unless PAYMENT_METHOD_NAME_PATTERN.match?(payment_method_name.to_s) raise CheckoutArgumentException, 'Invalid payment method name' diff --git a/spec/checkout_sdk/checkout_utils_spec.rb b/spec/checkout_sdk/checkout_utils_spec.rb index 6119e24..885189a 100644 --- a/spec/checkout_sdk/checkout_utils_spec.rb +++ b/spec/checkout_sdk/checkout_utils_spec.rb @@ -10,8 +10,8 @@ end it 'percent-encodes reserved characters with upper-case hex' do - expect(described_class.encode_path_segment('a/b?c#d%e f;g:h@i&j=k+l')) - .to eq('a%2Fb%3Fc%23d%25e%20f%3Bg%3Ah%40i%26j%3Dk%2Bl') + expect(described_class.encode_path_segment('a?b#c%d e;f:g@h&i=j+k')) + .to eq('a%3Fb%23c%25d%20e%3Bf%3Ag%40h%26i%3Dj%2Bk') end it 'percent-encodes non-ASCII text as UTF-8 bytes' do @@ -22,10 +22,6 @@ expect(described_class.encode_path_segment('é'.encode(Encoding::ISO_8859_1))).to eq('%C3%A9') end - it 'percent-encodes control characters' do - expect(described_class.encode_path_segment("a\r\nb\u0000")).to eq('a%0D%0Ab%00') - end - it 'keeps dots that are not a whole segment' do expect(described_class.encode_path_segment('...')).to eq('...') expect(described_class.encode_path_segment('a..b')).to eq('a..b') @@ -40,12 +36,27 @@ expect(described_class.encode_path_segment('é').encoding).to eq(Encoding::UTF_8) end - [nil, '', '.', '..', :'..'].each do |value| - it "raises CheckoutArgumentException for #{value.inspect}" do + it 'validates text in an encoding that is not ASCII compatible after converting it' do + expect(described_class.encode_path_segment('ab'.encode(Encoding::UTF_16LE))).to eq('ab') + end + + invalid_values = [nil, '', '.', '..', :'..', 'a/b', 'a\\b', "a\nb", "a\rb", "a\u0000b", "a\u007Fb", + '..'.encode(Encoding::UTF_16LE), '.'.encode(Encoding::UTF_32LE), + '..'.dup.force_encoding(Encoding::UTF_7), 'a/b'.encode(Encoding::UTF_16BE)] + invalid_values.each do |value| + it "raises CheckoutArgumentException for #{value.inspect} (#{value.is_a?(String) ? value.encoding : value.class})" do expect { described_class.encode_path_segment(value) } - .to raise_error(CheckoutSdk::CheckoutArgumentException, - "Invalid path segment: it must not be nil, empty, '.' or '..'") + .to raise_error(CheckoutSdk::CheckoutArgumentException, /\AInvalid path segment/) + end + end + + it 'raises CheckoutArgumentException when to_s does not return a String' do + value = Object.new + def value.to_s + 42 end + expect { described_class.encode_path_segment(value) } + .to raise_error(CheckoutSdk::CheckoutArgumentException, /\AInvalid path segment/) end end diff --git a/spec/checkout_sdk/client_spec.rb b/spec/checkout_sdk/client_spec.rb index c9bc9a2..fd7550f 100644 --- a/spec/checkout_sdk/client_spec.rb +++ b/spec/checkout_sdk/client_spec.rb @@ -14,8 +14,7 @@ def build_path(*args) end it 'keeps every argument as a single segment' do - expect(build_path('payments', '../x')).to eq('payments/..%2Fx') - expect(build_path('payments', '../../../x/y')).to eq('payments/..%2F..%2F..%2Fx%2Fy') + expect(build_path('payments', 'a b%c')).to eq('payments/a%20b%25c') end it 'encodes query and fragment delimiters' do @@ -26,8 +25,8 @@ def build_path(*args) expect(build_path('reports', 123, :files)).to eq('reports/123/files') end - [nil, '', '.', '..'].each do |value| - it "raises CheckoutArgumentException for #{value.inspect}" do + [nil, '', '.', '..', '../x', 'a/b', 'a\\b', '..'.encode(Encoding::UTF_16LE)].each do |value| + it "raises CheckoutArgumentException for #{value.inspect} (#{value.is_a?(String) ? value.encoding : value.class})" do expect { build_path('payments', value) }.to raise_error(CheckoutSdk::CheckoutArgumentException) end end @@ -56,8 +55,8 @@ def build_path(*args) end it 'keeps an identifier inside its own segment' do - api.payments_setups.confirm_payment_setup('../../x', 'klarna') - expect(requests.map(&:path)).to eq(['/payments/setups/..%2F..%2Fx/confirm/klarna']) + api.payments_setups.confirm_payment_setup('ps 1%', 'klarna') + expect(requests.map(&:path)).to eq(['/payments/setups/ps%201%25/confirm/klarna']) end it 'sends no query or fragment taken from an identifier' do @@ -74,9 +73,13 @@ def build_path(*args) expect(requests).to be_empty end - it 'raises before any request for an empty identifier' do - expect { api.payments.get_payment_details('') }.to raise_error(CheckoutSdk::CheckoutArgumentException) - expect(requests).to be_empty + ['', '../x', '..'.encode(Encoding::UTF_16LE)].each do |value| + it "raises before any request for the identifier #{value.inspect} (#{value.encoding})" do + expect { api.payments.get_payment_details(value) }.to raise_error(CheckoutSdk::CheckoutArgumentException) + expect { api.payments_setups.confirm_payment_setup(value, 'klarna') } + .to raise_error(CheckoutSdk::CheckoutArgumentException) + expect(requests).to be_empty + end end end @@ -93,5 +96,26 @@ def build_path(*args) .with('validation/bank-accounts/GB/GBP', 'auth', query).and_return('response') expect(instruments.get_bank_account_field_formatting('GB', 'GBP', query)).to eq('response') end + + it 'keeps the Bacs notification path' do + bacs = CheckoutSdk::Apm::BacsClient.new(api_client, configuration) + request = double('request') + expect(api_client).to receive(:invoke_post) + .with('apms/bacs/notifications', 'auth', request).and_return('response') + expect(bacs.send_notification(request)).to eq('response') + end + + it 'keeps the SEPA mandate paths' do + sepa = CheckoutSdk::Previous::Apm::SepaClient.new(api_client, configuration) + expect(api_client).to receive(:invoke_get).with('sepa/mandates/src_1', 'auth').and_return('get') + expect(api_client).to receive(:invoke_post).with('sepa/mandates/src_1/cancel', 'auth').and_return('cancel') + expect(api_client).to receive(:invoke_get).with('apms/ppro/sepa/mandates/src_1', 'auth').and_return('ppro_get') + expect(api_client).to receive(:invoke_post) + .with('apms/ppro/sepa/mandates/src_1/cancel', 'auth').and_return('ppro_cancel') + expect(sepa.get_mandate('src_1')).to eq('get') + expect(sepa.cancel_mandate('src_1')).to eq('cancel') + expect(sepa.get_mandate_via_ppro('src_1')).to eq('ppro_get') + expect(sepa.cancel_mandate_via_ppro('src_1')).to eq('ppro_cancel') + end end end From 3e60a72b20d3adf7a5afe5a9beacb05dfdd47656 Mon Sep 17 00:00:00 2001 From: david ruiz Date: Thu, 5 Nov 2026 15:13:53 +0100 Subject: [PATCH 3/5] PR review fine tunning --- README.md | 3 +- lib/checkout_sdk/balances/balances_client.rb | 5 +-- lib/checkout_sdk/checkout_utils.rb | 44 +++++++++++-------- lib/checkout_sdk/client.rb | 4 +- .../payments/setups/payment_setups_client.rb | 10 +---- lib/checkout_sdk/risk/risk_client.rb | 14 +++--- spec/checkout_sdk/checkout_utils_spec.rb | 19 +++++++- spec/checkout_sdk/client_spec.rb | 23 ++++++++-- .../setups/payment_setups_client_spec.rb | 11 ++--- 9 files changed, 86 insertions(+), 47 deletions(-) diff --git a/README.md b/README.md index 597169b..b1f216c 100644 --- a/README.md +++ b/README.md @@ -153,7 +153,8 @@ encapsulates the `http_metadata` and a map of `error_details`, if available. Identifiers passed to client methods (for example a payment id) are sent as single, percent-encoded path segments: pass them unencoded. A `CheckoutSdk::CheckoutArgumentException` is raised before any request is sent -when an identifier is `nil`, empty, `.` or `..`, or contains `/`, `\` or a control character. +when an identifier is `nil`, empty, `.` or `..`, cannot be converted to valid UTF-8, or contains `/`, `\` or an +ASCII control character (U+0000 to U+001F, U+007F). ## Custom Http Client diff --git a/lib/checkout_sdk/balances/balances_client.rb b/lib/checkout_sdk/balances/balances_client.rb index b1f86cc..c873841 100644 --- a/lib/checkout_sdk/balances/balances_client.rb +++ b/lib/checkout_sdk/balances/balances_client.rb @@ -39,9 +39,8 @@ def retrieve_entity_balances(entity_id, balances_query) # @param [String] currency_account_id the ID of the sub-account to retrieve top-up # instructions for # @return [Hash] the top-up instructions response - # @raise [CheckoutArgumentException] if either path parameter is nil, empty or blank. Both - # segments are interpolated straight into the request path, so a blank value would build a - # malformed URL and be rejected by the API rather than by the SDK. + # @raise [CheckoutArgumentException] if either path parameter is nil, empty or blank, or is not + # a valid path segment (see Client#build_path). def retrieve_top_up_instructions(entity_id, currency_account_id) raise CheckoutArgumentException, 'entity_id cannot be blank' if entity_id.to_s.strip.empty? raise CheckoutArgumentException, 'currency_account_id cannot be blank' if currency_account_id.to_s.strip.empty? diff --git a/lib/checkout_sdk/checkout_utils.rb b/lib/checkout_sdk/checkout_utils.rb index 12446a9..693a21f 100644 --- a/lib/checkout_sdk/checkout_utils.rb +++ b/lib/checkout_sdk/checkout_utils.rb @@ -54,25 +54,27 @@ def self.error_message(prefix, body, include_text_body: false) INVALID_PATH_SEGMENTS = ['', '.', '..'].freeze FORBIDDEN_PATH_SEGMENT_BYTES = %r{[/\\\x00-\x1F\x7F]}n.freeze - INVALID_PATH_SEGMENT_MESSAGE = "Invalid path segment: it must not be nil, empty, '.' or '..', " \ - "and must not contain '/', '\\' or control characters" + INVALID_PATH_SEGMENT_MESSAGE = "Invalid path segment: it must be valid text, not nil, empty, '.' or '..', " \ + "and must not contain '/', '\\' or ASCII control characters" private_constant :INVALID_PATH_SEGMENTS, :FORBIDDEN_PATH_SEGMENT_BYTES, :INVALID_PATH_SEGMENT_MESSAGE - # Encodes a value as one RFC 3986 path segment. Every byte of its UTF-8 form outside the - # unreserved set (A-Z, a-z, 0-9, "-", ".", "_", "~") is percent-encoded, so the value always - # stays a single segment of the request path. Values are validated after conversion to UTF-8, - # whatever their original encoding. + # Encodes a value as one RFC 3986 path segment. The value is converted to UTF-8 and every byte + # outside the unreserved set (A-Z, a-z, 0-9, "-", ".", "_", "~") is percent-encoded, so the value + # always stays a single segment of the request path. The checks run on the converted text. # # @param [String, Symbol, Integer] value # @return [String] - # @raise [CheckoutArgumentException] when the value is nil, empty, "." or "..", contains "/", - # "\" or a control character, or its to_s does not return a String + # @raise [CheckoutArgumentException] when the value is nil, empty, "." or "..", cannot be converted + # to valid UTF-8, contains "/", "\" or an ASCII control character (U+0000 to U+001F, U+007F), or + # its to_s does not return a String def self.encode_path_segment(value) text = value.nil? ? '' : value.to_s raise CheckoutArgumentException, INVALID_PATH_SEGMENT_MESSAGE unless text.is_a?(String) - bytes = utf8_bytes(text) - raise CheckoutArgumentException, INVALID_PATH_SEGMENT_MESSAGE if FORBIDDEN_PATH_SEGMENT_BYTES.match?(bytes) + bytes = to_valid_utf8(text)&.b + if bytes.nil? || FORBIDDEN_PATH_SEGMENT_BYTES.match?(bytes) + raise CheckoutArgumentException, INVALID_PATH_SEGMENT_MESSAGE + end encoded = bytes.gsub(/[^A-Za-z0-9\-._~]/n) { |byte| format('%%%02X', byte.ord) } .force_encoding(Encoding::UTF_8) @@ -81,13 +83,6 @@ def self.encode_path_segment(value) encoded end - def self.utf8_bytes(text) - text.encode(Encoding::UTF_8).b - rescue EncodingError - text.b - end - private_class_method :utf8_bytes - # Returns a copy of the Faraday error, of the same class and with the same backtrace and wrapped # exception, that keeps only the response status, headers and body and whose message names the # method and URL without the query string. Errors without a response are returned unchanged. @@ -127,8 +122,21 @@ def self.escape_control_characters(text) end private_class_method :escape_control_characters + # Converts text to UTF-8, transcoding from its own encoding. Returns nil when the text cannot be + # converted or the result is not valid UTF-8. + def self.to_valid_utf8(text) + converted = text.encode(Encoding::UTF_8) + converted.valid_encoding? ? converted : nil + rescue EncodingError + nil + end + private_class_method :to_valid_utf8 + + # Lenient form of to_valid_utf8 for log and message text: bytes that cannot be converted are read + # as UTF-8 and invalid sequences are replaced. def self.utf8_text(text) - text.to_s.dup.force_encoding(Encoding::UTF_8).scrub + text = text.to_s + (to_valid_utf8(text) || text.dup.force_encoding(Encoding::UTF_8)).scrub end private_class_method :utf8_text diff --git a/lib/checkout_sdk/client.rb b/lib/checkout_sdk/client.rb index a82cddc..cfdb729 100644 --- a/lib/checkout_sdk/client.rb +++ b/lib/checkout_sdk/client.rb @@ -28,8 +28,8 @@ def initialize(api_client, configuration, authorization_type) # # @param [Array] args # @return [String] - # @raise [CheckoutArgumentException] when an argument is nil, empty, "." or "..", or contains "/", - # "\" or a control character + # @raise [CheckoutArgumentException] when an argument is not a valid path segment (see + # CheckoutUtils.encode_path_segment) def build_path(*args) args.map { |segment| CheckoutUtils.encode_path_segment(segment) }.join('/') end diff --git a/lib/checkout_sdk/payments/setups/payment_setups_client.rb b/lib/checkout_sdk/payments/setups/payment_setups_client.rb index 9e7f3a1..dc286d7 100644 --- a/lib/checkout_sdk/payments/setups/payment_setups_client.rb +++ b/lib/checkout_sdk/payments/setups/payment_setups_client.rb @@ -8,8 +8,6 @@ class PaymentSetupsClient < Client PAYMENTS_PATH = 'payments' SETUPS_PATH = 'setups' CONFIRM_PATH = 'confirm' - PAYMENT_METHOD_NAME_PATTERN = /\A[a-z0-9_]+\z/i.freeze - private_constant :PAYMENT_METHOD_NAME_PATTERN # @param [ApiClient] api_client # @param [CheckoutConfiguration] configuration @@ -250,13 +248,9 @@ def get_payment_setup(id) # :schemes (supported card scheme names; Google Pay never lists cartes_bancaires) and card # details :last4, :bin, :scheme (Strings) and :expires_on (date-time); instrument returns the # read-only :type (String) and :action (:type, "set_instrument"). - # @raise [CheckoutArgumentException] when payment_method_name is not a payment method name - # (letters, digits and underscores), or id is not a valid path segment (see Client#build_path) + # @raise [CheckoutArgumentException] when id or payment_method_name is not a valid path segment + # (see Client#build_path) def confirm_payment_setup(id, payment_method_name) - unless PAYMENT_METHOD_NAME_PATTERN.match?(payment_method_name.to_s) - raise CheckoutArgumentException, 'Invalid payment method name' - end - api_client.invoke_post( build_path(PAYMENTS_PATH, SETUPS_PATH, id, CONFIRM_PATH, payment_method_name), sdk_authorization diff --git a/lib/checkout_sdk/risk/risk_client.rb b/lib/checkout_sdk/risk/risk_client.rb index 4cdd634..3ed8839 100644 --- a/lib/checkout_sdk/risk/risk_client.rb +++ b/lib/checkout_sdk/risk/risk_client.rb @@ -5,9 +5,11 @@ module Risk # @deprecated Risk endpoints are no longer supported officially, This module will be removed in a # future release. class RiskClient < Client - PRE_AUTHENTICATION = 'risk/assessments/pre-authentication' - PRE_CAPTURE = 'risk/assessments/pre-capture' - private_constant :PRE_AUTHENTICATION, :PRE_CAPTURE + RISK = 'risk' + ASSESSMENTS = 'assessments' + PRE_AUTHENTICATION = 'pre-authentication' + PRE_CAPTURE = 'pre-capture' + private_constant :RISK, :ASSESSMENTS, :PRE_AUTHENTICATION, :PRE_CAPTURE # @param [ApiClient] api_client # @param [CheckoutConfiguration] configuration @@ -17,12 +19,14 @@ def initialize(api_client, configuration) # @param [Hash, PreAuthenticationAssessment] pre_authentication_request def pre_authentication_scan(pre_authentication_request) - api_client.invoke_post(PRE_AUTHENTICATION, sdk_authorization, pre_authentication_request) + api_client.invoke_post(build_path(RISK, ASSESSMENTS, PRE_AUTHENTICATION), + sdk_authorization, + pre_authentication_request) end # @param [Hash, PreCaptureAssessment] pre_capture_request def pre_capture_scan(pre_capture_request) - api_client.invoke_post(PRE_CAPTURE, sdk_authorization, pre_capture_request) + api_client.invoke_post(build_path(RISK, ASSESSMENTS, PRE_CAPTURE), sdk_authorization, pre_capture_request) end end end diff --git a/spec/checkout_sdk/checkout_utils_spec.rb b/spec/checkout_sdk/checkout_utils_spec.rb index 885189a..2e36610 100644 --- a/spec/checkout_sdk/checkout_utils_spec.rb +++ b/spec/checkout_sdk/checkout_utils_spec.rb @@ -40,11 +40,21 @@ expect(described_class.encode_path_segment('ab'.encode(Encoding::UTF_16LE))).to eq('ab') end + it 'accepts binary text that holds only ASCII characters' do + expect(described_class.encode_path_segment('pay_1'.b)).to eq('pay_1') + end + + it 'percent-encodes control characters outside ASCII' do + expect(described_class.encode_path_segment("a\u0085b")).to eq('a%C2%85b') + end + invalid_values = [nil, '', '.', '..', :'..', 'a/b', 'a\\b', "a\nb", "a\rb", "a\u0000b", "a\u007Fb", '..'.encode(Encoding::UTF_16LE), '.'.encode(Encoding::UTF_32LE), - '..'.dup.force_encoding(Encoding::UTF_7), 'a/b'.encode(Encoding::UTF_16BE)] + '..'.dup.force_encoding(Encoding::UTF_7), 'a/b'.encode(Encoding::UTF_16BE), + "a\xFFb".dup.force_encoding(Encoding::UTF_8), "\xC3\xA9".b] invalid_values.each do |value| - it "raises CheckoutArgumentException for #{value.inspect} (#{value.is_a?(String) ? value.encoding : value.class})" do + label = value.is_a?(String) ? value.encoding : value.class + it "raises CheckoutArgumentException for #{value.inspect} (#{label})" do expect { described_class.encode_path_segment(value) } .to raise_error(CheckoutSdk::CheckoutArgumentException, /\AInvalid path segment/) end @@ -83,6 +93,11 @@ def value.to_s expect(described_class.loggable_path("payments/\xFF\n".b)).to eq("payments/\u{FFFD}#{backslash}n") expect(described_class.loggable_path(nil)).to eq('') end + + it 'converts text in another encoding to UTF-8' do + expect(described_class.loggable_path("payments/\u00E9\n".encode(Encoding::UTF_16LE))) + .to eq("payments/\u00E9#{backslash}n") + end end describe '.error_message' do diff --git a/spec/checkout_sdk/client_spec.rb b/spec/checkout_sdk/client_spec.rb index fd7550f..71c5f97 100644 --- a/spec/checkout_sdk/client_spec.rb +++ b/spec/checkout_sdk/client_spec.rb @@ -26,7 +26,8 @@ def build_path(*args) end [nil, '', '.', '..', '../x', 'a/b', 'a\\b', '..'.encode(Encoding::UTF_16LE)].each do |value| - it "raises CheckoutArgumentException for #{value.inspect} (#{value.is_a?(String) ? value.encoding : value.class})" do + label = value.is_a?(String) ? value.encoding : value.class + it "raises CheckoutArgumentException for #{value.inspect} (#{label})" do expect { build_path('payments', value) }.to raise_error(CheckoutSdk::CheckoutArgumentException) end end @@ -67,12 +68,17 @@ def build_path(*args) expect(url.fragment).to be_nil end - it 'raises before any request for an invalid payment method name' do + it 'raises before any request for a payment method name that is not a single segment' do expect { api.payments_setups.confirm_payment_setup('ps_x', '../../x/y') } - .to raise_error(CheckoutSdk::CheckoutArgumentException) + .to raise_error(CheckoutSdk::CheckoutArgumentException, /\AInvalid path segment/) expect(requests).to be_empty end + it 'sends a payment method name with unreserved punctuation unchanged' do + api.payments_setups.confirm_payment_setup('ps_1', 'pay-by.bank') + expect(requests.map(&:path)).to eq(['/payments/setups/ps_1/confirm/pay-by.bank']) + end + ['', '../x', '..'.encode(Encoding::UTF_16LE)].each do |value| it "raises before any request for the identifier #{value.inspect} (#{value.encoding})" do expect { api.payments.get_payment_details(value) }.to raise_error(CheckoutSdk::CheckoutArgumentException) @@ -105,6 +111,17 @@ def build_path(*args) expect(bacs.send_notification(request)).to eq('response') end + it 'keeps the risk assessment paths' do + risk = CheckoutSdk::Risk::RiskClient.new(api_client, configuration) + request = double('request') + expect(api_client).to receive(:invoke_post) + .with('risk/assessments/pre-authentication', 'auth', request).and_return('pre_authentication') + expect(api_client).to receive(:invoke_post) + .with('risk/assessments/pre-capture', 'auth', request).and_return('pre_capture') + expect(risk.pre_authentication_scan(request)).to eq('pre_authentication') + expect(risk.pre_capture_scan(request)).to eq('pre_capture') + end + it 'keeps the SEPA mandate paths' do sepa = CheckoutSdk::Previous::Apm::SepaClient.new(api_client, configuration) expect(api_client).to receive(:invoke_get).with('sepa/mandates/src_1', 'auth').and_return('get') diff --git a/spec/checkout_sdk/payments/setups/payment_setups_client_spec.rb b/spec/checkout_sdk/payments/setups/payment_setups_client_spec.rb index ddff19c..b6caa22 100644 --- a/spec/checkout_sdk/payments/setups/payment_setups_client_spec.rb +++ b/spec/checkout_sdk/payments/setups/payment_setups_client_spec.rb @@ -68,19 +68,20 @@ expect(client.confirm_payment_setup('ps_1', 'cashapp')).to eq('response') end - it 'accepts names with underscores and digits, any case, or a Symbol' do - { 'alipay_cn' => 'alipay_cn', 'p24' => 'p24', 'Card' => 'Card', klarna: 'klarna' }.each do |name, segment| + it 'sends any payment method name as one segment, unchanged when it holds only unreserved characters' do + { 'alipay_cn' => 'alipay_cn', 'p24' => 'p24', 'Card' => 'Card', klarna: 'klarna', + 'a-b' => 'a-b', 'a.b' => 'a.b', 'a~b' => 'a~b', 'a?b' => 'a%3Fb', 'a b' => 'a%20b' }.each do |name, segment| expect(api_client_mock).to receive(:invoke_post) .with("payments/setups/ps_1/confirm/#{segment}", 'secret_key').and_return('response') expect(client.confirm_payment_setup('ps_1', name)).to eq('response') end end - [nil, '', 'a/b', '../x', 'a?b', 'a#b', 'a b', 'a.b', 'a-b'].each do |name| - it "raises CheckoutArgumentException for #{name.inspect} without sending a request" do + [nil, '', '.', '..', 'a/b', '../x'].each do |name| + it "raises CheckoutArgumentException for the payment method name #{name.inspect} without sending a request" do expect(api_client_mock).not_to receive(:invoke_post) expect { client.confirm_payment_setup('ps_1', name) } - .to raise_error(CheckoutSdk::CheckoutArgumentException, 'Invalid payment method name') + .to raise_error(CheckoutSdk::CheckoutArgumentException, /\AInvalid path segment/) end end From 830926a2038cea95d0d8f7cbcf958c1272fd2e38 Mon Sep 17 00:00:00 2001 From: margarita-zabelina-cko <167215385+margarita-zabelina-cko@users.noreply.github.com> Date: Thu, 5 Nov 2026 18:23:08 +0000 Subject: [PATCH 4/5] Safe change to trigger GHA From f69c8dcdd7ea6beb56b8b3cc70fbdf188c5e63fc Mon Sep 17 00:00:00 2001 From: margarita-zabelina-cko <167215385+margarita-zabelina-cko@users.noreply.github.com> Date: Fri, 6 Nov 2026 13:48:55 +0000 Subject: [PATCH 5/5] Safe change to trigger GHA