Skip to content

Commit 0ee5b0b

Browse files
committed
fix: remove non UTF-8 chars from webhook response bodies before saving the logs to the (UTF-8 encoded) database table
1 parent 3a4339c commit 0ee5b0b

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

lib/pact_broker/domain/webhook_request.rb

+8-1
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,14 @@ def log_response response, execution_logger
123123
execution_logger.info "#{header.split("-").collect(&:capitalize).join('-')}: #{response[header]}"
124124
end
125125
logger.debug "body=#{response.body}"
126-
execution_logger.info response.body
126+
safe_body = nil
127+
if response.body
128+
safe_body = response.body.encode('UTF-8', 'binary', invalid: :replace, undef: :replace, replace: '')
129+
if response.body != safe_body
130+
execution_logger.debug "Note that invalid UTF-8 byte sequences were removed from response body before saving the logs"
131+
end
132+
end
133+
execution_logger.info safe_body
127134
end
128135

129136
def log_completion_message options, execution_logger, success

spec/lib/pact_broker/domain/webhook_request_spec.rb

+19
Original file line numberDiff line numberDiff line change
@@ -268,6 +268,25 @@ module Domain
268268
end
269269
end
270270

271+
context "when the response body contains a non UTF-8 character" do
272+
let!(:http_request) do
273+
stub_request(:post, "http://example.org/hook").
274+
to_return(:status => 200, :body => "This has some \xC2 invalid chars")
275+
end
276+
277+
it "removes the non UTF-8 characters before saving the logs so they don't blow up the database" do
278+
result = subject.execute(pact, options)
279+
expect(result.logs).to include "This has some invalid chars"
280+
end
281+
282+
it "logs that it has cleaned the string to the execution logger" do
283+
logger = double("logger").as_null_object
284+
allow(Logger).to receive(:new).and_return(logger)
285+
expect(logger).to receive(:debug).with(/Note that invalid UTF-8 byte sequences were removed/)
286+
subject.execute(pact, options)
287+
end
288+
end
289+
271290
context "when an error occurs executing the request" do
272291

273292
class WebhookTestError < StandardError; end

0 commit comments

Comments
 (0)