From c48c99191a7495ef459c6dfb655297aa86c1ce39 Mon Sep 17 00:00:00 2001 From: Beth Skurrie Date: Wed, 22 May 2019 15:27:57 +1000 Subject: [PATCH] feat: redact Authorization header from HTTP client debug output --- lib/pact/hal/authorization_header_redactor.rb | 32 +++++++++++++++++++ lib/pact/hal/http_client.rb | 7 +++- .../hal/authorization_header_redactor_spec.rb | 15 +++++++++ 3 files changed, 53 insertions(+), 1 deletion(-) create mode 100644 lib/pact/hal/authorization_header_redactor.rb create mode 100644 spec/lib/pact/hal/authorization_header_redactor_spec.rb diff --git a/lib/pact/hal/authorization_header_redactor.rb b/lib/pact/hal/authorization_header_redactor.rb new file mode 100644 index 00000000..a0c37537 --- /dev/null +++ b/lib/pact/hal/authorization_header_redactor.rb @@ -0,0 +1,32 @@ +require 'delegate' + +module Pact + module Hal + class AuthorizationHeaderRedactor < SimpleDelegator + def puts(*args) + __getobj__().puts(*redact_args(args)) + end + + def print(*args) + __getobj__().puts(*redact_args(args)) + end + + def <<(*args) + __getobj__().send(:<<, *redact_args(args)) + end + + private + + attr_reader :redactions + + def redact_args(args) + args.collect{ | s| redact(s) } + end + + def redact(string) + return string unless string.is_a?(String) + string.gsub(/Authorization: .*\\r\\n/, "Authorization: [redacted]\\r\\n") + end + end + end +end diff --git a/lib/pact/hal/http_client.rb b/lib/pact/hal/http_client.rb index 3bb2f84e..5a99886c 100644 --- a/lib/pact/hal/http_client.rb +++ b/lib/pact/hal/http_client.rb @@ -1,4 +1,5 @@ require 'pact/retry' +require 'pact/hal/authorization_header_redactor' require 'net/http' module Pact @@ -47,7 +48,7 @@ def create_request uri, http_method, body = nil, headers = {} def perform_request request, uri response = Retry.until_true do http = Net::HTTP.new(uri.host, uri.port, :ENV) - http.set_debug_output(Pact.configuration.output_stream) if verbose + http.set_debug_output(output_stream) if verbose http.use_ssl = (uri.scheme == 'https') http.start do |http| http.request request @@ -56,6 +57,10 @@ def perform_request request, uri Response.new(response) end + def output_stream + AuthorizationHeaderRedactor.new(Pact.configuration.output_stream) + end + class Response < SimpleDelegator def body bod = raw_body diff --git a/spec/lib/pact/hal/authorization_header_redactor_spec.rb b/spec/lib/pact/hal/authorization_header_redactor_spec.rb new file mode 100644 index 00000000..1b43eb70 --- /dev/null +++ b/spec/lib/pact/hal/authorization_header_redactor_spec.rb @@ -0,0 +1,15 @@ +require 'pact/hal/authorization_header_redactor' + +module Pact + module Hal + describe AuthorizationHeaderRedactor do + let(:stream) { StringIO.new } + let(:stream_redactor) { AuthorizationHeaderRedactor.new(stream) } + + it "redacts the authorizaton header" do + stream_redactor << "\\r\\nAuthorization: Bearer TOKEN\\r\\n" + expect(stream.string).to eq "\\r\\nAuthorization: [redacted]\\r\\n" + end + end + end +end