Skip to content

Commit

Permalink
feat: redact Authorization header from HTTP client debug output
Browse files Browse the repository at this point in the history
  • Loading branch information
bethesque committed May 22, 2019
1 parent 6887cdd commit c48c991
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 1 deletion.
32 changes: 32 additions & 0 deletions lib/pact/hal/authorization_header_redactor.rb
Original file line number Diff line number Diff line change
@@ -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
7 changes: 6 additions & 1 deletion lib/pact/hal/http_client.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
require 'pact/retry'
require 'pact/hal/authorization_header_redactor'
require 'net/http'

module Pact
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down
15 changes: 15 additions & 0 deletions spec/lib/pact/hal/authorization_header_redactor_spec.rb
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit c48c991

Please sign in to comment.