Skip to content

Commit 95ae715

Browse files
committed
API-Key: Initial work to support Api Key Authentication
1 parent 1866682 commit 95ae715

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

elasticsearch-transport/lib/elasticsearch/transport/client.rb

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,13 @@ def initialize(arguments={}, &block)
109109

110110
@send_get_body_as = @arguments[:send_get_body_as] || 'GET'
111111

112+
if (api_key = @arguments[:api_key])
113+
api_key = __encode(api_key) if api_key.is_a? Hash
114+
@arguments[:transport_options].merge!(
115+
headers: { 'Authorization' => "ApiKey #{api_key}" }
116+
)
117+
end
118+
112119
if @arguments[:request_timeout]
113120
@arguments[:transport_options][:request] = { :timeout => @arguments[:request_timeout] }
114121
end
@@ -232,6 +239,13 @@ def __auto_detect_adapter
232239
::Faraday.default_adapter
233240
end
234241
end
242+
243+
# Encode credentials for the Authorization Header
244+
# Credentials is the base64 encoding of id and api_key joined by a colon
245+
# @see https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-create-api-key.html
246+
def __encode(api_key)
247+
Base64.encode64([api_key[:id], api_key[:api_key]].join(':'))
248+
end
235249
end
236250
end
237251
end

elasticsearch-transport/spec/elasticsearch/transport/client_spec.rb

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,28 @@
4545
expect(client.transport.hosts[0][:host]).to eq('localhost')
4646
end
4747

48+
context 'when an encoded api_key is provided' do
49+
let(:client) do
50+
described_class.new(api_key: 'an_api_key')
51+
end
52+
53+
it 'Adds the ApiKey header to the connection' do
54+
expect(client.transport.connections.first.connection.headers['Authorization']).to eq('ApiKey an_api_key')
55+
end
56+
end
57+
58+
context 'when an un-encoded api_key is provided' do
59+
let(:client) do
60+
described_class.new(api_key: {id: 'my_id', api_key: 'my_api_key'})
61+
end
62+
63+
it 'Adds the ApiKey header to the connection' do
64+
expect(
65+
client.transport.connections.first.connection.headers['Authorization']
66+
).to eq("ApiKey #{Base64.encode64('my_id:my_api_key')}")
67+
end
68+
end
69+
4870
describe 'adapter' do
4971

5072
context 'when no adapter is specified' do

0 commit comments

Comments
 (0)