diff --git a/README.md b/README.md index 219c544..9c8a71e 100644 --- a/README.md +++ b/README.md @@ -172,6 +172,10 @@ 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` (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 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 bbeea66..00a893e 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 CheckoutUtils.without_request_data(e), cause: nil end parse_response(response) @@ -140,10 +142,12 @@ 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 CheckoutUtils.without_request_data(e), cause: nil end parse_response(response) diff --git a/lib/checkout_sdk/checkout_utils.rb b/lib/checkout_sdk/checkout_utils.rb index 601c05c..9be9c75 100644 --- a/lib/checkout_sdk/checkout_utils.rb +++ b/lib/checkout_sdk/checkout_utils.rb @@ -21,11 +21,86 @@ def self.map_to_http_metadata(response) http_metadata 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. + # + # @param [String, nil] path + # @return [String] + def self.loggable_path(path) + escape_control_characters(utf8_text(path).split('?', 2).first.to_s) + end + + # 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.error_message(prefix, body, include_text_body: false) + text = utf8_text(body).strip + 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 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 + # @return [Faraday::Error] + def self.without_request_data(error) + return error if error.response.nil? + + metadata = map_to_http_metadata(error.response) + 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 + + 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.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 + 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 @@ -33,7 +108,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 3527089..1d69aef 100644 --- a/lib/checkout_sdk/error.rb +++ b/lib/checkout_sdk/error.rb @@ -6,6 +6,16 @@ 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 + + # @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 @@ -13,6 +23,22 @@ 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 [CheckoutSdk::HttpMetadata] http_metadata + # @return [CheckoutSdk::CheckoutAuthorizationException] + def self.token_request_failed(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 + + # 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 end class CheckoutApiException < CheckoutException @@ -35,12 +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? - details = @error_details.to_h.map { |key, value| "#{key}: #{value}" }.join(', ') - message += " Details: #{details}." - 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/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..988e460 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,23 @@ 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 => 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 + raise CheckoutArgumentException, e.wrapped_exception + rescue Faraday::Error => e + raise CheckoutUtils.without_request_data(e), cause: nil + 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..a3ae204 100644 --- a/spec/checkout_sdk/api_client_spec.rb +++ b/spec/checkout_sdk/api_client_spec.rb @@ -291,4 +291,140 @@ 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\nsecond\r\nthird", auth) + + expect(log_output.string.lines.size).to eq(1) + expect(log_output.string).to include('get: /payments/pay_1\\nsecond\\r\\nthird') + 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, body = '{"error_type":"failure"}') + stubs = Faraday::Adapter::Test::Stubs.new do |stub| + 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 + 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 + + 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 + + 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 new file mode 100644 index 0000000..ba32655 --- /dev/null +++ b/spec/checkout_sdk/checkout_utils_spec.rb @@ -0,0 +1,139 @@ +# 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') + 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 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/\u{FFFD}#{backslash}n") + expect(described_class.loggable_path(nil)).to eq('') + end + end + + describe '.error_message' do + let(:prefix) { 'Request failed.' } + + 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 + + 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 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(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 + + 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 'keeps the class and wrapped exception for a class with another constructor' do + custom = Class.new(Faraday::ServerError) do + def initialize(code, response) + super(code.to_s, response) + end + end + 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(custom) + expect(result.wrapped_exception).to be_a(IOError) + 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/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..14626dc --- /dev/null +++ b/spec/checkout_sdk/oauth_sdk_credentials_spec.rb @@ -0,0 +1,128 @@ +# 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].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 '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 '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, + '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 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| + stub.post('/connect/token') { raise Faraday::TimeoutError } + end + + expect { build_credentials(stubs) }.to raise_error(Faraday::TimeoutError) + end + end +end