Skip to content

Commit 90bf27d

Browse files
committed
normalise hosts to URI::Generics, which reliably preserve defaults
An upstream bug in the Elasticsearch Ruby Client's handling of `String` host arguments that begin with a schema (e.g., `https://localhost`) causes it to default to port 80 or 443, depending on the schema, instead of Elasticsearch's port 9200. Since the Elasticsearch Ruby Client will accept a `URI` in this case, and will correctly handle falling through to appropriate defaults, we normalise to `URI::Generic`, which does not have a default port. We absorb the `ssl => true` case into this normalisation, as its previous implementation prevented the use of non-default ports in the array provided to `hosts`. We also add support for IPv6 addresses, requiring a square-bracketed notation when used in conjunction with a specified port. (see: RFC-3986) Supersedes: #104 Resolves: #110 Resolves: #111
1 parent a8ae485 commit 90bf27d

File tree

4 files changed

+271
-12
lines changed

4 files changed

+271
-12
lines changed

docs/index.asciidoc

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -221,6 +221,12 @@ fields => {
221221

222222
* Value type is <<array,array>>
223223
* Default value is `["localhost:9200"]`
224+
* Format for each entry is one of:
225+
- a valid RFC3986 URI with scheme, hostname, and optional port
226+
- an ipv4 address, optionally followed by a colon and port number
227+
- a hostname, optionally followed by a colon and port number
228+
- a square-bracketed ipv6 address, optionally followed by a colon and port number
229+
- a bare ipv6 address
224230

225231
List of elasticsearch hosts to use for querying.
226232

@@ -281,7 +287,9 @@ Comma-delimited list of `<field>:<direction>` pairs that define the sort order
281287
* Value type is <<boolean,boolean>>
282288
* Default value is `false`
283289

284-
SSL
290+
Force SSL/TLS secured communication to Elasticsearch cluster.
291+
Leaving this unspecified will use whatever scheme is specified in the URLs listed in <<plugins-{type}s-{plugin}-hosts>>, where mixed schemes are supported.
292+
If SSL is set to `true`, the plugin will refuse to start if any of the hosts specifies an `http://` scheme.
285293

286294
[id="plugins-{type}s-{plugin}-tag_on_failure"]
287295
===== `tag_on_failure`

lib/logstash/filters/elasticsearch.rb

Lines changed: 69 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,8 @@ def register
7171
@query_dsl = file.read
7272
end
7373

74+
@normalised_hosts = normalise_hosts(@hosts, @ssl)
75+
7476
test_connection!
7577
end # def register
7678

@@ -140,8 +142,7 @@ def filter(event)
140142
private
141143
def client_options
142144
{
143-
:ssl => @ssl,
144-
:hosts => @hosts,
145+
:hosts => @normalised_hosts,
145146
:ca_file => @ca_file,
146147
:logger => @logger
147148
}
@@ -191,4 +192,70 @@ def extract_total_from_hits(hits)
191192
def test_connection!
192193
get_client.client.ping
193194
end
195+
196+
private
197+
198+
PATTERN_START_WITH_URI_SCHEME =
199+
%r{\A[[:alpha:]][[:alnum:]\.\+\-]*://}i
200+
201+
PATTERN_CAPTURING_HOSTNAME_AND_OPTIONAL_PORT =
202+
%r{\A([^:\[\]]+|\[[^\]]+\])(?::([0-9]+))?\Z}
203+
204+
##
205+
# Map the provided array-of-strings to an array of `URI::Generic`
206+
# instances, which the Elasticsearch client can use to establish
207+
# connections.
208+
#
209+
# @param hosts [Array<String>]: one or more hosts, each is one of:
210+
# - a qualified URL with schema,
211+
# hostname, and optional port
212+
# - a bare hostname or ip, optionally
213+
# followed by a colon and port number
214+
# - a square-bracketed ipv6 literal,
215+
# optionally followed by a colon and port
216+
# number
217+
# - a bare ipv6-address
218+
# @param force_ssl [Boolean]: true to force SSL; will cause failure if one
219+
# or more hosts explicitly supplies non-SSL
220+
# scheme (e.g., `http`).
221+
#
222+
# @return [Array<URI::Generic>]
223+
def normalise_hosts(hosts, force_ssl)
224+
hosts.map do |input|
225+
if force_ssl && input.start_with?('http://')
226+
logger.error("Plugin configured to force SSL with `ssl => true`, " +
227+
"but a host explicitly declared non-https URL `#{input}`")
228+
229+
raise LogStash::ConfigurationError, "Aborting due to conflicting configuration"
230+
end
231+
232+
if PATTERN_START_WITH_URI_SCHEME =~ input
233+
# Avoid `URI::parse`, which routes to specific implementations
234+
# that inject defaults that do not make sense in this context.
235+
URI::Generic.new(*URI.split(input))
236+
else
237+
if PATTERN_CAPTURING_HOSTNAME_AND_OPTIONAL_PORT =~ input
238+
host, port = Regexp.last_match.captures
239+
elsif input =~ Resolv::IPv6::Regex
240+
# per RFC3986: to be used as hostname in URIs, ipv6 literals
241+
# MUST be wrapped in square-brackets.
242+
host, port = "[#{input}]", nil
243+
else
244+
logger.error("Plugin configured with invalid host value `#{input}`")
245+
raise LogStash::ConfigurationError, "Aborting due to invalid configuration"
246+
end
247+
URI::Generic.new(
248+
force_ssl ? 'https' : 'http',
249+
nil, # userinfo,
250+
host,
251+
port,
252+
nil, # registry
253+
nil, # path
254+
nil, # opaque
255+
nil, # query
256+
nil # fragment
257+
)
258+
end
259+
end
260+
end
194261
end #class LogStash::Filters::Elasticsearch

lib/logstash/filters/elasticsearch/client.rb

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,17 +11,15 @@ class ElasticsearchClient
1111
attr_reader :client
1212

1313
def initialize(user, password, options={})
14-
ssl = options.fetch(:ssl, false)
15-
hosts = options[:hosts]
16-
@logger = options[:logger]
14+
hosts = options.fetch(:hosts)
15+
@logger = options.fetch(:logger)
1716

1817
transport_options = {}
1918
if user && password
2019
token = ::Base64.strict_encode64("#{user}:#{password.value}")
2120
transport_options[:headers] = { Authorization: "Basic #{token}" }
2221
end
2322

24-
hosts.map! {|h| { host: h, scheme: 'https' } } if ssl
2523
# set ca_file even if ssl isn't on, since the host can be an https url
2624
ssl_options = { ssl: true, ca_file: options[:ca_file] } if options[:ca_file]
2725
ssl_options ||= {}

spec/filters/elasticsearch_spec.rb

Lines changed: 191 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,199 @@
88

99
context "registration" do
1010

11-
let(:plugin) { LogStash::Plugin.lookup("filter", "elasticsearch").new({}) }
12-
before do
13-
allow(plugin).to receive(:test_connection!)
11+
let(:plugin_class) { LogStash::Plugin.lookup("filter", "elasticsearch") }
12+
let(:plugin) { plugin_class.new(config) }
13+
let(:config) { Hash.new }
14+
15+
context 'with defaults' do
16+
before do
17+
allow(plugin).to receive(:test_connection!)
18+
end
19+
20+
it "should not raise an exception" do
21+
expect {plugin.register}.to_not raise_error
22+
end
1423
end
1524

16-
it "should not raise an exception" do
17-
expect {plugin.register}.to_not raise_error
25+
context 'hosts' do
26+
let(:config) do
27+
super().merge(
28+
'hosts' => hosts
29+
)
30+
end
31+
let(:hosts) do
32+
fail NotImplementedError, 'spec or spec group must define `hosts`.'
33+
end
34+
35+
let(:client_stub) { double(:client).as_null_object }
36+
let(:logger_stub) { double(:logger).as_null_object }
37+
38+
before(:each) do
39+
allow(plugin).to receive(:logger).and_return(logger_stub)
40+
end
41+
42+
context 'with schema://hostname' do
43+
let(:hosts) { ['http://foo.local', 'http://bar.local'] }
44+
45+
it 'creates client with URIs that do not include a port' do
46+
expect(::Elasticsearch::Client).to receive(:new) do |options|
47+
expect(options).to include :hosts
48+
expect(options[:hosts]).to be_an Array
49+
expect(options[:hosts]).to include(having_attributes(host: 'foo.local', scheme: 'http', port: nil))
50+
expect(options[:hosts]).to include(having_attributes(host: 'bar.local', scheme: 'http', port: nil))
51+
end.and_return(client_stub)
52+
53+
plugin.register
54+
end
55+
end
56+
57+
context 'with `ssl => true`' do
58+
let(:config) { super().merge('ssl' => 'true') }
59+
context 'and one or more explicitly-http hosts' do
60+
let(:hosts) { ['https://foo.local', 'http://bar.local'] }
61+
62+
it 'raises an exception' do
63+
expect { plugin.register }.to raise_error(LogStash::ConfigurationError)
64+
end
65+
66+
it 'emits a helpful log message' do
67+
plugin.register rescue nil
68+
expect(plugin.logger).to have_received(:error).with(match(/force SSL/))
69+
end
70+
end
71+
72+
context 'and all explicitly-https hosts' do
73+
let(:hosts) { ['https://foo.local', 'https://bar.local'] }
74+
75+
it 'sets the schemas on all to https' do
76+
expect(::Elasticsearch::Client).to receive(:new) do |options|
77+
expect(options).to include :hosts
78+
expect(options[:hosts]).to be_an Array
79+
options[:hosts].each do |host|
80+
expect(host).to be_an URI
81+
expect(host.scheme).to eq 'https'
82+
end
83+
end.and_return(client_stub)
84+
85+
plugin.register
86+
end
87+
end
88+
89+
context 'and one or more schemaless hosts' do
90+
let(:hosts) { ['https://foo.local', 'bar.local'] }
91+
92+
it 'sets the schemas on all to https' do
93+
expect(::Elasticsearch::Client).to receive(:new) do |options|
94+
expect(options).to include :hosts
95+
expect(options[:hosts]).to be_an Array
96+
options[:hosts].each do |host|
97+
expect(host).to be_an URI
98+
expect(host.scheme).to eq 'https'
99+
end
100+
end.and_return(client_stub)
101+
102+
plugin.register
103+
end
104+
end
105+
106+
context 'with one or more ipv6 hostnames' do
107+
let(:hosts) { ['[::1]', '[::2]:9201', 'https://[::3]:9202', '::4'] }
108+
it 'defaults to the http protocol' do
109+
expect(::Elasticsearch::Client).to receive(:new) do |options|
110+
expect(options).to include :hosts
111+
expect(options[:hosts]).to be_an Array
112+
expect(options[:hosts]).to include(having_attributes(scheme: 'https', host: '[::1]', port: nil))
113+
expect(options[:hosts]).to include(having_attributes(scheme: 'https', host: '[::2]', port: 9201))
114+
expect(options[:hosts]).to include(having_attributes(scheme: 'https', host: '[::3]', port: 9202))
115+
expect(options[:hosts]).to include(having_attributes(scheme: 'https', host: '[::4]', port: nil))
116+
end.and_return(client_stub)
117+
118+
plugin.register
119+
end
120+
end
121+
end
122+
123+
{
124+
'with `ssl => false' => {'ssl' => 'false'},
125+
'without `ssl` directive' => {}
126+
}.each do |context_string, config_override|
127+
context(context_string) do
128+
let(:config) { super().merge(config_override) }
129+
130+
context 'with a mix of http and https hosts' do
131+
let(:hosts) { ['https://foo.local', 'http://bar.local'] }
132+
it 'does not modify the protocol' do
133+
expect(::Elasticsearch::Client).to receive(:new) do |options|
134+
expect(options).to include :hosts
135+
expect(options[:hosts]).to be_an Array
136+
expect(options[:hosts]).to include(having_attributes(scheme: 'https', host: 'foo.local', port: nil))
137+
expect(options[:hosts]).to include(having_attributes(scheme: 'http', host: 'bar.local', port: nil))
138+
end.and_return(client_stub)
139+
140+
plugin.register
141+
end
142+
end
143+
144+
context 'with https-only hosts' do
145+
let(:hosts) { ['https://foo.local', 'https://bar.local'] }
146+
it 'does not modify the protocol' do
147+
expect(::Elasticsearch::Client).to receive(:new) do |options|
148+
expect(options).to include :hosts
149+
expect(options[:hosts]).to be_an Array
150+
expect(options[:hosts]).to include(having_attributes(scheme: 'https', host: 'foo.local', port: nil))
151+
expect(options[:hosts]).to include(having_attributes(scheme: 'https', host: 'bar.local', port: nil))
152+
end.and_return(client_stub)
153+
154+
plugin.register
155+
end
156+
end
157+
158+
context 'with http-only hosts' do
159+
let(:hosts) { ['http://foo.local', 'http://bar.local'] }
160+
it 'does not modify the protocol' do
161+
expect(::Elasticsearch::Client).to receive(:new) do |options|
162+
expect(options).to include :hosts
163+
expect(options[:hosts]).to be_an Array
164+
expect(options[:hosts]).to include(having_attributes(scheme: 'http', host: 'foo.local', port: nil))
165+
expect(options[:hosts]).to include(having_attributes(scheme: 'http', host: 'bar.local', port: nil))
166+
end.and_return(client_stub)
167+
168+
plugin.register
169+
end
170+
end
171+
172+
context 'with one or more schemaless hosts' do
173+
let(:hosts) { ['foo.local', 'bar.local' ] }
174+
it 'defaults to the http protocol' do
175+
expect(::Elasticsearch::Client).to receive(:new) do |options|
176+
expect(options).to include :hosts
177+
expect(options[:hosts]).to be_an Array
178+
expect(options[:hosts]).to include(having_attributes(scheme: 'http', host: 'foo.local', port: nil))
179+
expect(options[:hosts]).to include(having_attributes(scheme: 'http', host: 'bar.local', port: nil))
180+
end.and_return(client_stub)
181+
182+
plugin.register
183+
end
184+
end
185+
186+
context 'with one or more square-bracketed ipv6 literals' do
187+
let(:hosts) { ['[::1]', '[::2]:9201', 'http://[::3]','https://[::4]:9202', '::5'] }
188+
it 'defaults to the http protocol' do
189+
expect(::Elasticsearch::Client).to receive(:new) do |options|
190+
expect(options).to include :hosts
191+
expect(options[:hosts]).to be_an Array
192+
expect(options[:hosts]).to include(having_attributes(scheme: 'http', host: '[::1]', port: nil))
193+
expect(options[:hosts]).to include(having_attributes(scheme: 'http', host: '[::2]', port: 9201))
194+
expect(options[:hosts]).to include(having_attributes(scheme: 'http', host: '[::3]', port: nil))
195+
expect(options[:hosts]).to include(having_attributes(scheme: 'https', host: '[::4]', port: 9202))
196+
expect(options[:hosts]).to include(having_attributes(scheme: 'http', host: '[::5]', port: nil))
197+
end.and_return(client_stub)
198+
199+
plugin.register
200+
end
201+
end
202+
end
203+
end
18204
end
19205
end
20206

0 commit comments

Comments
 (0)