Skip to content

Commit 74ea4b4

Browse files
author
Ron Dahlgren
committed
Mask API key when a client is displayed as a string
This commit implements `to_s` and `inspect` to mask everything after the first four characters of the api key. When using the Ruby SerpAPI client in pry, for instance, the default `inspect` representation will include the `api_key` of the `@params` attribute.
1 parent 3f8842d commit 74ea4b4

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

lib/serpapi/client.rb

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,20 @@ def close
181181
@socket.close if @socket
182182
end
183183

184+
def to_s
185+
# If the api_key is set, mask it
186+
masked_api_key = if api_key && api_key.length > 4
187+
"#{api_key[0..3]}#{'*' * (api_key.length - 4)}"
188+
else
189+
api_key
190+
end
191+
"SerpApi::Client(engine: #{engine}, api_key: #{masked_api_key}, persistent: #{persistent?}, timeout: #{timeout}s)"
192+
end
193+
194+
def inspect
195+
to_s
196+
end
197+
184198
private
185199

186200
# @param [Hash] params to merge with default parameters provided to the constructor.

spec/serpapi/client/client_spec.rb

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,25 @@
9595
raise("wrong exception: #{e}")
9696
end
9797
end
98+
99+
it 'should not expose api_key in to_s and inspect' do
100+
str = client.to_s
101+
expect(str).to include('SerpApi::Client(engine: google, api_key: ')
102+
expect(str).to_not include(ENV['SERPAPI_KEY'])
103+
104+
inspect_str = client.inspect
105+
expect(inspect_str).to include('SerpApi::Client(engine: google, api_key: ')
106+
expect(inspect_str).to_not include(ENV['SERPAPI_KEY'])
107+
end
108+
109+
it 'should gracefully handle api_key values shorter than 5 characters' do
110+
short_key_client = SerpApi::Client.new(engine: 'google', api_key: 'abcd', timeout: 10)
111+
str = short_key_client.to_s
112+
expect(str).to include('SerpApi::Client(engine: google, api_key: abcd')
113+
114+
inspect_str = short_key_client.inspect
115+
expect(inspect_str).to include('SerpApi::Client(engine: google, api_key: abcd')
116+
end
98117
end
99118

100119
describe 'SerpApi client with persitency enable' do
@@ -136,4 +155,4 @@
136155
expect(client.socket).to be_nil
137156
expect(client.close).to be_nil
138157
end
139-
end
158+
end

0 commit comments

Comments
 (0)