File tree Expand file tree Collapse file tree 2 files changed +36
-0
lines changed
lib/elasticsearch/transport
spec/elasticsearch/transport Expand file tree Collapse file tree 2 files changed +36
-0
lines changed Original file line number Diff line number Diff line change @@ -109,6 +109,13 @@ def initialize(arguments={}, &block)
109
109
110
110
@send_get_body_as = @arguments [ :send_get_body_as ] || 'GET'
111
111
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
+
112
119
if @arguments [ :request_timeout ]
113
120
@arguments [ :transport_options ] [ :request ] = { :timeout => @arguments [ :request_timeout ] }
114
121
end
@@ -232,6 +239,13 @@ def __auto_detect_adapter
232
239
::Faraday . default_adapter
233
240
end
234
241
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
235
249
end
236
250
end
237
251
end
Original file line number Diff line number Diff line change 45
45
expect ( client . transport . hosts [ 0 ] [ :host ] ) . to eq ( 'localhost' )
46
46
end
47
47
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
+
48
70
describe 'adapter' do
49
71
50
72
context 'when no adapter is specified' do
You can’t perform that action at this time.
0 commit comments