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
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
12 changes: 8 additions & 4 deletions lib/checkout_sdk/api_client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down
79 changes: 77 additions & 2 deletions lib/checkout_sdk/checkout_utils.rb
Original file line number Diff line number Diff line change
Expand Up @@ -21,19 +21,94 @@ 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

# @return [Faraday::Connection]
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
Expand Down
34 changes: 28 additions & 6 deletions lib/checkout_sdk/error.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,39 @@ 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

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
Expand All @@ -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
2 changes: 1 addition & 1 deletion lib/checkout_sdk/events/events_client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
29 changes: 18 additions & 11 deletions lib/checkout_sdk/oauth_sdk_credentials.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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
Expand Down
138 changes: 137 additions & 1 deletion spec/checkout_sdk/api_client_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -291,4 +291,140 @@
expect(captured).not_to have_key(:'If-Match')
end
end
end

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
Loading
Loading