Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,11 @@ 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 `..`, cannot be converted to valid UTF-8, or contains `/`, `\` or an
ASCII control character (U+0000 to U+001F, U+007F).

## Custom Http Client

Ruby SDK supports your own configuration for `http client` using `Faraday::Connection` object, you can pass
Expand Down
7 changes: 4 additions & 3 deletions lib/checkout_sdk/apm/bacs/bacs_client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
13 changes: 7 additions & 6 deletions lib/checkout_sdk/apm/previous/sepa/sepa_client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
5 changes: 2 additions & 3 deletions lib/checkout_sdk/balances/balances_client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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?
Expand Down
46 changes: 45 additions & 1 deletion lib/checkout_sdk/checkout_utils.rb
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,37 @@ def self.error_message(prefix, body, include_text_body: false)
"#{prefix} Details: #{escape_control_characters(details)}."
end

INVALID_PATH_SEGMENTS = ['', '.', '..'].freeze
FORBIDDEN_PATH_SEGMENT_BYTES = %r{[/\\\x00-\x1F\x7F]}n.freeze
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. 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 "..", 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 = 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)
raise CheckoutArgumentException, INVALID_PATH_SEGMENT_MESSAGE if INVALID_PATH_SEGMENTS.include?(encoded)

encoded
end

# 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.
Expand Down Expand Up @@ -91,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

Expand Down
10 changes: 8 additions & 2 deletions lib/checkout_sdk/client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,15 @@ 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<String, Symbol, Integer>] args
# @return [String]
# @raise [CheckoutArgumentException] when an argument is not a valid path segment (see
# CheckoutUtils.encode_path_segment)
def build_path(*args)
args.join('/')
args.map { |segment| CheckoutUtils.encode_path_segment(segment) }.join('/')
end

# @return [TrueClass, FalseClass]
Expand Down
7 changes: 4 additions & 3 deletions lib/checkout_sdk/instruments/instruments_client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
2 changes: 2 additions & 0 deletions lib/checkout_sdk/payments/setups/payment_setups_client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,8 @@ 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 id or payment_method_name is not a valid path segment
# (see Client#build_path)
def confirm_payment_setup(id, payment_method_name)
api_client.invoke_post(
build_path(PAYMENTS_PATH, SETUPS_PATH, id, CONFIRM_PATH, payment_method_name),
Expand Down
14 changes: 9 additions & 5 deletions lib/checkout_sdk/risk/risk_client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
72 changes: 72 additions & 0 deletions spec/checkout_sdk/checkout_utils_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,73 @@
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'))
.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
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 '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

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

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),
"a\xFFb".dup.force_encoding(Encoding::UTF_8), "\xC3\xA9".b]
invalid_values.each do |value|
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
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

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')
Expand All @@ -26,6 +93,11 @@
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
Expand Down
Loading
Loading