From 8475c227d3020e30555b901bbb880e75232da100 Mon Sep 17 00:00:00 2001 From: david ruiz Date: Wed, 4 Nov 2026 09:38:11 +0100 Subject: [PATCH 1/3] Security hardening, authentication, exceptions and logs + tests --- lib/checkout_sdk/api_client.rb | 19 ++++- lib/checkout_sdk/checkout_utils.rb | 10 +++ lib/checkout_sdk/error.rb | 37 ++++++++ lib/checkout_sdk/events/events_client.rb | 2 +- lib/checkout_sdk/oauth_sdk_credentials.rb | 28 +++--- spec/checkout_sdk/api_client_spec.rb | 85 ++++++++++++++++++- spec/checkout_sdk/checkout_utils_spec.rb | 26 ++++++ .../checkout_sdk/events/events_client_spec.rb | 26 ++++++ .../oauth_sdk_credentials_spec.rb | 77 +++++++++++++++++ 9 files changed, 293 insertions(+), 17 deletions(-) create mode 100644 spec/checkout_sdk/checkout_utils_spec.rb create mode 100644 spec/checkout_sdk/events/events_client_spec.rb create mode 100644 spec/checkout_sdk/oauth_sdk_credentials_spec.rb diff --git a/lib/checkout_sdk/api_client.rb b/lib/checkout_sdk/api_client.rb index bbeea66..ea93a85 100644 --- a/lib/checkout_sdk/api_client.rb +++ b/lib/checkout_sdk/api_client.rb @@ -52,10 +52,12 @@ def invoke(method, path, authorization, body = nil, idempotency_key = nil, param json_body = CheckoutSdk::JsonSerializer.to_custom_hash(body).to_json begin - @log.info "#{method}: /#{path}" + @log.info "#{method}: /#{CheckoutUtils.loggable_path(path)}" response = @client.run_request(method, path, json_body, headers) rescue Faraday::ClientError => e - raise CheckoutApiException, e.response + raise CheckoutApiException.new(e.response), cause: nil + rescue Faraday::Error => e + raise_without_request_data(e) end parse_response(response) @@ -140,16 +142,25 @@ def upload(path, authorization, file_request) form = build_multipart_request(file_request, file) begin - @log.info "post: /#{path}" + @log.info "post: /#{CheckoutUtils.loggable_path(path)}" response = @multipart_client.run_request(:post, path, form, headers) rescue Faraday::ClientError => e - raise CheckoutApiException, e.response + raise CheckoutApiException.new(e.response), cause: nil + rescue Faraday::Error => e + raise_without_request_data(e) end parse_response(response) end end + # Re-raises a Faraday error unchanged except that the request data attached by the raise_error + # middleware is removed; the response status, headers and body stay available. + def raise_without_request_data(error) + error.response.delete(:request) if error.response.is_a?(Hash) && !error.response.frozen? + raise error + end + def parse_response(response) raise CheckoutApiException, response if response.status < 200 || response.status >= 400 diff --git a/lib/checkout_sdk/checkout_utils.rb b/lib/checkout_sdk/checkout_utils.rb index 601c05c..157ce5e 100644 --- a/lib/checkout_sdk/checkout_utils.rb +++ b/lib/checkout_sdk/checkout_utils.rb @@ -21,6 +21,16 @@ def self.map_to_http_metadata(response) http_metadata end + # Returns the request path in a form safe for a single log line: the query string is left out + # and control characters are escaped. + # + # @param [String, nil] path + # @return [String] + def self.loggable_path(path) + text = path.to_s.dup.force_encoding(Encoding::UTF_8).scrub + text.split('?', 2).first.to_s.gsub(/[[:cntrl:]]/) { |char| char.dump[1..-2] } + end + # @return [Faraday::Connection] def self.build_multipart_client Faraday.new do |f| diff --git a/lib/checkout_sdk/error.rb b/lib/checkout_sdk/error.rb index 3527089..fa251e7 100644 --- a/lib/checkout_sdk/error.rb +++ b/lib/checkout_sdk/error.rb @@ -6,6 +6,9 @@ class CheckoutException < StandardError; end class CheckoutArgumentException < CheckoutException; end class CheckoutAuthorizationException < CheckoutException + # @return [CheckoutSdk::HttpMetadata, nil] response status, headers and body when raised for an OAuth token response + attr_reader :http_metadata + def self.invalid_authorization(authorization_type) new("Operation requires #{authorization_type} authorization type.") end @@ -13,6 +16,40 @@ def self.invalid_authorization(authorization_type) def self.invalid_key(key_type) new("#{key_type} is required for this operation.") end + + # Builds the error for an unsuccessful OAuth token response from the response data only. + # + # @param [Integer, nil] status + # @param [Hash, nil] headers + # @param [String, nil] body + # @return [CheckoutSdk::CheckoutAuthorizationException] + def self.token_request_failed(status, headers, body) + http_metadata = CheckoutSdk::HttpMetadata.new + http_metadata.status_code = status + http_metadata.headers = headers + http_metadata.body = body + + error = new(token_error_message(status, body)) + error.instance_variable_set(:@http_metadata, http_metadata) + error + end + + def self.token_error_message(status, body) + message = "The OAuth token response status code (#{status}) does not indicate success." + return message if body.nil? || body.to_s.strip.empty? + + parsed = parse_json(body) + details = parsed.is_a?(Hash) ? parsed.map { |key, value| "#{key}: #{value}" }.join(', ') : body.to_s.strip + "#{message} Details: #{details}." + end + + def self.parse_json(body) + JSON.parse(body) + rescue JSON::ParserError, TypeError + nil + end + private_class_method :parse_json + private_class_method :token_error_message end class CheckoutApiException < CheckoutException diff --git a/lib/checkout_sdk/events/events_client.rb b/lib/checkout_sdk/events/events_client.rb index 1a5c7c2..83b18a2 100644 --- a/lib/checkout_sdk/events/events_client.rb +++ b/lib/checkout_sdk/events/events_client.rb @@ -20,7 +20,7 @@ def initialize(api_client, configuration) # @param [String,nil] version def retrieve_all_event_types(version = nil) - query = "version=#{version}" unless version.nil? + query = URI.encode_www_form(version: version) unless version.nil? api_client.invoke_get(EVENT_TYPES, sdk_authorization, query) end diff --git a/lib/checkout_sdk/oauth_sdk_credentials.rb b/lib/checkout_sdk/oauth_sdk_credentials.rb index ca49698..d570fd7 100644 --- a/lib/checkout_sdk/oauth_sdk_credentials.rb +++ b/lib/checkout_sdk/oauth_sdk_credentials.rb @@ -65,17 +65,7 @@ def build_access_token scope: @scopes.join(' ') } - headers = { 'Content-Type': 'application/x-www-form-urlencoded' } - body = URI.encode_www_form data - - begin - @log.info "post: #{authorization_uri}" - response = @oauth_http_client.run_request(:post, @authorization_uri, body, headers) - rescue Faraday::ClientError => e - raise CheckoutAuthorizationException, e.response - rescue Faraday::ConnectionFailed => e - raise CheckoutArgumentException, e.wrapped_exception - end + response = request_access_token(URI.encode_www_form(data)) if !response.body.nil? && response.body != '' oauth_response = JSON.parse(response.body, object_class: OpenStruct) @@ -90,6 +80,22 @@ def build_access_token private + # @param [String] body + # @return [Faraday::Response] + def request_access_token(body) + headers = { 'Content-Type': 'application/x-www-form-urlencoded' } + @log.info "post: #{CheckoutUtils.loggable_path(authorization_uri)}" + @oauth_http_client.run_request(:post, @authorization_uri, body, headers) + rescue Faraday::ClientError, Faraday::ServerError => e + raise if e.response.nil? + + metadata = CheckoutUtils.map_to_http_metadata(e.response) + raise CheckoutAuthorizationException.token_request_failed(metadata.status_code, metadata.headers, + metadata.body), cause: nil + rescue Faraday::ConnectionFailed => e + raise CheckoutArgumentException, e.wrapped_exception + end + # @param [String] client_id # @param [String] client_secret # @param [Environment] environment diff --git a/spec/checkout_sdk/api_client_spec.rb b/spec/checkout_sdk/api_client_spec.rb index f5160fd..fddc91a 100644 --- a/spec/checkout_sdk/api_client_spec.rb +++ b/spec/checkout_sdk/api_client_spec.rb @@ -291,4 +291,87 @@ expect(captured).not_to have_key(:'If-Match') end end -end \ No newline at end of file + + describe 'request logging' do + let(:log_output) { StringIO.new } + let(:logging_configuration) do + double( + 'CheckoutConfiguration', + http_client: Faraday.new, + multipart_http_client: Faraday.new, + logger: Logger.new(log_output) + ) + end + let(:logging_client) { CheckoutSdk::ApiClient.new(logging_configuration, 'https://api.sandbox.checkout.com') } + let(:auth) { double('auth', authorization_header: 'Bearer xxx') } + let(:response) { double('Response', status: 200, body: '{}', headers: { 'Content-Type' => 'application/json' }) } + + before do + allow(CheckoutSdk::CheckoutUtils).to receive(:map_to_http_metadata).and_return( + OpenStruct.new(status_code: 200, body: '{}') + ) + allow(logging_client.client).to receive(:run_request).and_return(response) + end + + it 'writes one log line for an id with line breaks' do + logging_client.invoke_get("payments/pay_1\nI, [2026] INFO -- : extra\r\nline", auth) + + expect(log_output.string.lines.size).to eq(1) + expect(log_output.string).to include('get: /payments/pay_1\\nI, [2026] INFO -- : extra\\r\\nline') + end + + it 'logs the path without the query string' do + logging_client.invoke_get('events', auth, { reference: 'order-1' }) + + expect(log_output.string).to include('get: /events') + expect(log_output.string).not_to include('order-1') + expect(logging_client.client).to have_received(:run_request) + .with(:get, 'events?reference=order-1', anything, anything) + end + end + + describe 'error data' do + let(:secret_key) { 'sk_sbox_m73dzbpy7cf3gfd46xr4yj5xo4e' } + let(:auth) { double('auth', authorization_header: secret_key) } + + def client_answering(status) + stubs = Faraday::Adapter::Test::Stubs.new do |stub| + stub.post('/payments') { [status, { 'Content-Type' => 'application/json' }, '{"error_type":"failure"}'] } + end + http_client = Faraday.new do |f| + f.response :raise_error + f.adapter :test, stubs + end + configuration = double('CheckoutConfiguration', http_client: http_client, multipart_http_client: Faraday.new, + logger: Logger.new(StringIO.new)) + CheckoutSdk::ApiClient.new(configuration, 'https://api.sandbox.checkout.com') + end + + def expect_no_request_data(error) + [error.message, error.inspect, error.full_message].each do |text| + expect(text).not_to include(secret_key) + expect(text).not_to include('card_number') + end + expect(error.cause).to be_nil + end + + it 'client error omits request data' do + expect { client_answering(422).invoke_post('payments', auth, { card_number: '4242' }) } + .to raise_error(CheckoutSdk::CheckoutApiException) do |error| + expect_no_request_data(error) + expect(error.http_metadata.status_code).to eq(422) + expect(error.error_details.error_type).to eq('failure') + end + end + + it 'server error keeps its class and response but omits request data' do + expect { client_answering(500).invoke_post('payments', auth, { card_number: '4242' }) } + .to raise_error(Faraday::ServerError) do |error| + expect_no_request_data(error) + expect(error.response).not_to have_key(:request) + expect(error.response_status).to eq(500) + expect(error.response_body).to eq('{"error_type":"failure"}') + end + end + end +end diff --git a/spec/checkout_sdk/checkout_utils_spec.rb b/spec/checkout_sdk/checkout_utils_spec.rb new file mode 100644 index 0000000..6af235b --- /dev/null +++ b/spec/checkout_sdk/checkout_utils_spec.rb @@ -0,0 +1,26 @@ +# frozen_string_literal: true + +RSpec.describe CheckoutSdk::CheckoutUtils do + 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') + end + + it 'leaves out the query string' do + expect(described_class.loggable_path('events?from=2026-01-01&reference=ref')).to eq('events') + end + + it 'escapes control characters' do + expect(described_class.loggable_path("payments/a\nb\rc\td\e")).to eq('payments/a\nb\rc\td\e') + end + + it 'escapes unicode line separators' do + expect(described_class.loggable_path("payments/a\u2028b\u2029c")).to eq('payments/a\u2028b\u2029c') + end + + it 'accepts invalid byte sequences and nil' do + expect(described_class.loggable_path("payments/\xFF\n".b)).to eq("payments/\uFFFD\\n") + expect(described_class.loggable_path(nil)).to eq('') + end + end +end diff --git a/spec/checkout_sdk/events/events_client_spec.rb b/spec/checkout_sdk/events/events_client_spec.rb new file mode 100644 index 0000000..da8f7c1 --- /dev/null +++ b/spec/checkout_sdk/events/events_client_spec.rb @@ -0,0 +1,26 @@ +# frozen_string_literal: true + +RSpec.describe CheckoutSdk::Previous::Events::EventsClient do + let(:api_client) { instance_double(CheckoutSdk::ApiClient) } + let(:authorization) { CheckoutSdk::SdkAuthorization.new(CheckoutSdk::PlatformType::PREVIOUS, 'sk_test') } + let(:client) do + client = described_class.allocate + allow(client).to receive(:api_client).and_return(api_client) + allow(client).to receive(:sdk_authorization).and_return(authorization) + client + end + + describe '#retrieve_all_event_types' do + it 'encodes the version query value' do + expect(api_client).to receive(:invoke_get).with('event-types', authorization, 'version=1.0%26x%3Dy%23z') + + client.retrieve_all_event_types('1.0&x=y#z') + end + + it 'sends no query without a version' do + expect(api_client).to receive(:invoke_get).with('event-types', authorization, nil) + + client.retrieve_all_event_types + end + end +end diff --git a/spec/checkout_sdk/oauth_sdk_credentials_spec.rb b/spec/checkout_sdk/oauth_sdk_credentials_spec.rb new file mode 100644 index 0000000..9652eed --- /dev/null +++ b/spec/checkout_sdk/oauth_sdk_credentials_spec.rb @@ -0,0 +1,77 @@ +# frozen_string_literal: true + +RSpec.describe CheckoutSdk::OAuthSdkCredentials do + let(:client_secret) { 'oauth-client-secret-value' } + let(:authorization_uri) { 'https://access.sandbox.checkout.com/connect/token' } + + def build_credentials(stubs) + http_client = Faraday.new do |f| + f.response :raise_error + f.adapter :test, stubs + end + described_class.new('ack_client_id', client_secret, [CheckoutSdk::OAuthScopes::GATEWAY], http_client, + CheckoutSdk::Environment.sandbox, Logger.new(StringIO.new), authorization_uri) + end + + def token_stubs(status, body) + Faraday::Adapter::Test::Stubs.new do |stub| + stub.post('/connect/token') { [status, { 'Content-Type' => 'application/json' }, body] } + end + end + + context 'when the token response is successful' do + it 'builds the access token' do + body = '{"access_token":"token-value","token_type":"Bearer","expires_in":3600}' + credentials = build_credentials(token_stubs(200, body)) + + expect(credentials.access_token.token).to eq('token-value') + end + end + + context 'when the token response does not indicate success' do + [400, 401, 429, 500].each do |status| + it "error message omits credentials for status #{status}" do + expect { build_credentials(token_stubs(status, '{"error":"invalid_client"}')) } + .to raise_error(CheckoutSdk::CheckoutAuthorizationException) do |error| + [error.message, error.inspect, error.full_message].each do |text| + expect(text).not_to include(client_secret) + expect(text).not_to include('grant_type=') + end + expect(error.cause).to be_nil + end + end + end + + it 'builds the message from status and body' do + expect { build_credentials(token_stubs(401, '{"error":"invalid_client"}')) } + .to raise_error(CheckoutSdk::CheckoutAuthorizationException, + 'The OAuth token response status code (401) does not indicate success. ' \ + 'Details: error: invalid_client.') + end + + it 'keeps a body that is not JSON in the message' do + expect { build_credentials(token_stubs(400, 'Bad Request')) } + .to raise_error(CheckoutSdk::CheckoutAuthorizationException, + 'The OAuth token response status code (400) does not indicate success. Details: Bad Request.') + end + + it 'exposes the response status, headers and body' do + expect { build_credentials(token_stubs(429, '{"error":"rate_limited"}')) } + .to raise_error(CheckoutSdk::CheckoutAuthorizationException) do |error| + expect(error.http_metadata.status_code).to eq(429) + expect(error.http_metadata.headers['Content-Type']).to eq('application/json') + expect(error.http_metadata.body).to eq('{"error":"rate_limited"}') + end + end + end + + context 'when the token request times out' do + it 're-raises the timeout unchanged' do + stubs = Faraday::Adapter::Test::Stubs.new do |stub| + stub.post('/connect/token') { raise Faraday::TimeoutError } + end + + expect { build_credentials(stubs) }.to raise_error(Faraday::TimeoutError) + end + end +end From b90f464b126dba9e3cba54c94bd51194971fe016 Mon Sep 17 00:00:00 2001 From: david ruiz Date: Wed, 4 Nov 2026 11:00:43 +0100 Subject: [PATCH 2/3] Fine tune the code with more findings + tests --- README.md | 3 + lib/checkout_sdk/api_client.rb | 11 +- lib/checkout_sdk/checkout_utils.rb | 72 +++++++++++- lib/checkout_sdk/error.rb | 36 +++--- lib/checkout_sdk/oauth_sdk_credentials.rb | 11 +- spec/checkout_sdk/api_client_spec.rb | 13 ++- spec/checkout_sdk/checkout_utils_spec.rb | 105 +++++++++++++++++- .../oauth_sdk_credentials_spec.rb | 27 ++++- 8 files changed, 235 insertions(+), 43 deletions(-) diff --git a/README.md b/README.md index 219c544..3a03b96 100644 --- a/README.md +++ b/README.md @@ -172,6 +172,9 @@ api = CheckoutSdk.builder .build ``` +If your connection uses the `raise_error` middleware, configure it as the default client does: +`conn.response :raise_error, include_request: false`. + You don't need to specify the URL for Faraday constructor the SDK grabs the belong URI from `CheckoutSdk::Environment` however if you want to use specific URI's without a proxy you can create the `Environment` object as follows. diff --git a/lib/checkout_sdk/api_client.rb b/lib/checkout_sdk/api_client.rb index ea93a85..00a893e 100644 --- a/lib/checkout_sdk/api_client.rb +++ b/lib/checkout_sdk/api_client.rb @@ -57,7 +57,7 @@ def invoke(method, path, authorization, body = nil, idempotency_key = nil, param rescue Faraday::ClientError => e raise CheckoutApiException.new(e.response), cause: nil rescue Faraday::Error => e - raise_without_request_data(e) + raise CheckoutUtils.without_request_data(e), cause: nil end parse_response(response) @@ -147,20 +147,13 @@ def upload(path, authorization, file_request) rescue Faraday::ClientError => e raise CheckoutApiException.new(e.response), cause: nil rescue Faraday::Error => e - raise_without_request_data(e) + raise CheckoutUtils.without_request_data(e), cause: nil end parse_response(response) end end - # Re-raises a Faraday error unchanged except that the request data attached by the raise_error - # middleware is removed; the response status, headers and body stay available. - def raise_without_request_data(error) - error.response.delete(:request) if error.response.is_a?(Hash) && !error.response.frozen? - raise error - end - def parse_response(response) raise CheckoutApiException, response if response.status < 200 || response.status >= 400 diff --git a/lib/checkout_sdk/checkout_utils.rb b/lib/checkout_sdk/checkout_utils.rb index 157ce5e..44eb324 100644 --- a/lib/checkout_sdk/checkout_utils.rb +++ b/lib/checkout_sdk/checkout_utils.rb @@ -21,21 +21,85 @@ def self.map_to_http_metadata(response) http_metadata end + MAX_MESSAGE_BODY_LENGTH = 256 + private_constant :MAX_MESSAGE_BODY_LENGTH + + # Returns the text in a form safe for a single log line: control characters and Unicode line + # and paragraph separators are escaped, invalid byte sequences are replaced. + # + # @param [String, nil] text + # @return [String] + def self.escape_control_characters(text) + utf8_text(text).gsub(/[[:cntrl:]\p{Zl}\p{Zp}]/) { |char| char.dump[1..-2] } + end + # Returns the request path in a form safe for a single log line: the query string is left out # and control characters are escaped. # # @param [String, nil] path # @return [String] def self.loggable_path(path) - text = path.to_s.dup.force_encoding(Encoding::UTF_8).scrub - text.split('?', 2).first.to_s.gsub(/[[:cntrl:]]/) { |char| char.dump[1..-2] } + escape_control_characters(utf8_text(path).split('?', 2).first) + end + + # Formats error details as "key: value" pairs for an exception message. + # + # @param [Hash] details + # @return [String] + def self.format_error_details(details) + escape_control_characters(details.map { |key, value| "#{key}: #{value}" }.join(', ')) + end + + # Shortens a response body for an exception message and escapes its control characters. + # + # @param [String, nil] body + # @return [String] + def self.message_body(body) + text = utf8_text(body).strip + text = "#{text[0, MAX_MESSAGE_BODY_LENGTH]}..." if text.length > MAX_MESSAGE_BODY_LENGTH + escape_control_characters(text) + end + + # Returns a Faraday error that keeps the class, the response status, headers and body and the + # backtrace of the given error, without the request data and with a message that names the + # method and URL without the query string. Errors without a response are returned unchanged. + # + # @param [Faraday::Error] error + # @return [Faraday::Error] + def self.without_request_data(error) + return error if error.response.nil? + + metadata = map_to_http_metadata(error.response) + response = { status: metadata.status_code, headers: metadata.headers, body: metadata.body } + message = response_error_message(metadata.status_code, error.response) + rebuilt = begin + error.class.new(message, response) + rescue StandardError + Faraday::Error.new(message, response) + end + rebuilt.set_backtrace(error.backtrace) + rebuilt + end + + def self.response_error_message(status, response) + message = "the server responded with status #{status}" + request = response.is_a?(Hash) ? response[:request] : nil + return message unless request.is_a?(Hash) && request[:url] + + "#{message} for #{request[:method].to_s.upcase} #{loggable_path(request[:url].to_s)}" + end + private_class_method :response_error_message + + def self.utf8_text(text) + text.to_s.dup.force_encoding(Encoding::UTF_8).scrub end + private_class_method :utf8_text # @return [Faraday::Connection] def self.build_multipart_client Faraday.new do |f| f.request :multipart - f.response :raise_error + f.response :raise_error, include_request: false end end @@ -43,7 +107,7 @@ def self.build_multipart_client def self.build_default_client Faraday.new do |f| f.response :follow_redirects - f.response :raise_error + f.response :raise_error, include_request: false end end end diff --git a/lib/checkout_sdk/error.rb b/lib/checkout_sdk/error.rb index fa251e7..e3acbe9 100644 --- a/lib/checkout_sdk/error.rb +++ b/lib/checkout_sdk/error.rb @@ -9,6 +9,13 @@ class CheckoutAuthorizationException < CheckoutException # @return [CheckoutSdk::HttpMetadata, nil] response status, headers and body when raised for an OAuth token response attr_reader :http_metadata + # @param [String, nil] message + # @param [CheckoutSdk::HttpMetadata, nil] http_metadata + def initialize(message = nil, http_metadata = nil) + @http_metadata = http_metadata + super(message) + end + def self.invalid_authorization(authorization_type) new("Operation requires #{authorization_type} authorization type.") end @@ -19,27 +26,21 @@ def self.invalid_key(key_type) # Builds the error for an unsuccessful OAuth token response from the response data only. # - # @param [Integer, nil] status - # @param [Hash, nil] headers - # @param [String, nil] body + # @param [CheckoutSdk::HttpMetadata] http_metadata # @return [CheckoutSdk::CheckoutAuthorizationException] - def self.token_request_failed(status, headers, body) - http_metadata = CheckoutSdk::HttpMetadata.new - http_metadata.status_code = status - http_metadata.headers = headers - http_metadata.body = body - - error = new(token_error_message(status, body)) - error.instance_variable_set(:@http_metadata, http_metadata) - error + def self.token_request_failed(http_metadata) + new(token_error_message(http_metadata), http_metadata) end - def self.token_error_message(status, body) - message = "The OAuth token response status code (#{status}) does not indicate success." - return message if body.nil? || body.to_s.strip.empty? + def self.token_error_message(http_metadata) + message = "The OAuth token response status code (#{http_metadata.status_code}) does not indicate success." + body = http_metadata.body.to_s.strip + return message if body.empty? parsed = parse_json(body) - details = parsed.is_a?(Hash) ? parsed.map { |key, value| "#{key}: #{value}" }.join(', ') : body.to_s.strip + return message if parsed.is_a?(Hash) && parsed.empty? + + details = parsed.is_a?(Hash) ? CheckoutUtils.format_error_details(parsed) : CheckoutUtils.message_body(body) "#{message} Details: #{details}." end @@ -74,8 +75,7 @@ def parse_error_details(body) def build_error_message message = "The API response status code (#{http_metadata.status_code}) does not indicate success." if @error_details && !@error_details.to_h.empty? - details = @error_details.to_h.map { |key, value| "#{key}: #{value}" }.join(', ') - message += " Details: #{details}." + message += " Details: #{CheckoutUtils.format_error_details(@error_details.to_h)}." end message end diff --git a/lib/checkout_sdk/oauth_sdk_credentials.rb b/lib/checkout_sdk/oauth_sdk_credentials.rb index d570fd7..90978ee 100644 --- a/lib/checkout_sdk/oauth_sdk_credentials.rb +++ b/lib/checkout_sdk/oauth_sdk_credentials.rb @@ -86,14 +86,13 @@ def request_access_token(body) headers = { 'Content-Type': 'application/x-www-form-urlencoded' } @log.info "post: #{CheckoutUtils.loggable_path(authorization_uri)}" @oauth_http_client.run_request(:post, @authorization_uri, body, headers) - rescue Faraday::ClientError, Faraday::ServerError => e - raise if e.response.nil? - - metadata = CheckoutUtils.map_to_http_metadata(e.response) - raise CheckoutAuthorizationException.token_request_failed(metadata.status_code, metadata.headers, - metadata.body), cause: nil + rescue Faraday::ClientError => e + raise CheckoutAuthorizationException.token_request_failed(CheckoutUtils.map_to_http_metadata(e.response)), + cause: nil rescue Faraday::ConnectionFailed => e raise CheckoutArgumentException, e.wrapped_exception + rescue Faraday::Error => e + raise CheckoutUtils.without_request_data(e), cause: nil end # @param [String] client_id diff --git a/spec/checkout_sdk/api_client_spec.rb b/spec/checkout_sdk/api_client_spec.rb index fddc91a..17df486 100644 --- a/spec/checkout_sdk/api_client_spec.rb +++ b/spec/checkout_sdk/api_client_spec.rb @@ -314,10 +314,10 @@ end it 'writes one log line for an id with line breaks' do - logging_client.invoke_get("payments/pay_1\nI, [2026] INFO -- : extra\r\nline", auth) + logging_client.invoke_get("payments/pay_1\nsecond\r\nthird", auth) expect(log_output.string.lines.size).to eq(1) - expect(log_output.string).to include('get: /payments/pay_1\\nI, [2026] INFO -- : extra\\r\\nline') + expect(log_output.string).to include('get: /payments/pay_1\\nsecond\\r\\nthird') end it 'logs the path without the query string' do @@ -337,6 +337,7 @@ def client_answering(status) stubs = Faraday::Adapter::Test::Stubs.new do |stub| stub.post('/payments') { [status, { 'Content-Type' => 'application/json' }, '{"error_type":"failure"}'] } + stub.get('/events') { [status, {}, ''] } end http_client = Faraday.new do |f| f.response :raise_error @@ -373,5 +374,13 @@ def expect_no_request_data(error) expect(error.response_body).to eq('{"error_type":"failure"}') end end + + it 'server error message names the path without the query string' do + expect { client_answering(503).invoke_get('events', auth, { reference: 'order-1' }) } + .to raise_error(Faraday::ServerError) do |error| + expect(error.message).to eq('the server responded with status 503 for GET https://api.sandbox.checkout.com/events') + expect(error.full_message).not_to include('order-1') + end + end end end diff --git a/spec/checkout_sdk/checkout_utils_spec.rb b/spec/checkout_sdk/checkout_utils_spec.rb index 6af235b..288fc97 100644 --- a/spec/checkout_sdk/checkout_utils_spec.rb +++ b/spec/checkout_sdk/checkout_utils_spec.rb @@ -1,6 +1,8 @@ # frozen_string_literal: true RSpec.describe CheckoutSdk::CheckoutUtils do + let(:backslash) { '\\' } + 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') @@ -14,13 +16,110 @@ expect(described_class.loggable_path("payments/a\nb\rc\td\e")).to eq('payments/a\nb\rc\td\e') end - it 'escapes unicode line separators' do - expect(described_class.loggable_path("payments/a\u2028b\u2029c")).to eq('payments/a\u2028b\u2029c') + it 'escapes unicode line and paragraph separators' do + expected = "payments/a#{backslash}u2028b#{backslash}u2029c" + + expect(described_class.loggable_path("payments/a\u{2028}b\u{2029}c")).to eq(expected) end it 'accepts invalid byte sequences and nil' do - expect(described_class.loggable_path("payments/\xFF\n".b)).to eq("payments/\uFFFD\\n") + 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 end + + describe '.format_error_details' do + it 'joins key and value pairs on one line' do + details = { error_type: 'request_invalid', error_codes: "a\nb" } + + expect(described_class.format_error_details(details)).to eq('error_type: request_invalid, error_codes: a\nb') + end + end + + describe '.message_body' do + it 'keeps a short body' do + expect(described_class.message_body(" Bad Request \n")).to eq('Bad Request') + end + + it 'shortens a long body and escapes it' do + result = described_class.message_body("#{'x' * 300}\n") + + expect(result).to eq("#{'x' * 256}...") + end + end + + describe '.without_request_data' do + let(:request) { { method: :get, url: URI('https://api.example.com/events?reference=order-1'), headers: { 'Authorization' => 'secret-value' } } } + + def expect_clean(error) + expect(error.inspect).not_to include('secret-value') + expect(error.message).to eq('the server responded with status 500 for GET https://api.example.com/events') + end + + it 'keeps the class, response and backtrace' do + original = Faraday::ServerError.new({ status: 500, headers: { 'Cko-Request-Id' => 'id' }, body: '{}', request: request }) + original.set_backtrace(%w[frame_one frame_two]) + + result = described_class.without_request_data(original) + + expect(result).to be_a(Faraday::ServerError) + expect(result.response).to eq(status: 500, headers: { 'Cko-Request-Id' => 'id' }, body: '{}') + expect(result.backtrace).to eq(%w[frame_one frame_two]) + expect_clean(result) + end + + it 'handles a frozen response' do + original = Faraday::ServerError.new({ status: 500, body: '{}', request: request }.freeze) + + result = described_class.without_request_data(original) + + expect(result.response).not_to have_key(:request) + expect_clean(result) + end + + it 'handles a Faraday::Response' do + env = Faraday::Env.from(status: 500, body: '{}', response_headers: {}, request_headers: { 'Authorization' => 'secret-value' }) + original = Faraday::ServerError.new('failed', Faraday::Response.new(env)) + + result = described_class.without_request_data(original) + + expect(result.inspect).not_to include('secret-value') + expect(result.response).to eq(status: 500, headers: {}, body: '{}') + expect(result.message).to eq('the server responded with status 500') + end + + it 'falls back to Faraday::Error for a class with another constructor' do + custom = Class.new(Faraday::ServerError) do + def initialize(response) + super('custom', response) + end + end + original = custom.new({ status: 500, request: request }) + + result = described_class.without_request_data(original) + + expect(result).to be_a(Faraday::Error) + expect_clean(result) + end + + it 'returns an error without response unchanged' do + original = Faraday::TimeoutError.new + + expect(described_class.without_request_data(original)).to be(original) + end + end + + describe 'default clients' do + %i[build_default_client build_multipart_client].each do |builder| + it "#{builder} raises errors without request data" do + stubs = Faraday::Adapter::Test::Stubs.new { |stub| stub.get('/payments') { [500, {}, ''] } } + client = described_class.public_send(builder) + client.builder.adapter :test, stubs + + expect { client.get('/payments') }.to raise_error(Faraday::ServerError) do |error| + expect(error.response).not_to have_key(:request) + end + end + end + end end diff --git a/spec/checkout_sdk/oauth_sdk_credentials_spec.rb b/spec/checkout_sdk/oauth_sdk_credentials_spec.rb index 9652eed..0ec318d 100644 --- a/spec/checkout_sdk/oauth_sdk_credentials_spec.rb +++ b/spec/checkout_sdk/oauth_sdk_credentials_spec.rb @@ -29,7 +29,7 @@ def token_stubs(status, body) end context 'when the token response does not indicate success' do - [400, 401, 429, 500].each do |status| + [400, 401, 429].each do |status| it "error message omits credentials for status #{status}" do expect { build_credentials(token_stubs(status, '{"error":"invalid_client"}')) } .to raise_error(CheckoutSdk::CheckoutAuthorizationException) do |error| @@ -42,6 +42,31 @@ def token_stubs(status, body) end end + it 'server error keeps its class and omits request data' do + expect { build_credentials(token_stubs(500, '{"error":"server_error"}')) } + .to raise_error(Faraday::ServerError) do |error| + [error.message, error.inspect, error.full_message].each do |text| + expect(text).not_to include(client_secret) + expect(text).not_to include('grant_type=') + end + expect(error.response).not_to have_key(:request) + expect(error.response_status).to eq(500) + expect(error.cause).to be_nil + end + end + + it 'shortens a long body that is not JSON to one line' do + html = "\n#{'x' * 600}\n" + + expect { build_credentials(token_stubs(403, html)) } + .to raise_error(CheckoutSdk::CheckoutAuthorizationException) do |error| + expect(error.message.lines.size).to eq(1) + expect(error.message.length).to be < 400 + expect(error.message).to end_with('....') + expect(error.http_metadata.body).to eq(html) + end + end + it 'builds the message from status and body' do expect { build_credentials(token_stubs(401, '{"error":"invalid_client"}')) } .to raise_error(CheckoutSdk::CheckoutAuthorizationException, From e1aea51f036d6c0c4fbc0189d83f0b294db91c1b Mon Sep 17 00:00:00 2001 From: david ruiz Date: Wed, 4 Nov 2026 12:52:42 +0100 Subject: [PATCH 3/3] Code review changes to fine tune error messages + tests --- README.md | 3 +- lib/checkout_sdk/checkout_utils.rb | 69 ++++++++++--------- lib/checkout_sdk/error.rb | 33 +++------ lib/checkout_sdk/oauth_sdk_credentials.rb | 2 + spec/checkout_sdk/api_client_spec.rb | 48 ++++++++++++- spec/checkout_sdk/checkout_utils_spec.rb | 46 ++++++++----- .../oauth_sdk_credentials_spec.rb | 26 +++++++ 7 files changed, 150 insertions(+), 77 deletions(-) diff --git a/README.md b/README.md index 3a03b96..9c8a71e 100644 --- a/README.md +++ b/README.md @@ -173,7 +173,8 @@ api = CheckoutSdk.builder ``` If your connection uses the `raise_error` middleware, configure it as the default client does: -`conn.response :raise_error, include_request: false`. +`conn.response :raise_error, include_request: false` (the option needs Faraday 2.7.11 or later; +the SDK leaves the request data out of the errors it raises in any case). You don't need to specify the URL for Faraday constructor the SDK grabs the belong URI from `CheckoutSdk::Environment` however if you want to diff --git a/lib/checkout_sdk/checkout_utils.rb b/lib/checkout_sdk/checkout_utils.rb index 44eb324..9be9c75 100644 --- a/lib/checkout_sdk/checkout_utils.rb +++ b/lib/checkout_sdk/checkout_utils.rb @@ -21,17 +21,8 @@ def self.map_to_http_metadata(response) http_metadata end - MAX_MESSAGE_BODY_LENGTH = 256 - private_constant :MAX_MESSAGE_BODY_LENGTH - - # Returns the text in a form safe for a single log line: control characters and Unicode line - # and paragraph separators are escaped, invalid byte sequences are replaced. - # - # @param [String, nil] text - # @return [String] - def self.escape_control_characters(text) - utf8_text(text).gsub(/[[:cntrl:]\p{Zl}\p{Zp}]/) { |char| char.dump[1..-2] } - end + MAX_MESSAGE_DETAILS_LENGTH = 256 + private_constant :MAX_MESSAGE_DETAILS_LENGTH # Returns the request path in a form safe for a single log line: the query string is left out # and control characters are escaped. @@ -39,29 +30,30 @@ def self.escape_control_characters(text) # @param [String, nil] path # @return [String] def self.loggable_path(path) - escape_control_characters(utf8_text(path).split('?', 2).first) - end - - # Formats error details as "key: value" pairs for an exception message. - # - # @param [Hash] details - # @return [String] - def self.format_error_details(details) - escape_control_characters(details.map { |key, value| "#{key}: #{value}" }.join(', ')) + escape_control_characters(utf8_text(path).split('?', 2).first.to_s) end - # Shortens a response body for an exception message and escapes its control characters. + # Builds an exception message from a prefix and a response body. A JSON object body adds its + # "key: value" pairs as details; any other non-empty body is added as is only when + # include_text_body is true. Details are shortened and their control characters escaped. # + # @param [String] prefix # @param [String, nil] body + # @param [Boolean] include_text_body # @return [String] - def self.message_body(body) + def self.error_message(prefix, body, include_text_body: false) text = utf8_text(body).strip - text = "#{text[0, MAX_MESSAGE_BODY_LENGTH]}..." if text.length > MAX_MESSAGE_BODY_LENGTH - escape_control_characters(text) + parsed = json_object(text) + details = parsed&.map { |key, value| "#{key}: #{value}" }&.join(', ') + details = text if details.nil? && include_text_body + return prefix if details.nil? || details.empty? + + details = "#{details[0, MAX_MESSAGE_DETAILS_LENGTH]}..." if details.length > MAX_MESSAGE_DETAILS_LENGTH + "#{prefix} Details: #{escape_control_characters(details)}." end - # Returns a Faraday error that keeps the class, the response status, headers and body and the - # backtrace of the given error, without the request data and with a message that names the + # 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. # # @param [Faraday::Error] error @@ -70,14 +62,9 @@ def self.without_request_data(error) return error if error.response.nil? metadata = map_to_http_metadata(error.response) - response = { status: metadata.status_code, headers: metadata.headers, body: metadata.body } - message = response_error_message(metadata.status_code, error.response) - rebuilt = begin - error.class.new(message, response) - rescue StandardError - Faraday::Error.new(message, response) - end - rebuilt.set_backtrace(error.backtrace) + rebuilt = error.exception(response_error_message(metadata.status_code, error.response)) + rebuilt.instance_variable_set(:@response, + { status: metadata.status_code, headers: metadata.headers, body: metadata.body }) rebuilt end @@ -90,6 +77,20 @@ def self.response_error_message(status, response) end private_class_method :response_error_message + def self.json_object(text) + parsed = JSON.parse(text) + parsed.is_a?(Hash) ? parsed : nil + rescue JSON::ParserError + nil + end + private_class_method :json_object + + # Escapes control characters and Unicode line and paragraph separators in UTF-8 text. + def self.escape_control_characters(text) + text.gsub(/[[:cntrl:]\p{Zl}\p{Zp}]/) { |char| char.dump[1..-2] } + end + private_class_method :escape_control_characters + def self.utf8_text(text) text.to_s.dup.force_encoding(Encoding::UTF_8).scrub end diff --git a/lib/checkout_sdk/error.rb b/lib/checkout_sdk/error.rb index e3acbe9..1d69aef 100644 --- a/lib/checkout_sdk/error.rb +++ b/lib/checkout_sdk/error.rb @@ -29,28 +29,16 @@ def self.invalid_key(key_type) # @param [CheckoutSdk::HttpMetadata] http_metadata # @return [CheckoutSdk::CheckoutAuthorizationException] def self.token_request_failed(http_metadata) - new(token_error_message(http_metadata), http_metadata) + prefix = "The OAuth token response status code (#{http_metadata.status_code}) does not indicate success." + new(CheckoutUtils.error_message(prefix, http_metadata.body, include_text_body: true), http_metadata) end - def self.token_error_message(http_metadata) - message = "The OAuth token response status code (#{http_metadata.status_code}) does not indicate success." - body = http_metadata.body.to_s.strip - return message if body.empty? - - parsed = parse_json(body) - return message if parsed.is_a?(Hash) && parsed.empty? - - details = parsed.is_a?(Hash) ? CheckoutUtils.format_error_details(parsed) : CheckoutUtils.message_body(body) - "#{message} Details: #{details}." - end - - def self.parse_json(body) - JSON.parse(body) - rescue JSON::ParserError, TypeError - nil + # Builds the error for an OAuth token request that failed without a response. + # + # @return [CheckoutSdk::CheckoutAuthorizationException] + def self.token_request_without_response + new('The OAuth token request failed without a response.') end - private_class_method :parse_json - private_class_method :token_error_message end class CheckoutApiException < CheckoutException @@ -73,11 +61,8 @@ def parse_error_details(body) end def build_error_message - message = "The API response status code (#{http_metadata.status_code}) does not indicate success." - if @error_details && !@error_details.to_h.empty? - message += " Details: #{CheckoutUtils.format_error_details(@error_details.to_h)}." - end - message + prefix = "The API response status code (#{http_metadata.status_code}) does not indicate success." + CheckoutUtils.error_message(prefix, http_metadata.body) end end end diff --git a/lib/checkout_sdk/oauth_sdk_credentials.rb b/lib/checkout_sdk/oauth_sdk_credentials.rb index 90978ee..988e460 100644 --- a/lib/checkout_sdk/oauth_sdk_credentials.rb +++ b/lib/checkout_sdk/oauth_sdk_credentials.rb @@ -87,6 +87,8 @@ def request_access_token(body) @log.info "post: #{CheckoutUtils.loggable_path(authorization_uri)}" @oauth_http_client.run_request(:post, @authorization_uri, body, headers) rescue Faraday::ClientError => e + raise CheckoutAuthorizationException.token_request_without_response if e.response.nil? + raise CheckoutAuthorizationException.token_request_failed(CheckoutUtils.map_to_http_metadata(e.response)), cause: nil rescue Faraday::ConnectionFailed => e diff --git a/spec/checkout_sdk/api_client_spec.rb b/spec/checkout_sdk/api_client_spec.rb index 17df486..a3ae204 100644 --- a/spec/checkout_sdk/api_client_spec.rb +++ b/spec/checkout_sdk/api_client_spec.rb @@ -334,11 +334,15 @@ let(:secret_key) { 'sk_sbox_m73dzbpy7cf3gfd46xr4yj5xo4e' } let(:auth) { double('auth', authorization_header: secret_key) } - def client_answering(status) + def client_answering(status, body = '{"error_type":"failure"}') stubs = Faraday::Adapter::Test::Stubs.new do |stub| - stub.post('/payments') { [status, { 'Content-Type' => 'application/json' }, '{"error_type":"failure"}'] } + stub.post('/payments') { [status, { 'Content-Type' => 'application/json' }, body] } stub.get('/events') { [status, {}, ''] } end + client_with(stubs) + end + + def client_with(stubs) http_client = Faraday.new do |f| f.response :raise_error f.adapter :test, stubs @@ -382,5 +386,45 @@ def expect_no_request_data(error) expect(error.full_message).not_to include('order-1') end end + + it 'client error message renders nested values and accepts a JSON array body' do + source = { 'type' => 'card' } + + expect { client_answering(422, { error_type: 'failure', source: source }.to_json).invoke_post('payments', auth) } + .to raise_error(CheckoutSdk::CheckoutApiException, + 'The API response status code (422) does not indicate success. ' \ + "Details: error_type: failure, source: #{source}.") + expect { client_answering(422, '[1,2]').invoke_post('payments', auth) } + .to raise_error(CheckoutSdk::CheckoutApiException, + 'The API response status code (422) does not indicate success.') + end + + it 'client error message shortens a long body' do + body = { error_type: 'x' * 2000 }.to_json + + expect { client_answering(422, body).invoke_post('payments', auth) } + .to raise_error(CheckoutSdk::CheckoutApiException) do |error| + expect(error.message.length).to be < 400 + expect(error.http_metadata.body).to eq(body) + end + end + + low_level_errors = { Faraday::TimeoutError => Net::ReadTimeout, Faraday::ConnectionFailed => Errno::ECONNREFUSED } + low_level_errors.each do |error_class, low_level| + it "#{error_class} keeps its cause and wrapped exception" do + stubs = Faraday::Adapter::Test::Stubs.new do |stub| + stub.get('/events') do + raise low_level + rescue low_level => e + raise error_class, e + end + end + + expect { client_with(stubs).invoke_get('events', auth) }.to raise_error(error_class) do |error| + expect(error.cause).to be_a(low_level) + expect(error.wrapped_exception).to be_a(low_level) + end + end + end end end diff --git a/spec/checkout_sdk/checkout_utils_spec.rb b/spec/checkout_sdk/checkout_utils_spec.rb index 288fc97..ba32655 100644 --- a/spec/checkout_sdk/checkout_utils_spec.rb +++ b/spec/checkout_sdk/checkout_utils_spec.rb @@ -28,23 +28,35 @@ end end - describe '.format_error_details' do - it 'joins key and value pairs on one line' do - details = { error_type: 'request_invalid', error_codes: "a\nb" } + describe '.error_message' do + let(:prefix) { 'Request failed.' } - expect(described_class.format_error_details(details)).to eq('error_type: request_invalid, error_codes: a\nb') + it 'adds the key and value pairs of a JSON object on one line' do + body = '{"error_type":"request_invalid","error_codes":["card_invalid"],"message":"a\\nb","source":{"a":1}}' + source = { 'a' => 1 } + + expect(described_class.error_message(prefix, body)) + .to eq('Request failed. Details: error_type: request_invalid, error_codes: ["card_invalid"], ' \ + "message: a#{backslash}nb, source: #{source}.") + end + + it 'returns the prefix alone for an empty body or an empty JSON object' do + expect(described_class.error_message(prefix, nil)).to eq(prefix) + expect(described_class.error_message(prefix, " {} \n", include_text_body: true)).to eq(prefix) end - end - describe '.message_body' do - it 'keeps a short body' do - expect(described_class.message_body(" Bad Request \n")).to eq('Bad Request') + it 'adds a body that is not a JSON object only when asked to' do + expect(described_class.error_message(prefix, '[1,2]')).to eq(prefix) + expect(described_class.error_message(prefix, " Bad Request \n", include_text_body: true)) + .to eq('Request failed. Details: Bad Request.') end - it 'shortens a long body and escapes it' do - result = described_class.message_body("#{'x' * 300}\n") + it 'shortens long details and escapes them' do + text_body = described_class.error_message(prefix, "a\n#{'x' * 300}", include_text_body: true) + json_body = described_class.error_message(prefix, { error: 'x' * 300 }.to_json) - expect(result).to eq("#{'x' * 256}...") + expect(text_body).to eq("Request failed. Details: a#{backslash}n#{'x' * 254}....") + expect(json_body).to eq("Request failed. Details: error: #{'x' * 249}....") end end @@ -88,17 +100,19 @@ def expect_clean(error) expect(result.message).to eq('the server responded with status 500') end - it 'falls back to Faraday::Error for a class with another constructor' do + it 'keeps the class and wrapped exception for a class with another constructor' do custom = Class.new(Faraday::ServerError) do - def initialize(response) - super('custom', response) + def initialize(code, response) + super(code.to_s, response) end end - original = custom.new({ status: 500, request: request }) + original = custom.new(500, { status: 500, request: request }) + original.instance_variable_set(:@wrapped_exception, IOError.new('closed')) result = described_class.without_request_data(original) - expect(result).to be_a(Faraday::Error) + expect(result).to be_a(custom) + expect(result.wrapped_exception).to be_a(IOError) expect_clean(result) end diff --git a/spec/checkout_sdk/oauth_sdk_credentials_spec.rb b/spec/checkout_sdk/oauth_sdk_credentials_spec.rb index 0ec318d..14626dc 100644 --- a/spec/checkout_sdk/oauth_sdk_credentials_spec.rb +++ b/spec/checkout_sdk/oauth_sdk_credentials_spec.rb @@ -67,6 +67,16 @@ def token_stubs(status, body) end end + it 'shortens a long JSON body in the message' do + body = { error: 'x' * 2000 }.to_json + + expect { build_credentials(token_stubs(400, body)) } + .to raise_error(CheckoutSdk::CheckoutAuthorizationException) do |error| + expect(error.message.length).to be < 400 + expect(error.http_metadata.body).to eq(body) + end + end + it 'builds the message from status and body' do expect { build_credentials(token_stubs(401, '{"error":"invalid_client"}')) } .to raise_error(CheckoutSdk::CheckoutAuthorizationException, @@ -90,6 +100,22 @@ def token_stubs(status, body) end end + context 'when the token request fails without a response' do + it 'raises an authorization error that keeps the original as cause' do + stubs = Faraday::Adapter::Test::Stubs.new do |stub| + stub.post('/connect/token') { raise Faraday::ClientError, 'proxy refused' } + end + + expect { build_credentials(stubs) } + .to raise_error(CheckoutSdk::CheckoutAuthorizationException, + 'The OAuth token request failed without a response.') do |error| + expect(error.http_metadata).to be_nil + expect(error.cause).to be_a(Faraday::ClientError) + expect(error.cause.message).to eq('proxy refused') + end + end + end + context 'when the token request times out' do it 're-raises the timeout unchanged' do stubs = Faraday::Adapter::Test::Stubs.new do |stub|