From 4588257c72c07cf100d192ee549f8721a9da2323 Mon Sep 17 00:00:00 2001 From: Jaime Soriano Pastor Date: Thu, 21 Mar 2019 11:03:43 +0100 Subject: [PATCH] Fix authentication in HTTP helper (#11353) After the refactor done in #11032, baseData was not being passed to the HTTP helper, so authentication was not working. Added a test to avoid regressions here. Fix #11351 --- metricbeat/helper/http.go | 1 + metricbeat/helper/http_test.go | 42 ++++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+) diff --git a/metricbeat/helper/http.go b/metricbeat/helper/http.go index 1f738b97d18..a8d910a1043 100644 --- a/metricbeat/helper/http.go +++ b/metricbeat/helper/http.go @@ -81,6 +81,7 @@ func newHTTPFromConfig(config Config, name string, hostData mb.HostData) (*HTTP, } return &HTTP{ + hostData: hostData, client: &http.Client{ Transport: &http.Transport{ Dial: dialer.Dial, diff --git a/metricbeat/helper/http_test.go b/metricbeat/helper/http_test.go index aee80166fa2..21b4ce69729 100644 --- a/metricbeat/helper/http_test.go +++ b/metricbeat/helper/http_test.go @@ -113,6 +113,48 @@ func TestConnectTimeout(t *testing.T) { checkTimeout(t, h) } +func TestAuthentication(t *testing.T) { + expectedUser := "elastic" + expectedPassword := "super1234" + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + user, password, ok := r.BasicAuth() + if !ok || user != expectedUser || password != expectedPassword { + w.WriteHeader(http.StatusUnauthorized) + } + })) + defer ts.Close() + + cfg := defaultConfig() + + // Unauthorized + hostData := mb.HostData{ + URI: ts.URL, + SanitizedURI: ts.URL, + } + h, err := newHTTPFromConfig(cfg, "test", hostData) + require.NoError(t, err) + + response, err := h.FetchResponse() + response.Body.Close() + assert.NoError(t, err) + assert.Equal(t, http.StatusUnauthorized, response.StatusCode, "response status code") + + // Authorized + hostData = mb.HostData{ + URI: ts.URL, + SanitizedURI: ts.URL, + User: expectedUser, + Password: expectedPassword, + } + h, err = newHTTPFromConfig(cfg, "test", hostData) + require.NoError(t, err) + + response, err = h.FetchResponse() + response.Body.Close() + assert.NoError(t, err) + assert.Equal(t, http.StatusOK, response.StatusCode, "response status code") +} + func checkTimeout(t *testing.T, h *HTTP) { t.Helper()