Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added basic authentication support to the http_response input plugin #7491

Merged
merged 5 commits into from
May 12, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 34 additions & 8 deletions plugins/inputs/http_response/http_response.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,21 @@ import (

// HTTPResponse struct
type HTTPResponse struct {
Address string // deprecated in 1.12
URLs []string `toml:"urls"`
HTTPProxy string `toml:"http_proxy"`
Body string
Method string
ResponseTimeout internal.Duration
Headers map[string]string
FollowRedirects bool
Address string // deprecated in 1.12
URLs []string `toml:"urls"`
HTTPProxy string `toml:"http_proxy"`
Body string
Method string
ResponseTimeout internal.Duration
Headers map[string]string
FollowRedirects bool
// Absolute path to file with Bearer token
BearerToken string `toml:"bearer_token"`
ResponseStringMatch string
Interface string
// HTTP Basic Auth Credentials
Username string `toml:"username"`
Password string `toml:"password"`
tls.ClientConfig

Log telegraf.Logger
Expand Down Expand Up @@ -64,6 +69,14 @@ var sampleConfig = `
## Whether to follow redirects from the server (defaults to false)
# follow_redirects = false

## Optional file with Bearer token
## file content is added as an Authorization header
# bearer_token = "/path/to/file"

## Optional HTTP Basic Auth Credentials
# username = "username"
# password = "pa$$word"

## Optional HTTP Request Body
# body = '''
# {'fake':'data'}
Expand Down Expand Up @@ -227,13 +240,26 @@ func (h *HTTPResponse) httpGather(u string) (map[string]interface{}, map[string]
return nil, nil, err
}

if h.BearerToken != "" {
token, err := ioutil.ReadFile(h.BearerToken)
if err != nil {
return nil, nil, err
}
bearer := "Bearer " + strings.Trim(string(token), "\n")
request.Header.Add("Authorization", bearer)
}

for key, val := range h.Headers {
request.Header.Add(key, val)
if key == "Host" {
request.Host = val
}
}

if h.Username != "" || h.Password != "" {
request.SetBasicAuth(h.Username, h.Password)
}

// Start Timer
start := time.Now()
resp, err := h.client.Do(request)
Expand Down
42 changes: 42 additions & 0 deletions plugins/inputs/http_response/http_response_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -864,3 +864,45 @@ func TestRedirect(t *testing.T) {

testutil.RequireMetricsEqual(t, expected, actual, testutil.IgnoreTime())
}

func TestBasicAuth(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
aHeader := r.Header.Get("Authorization")
assert.Equal(t, "Basic bWU6bXlwYXNzd29yZA==", aHeader)
w.WriteHeader(http.StatusOK)
}))
defer ts.Close()

h := &HTTPResponse{
Log: testutil.Logger{},
Address: ts.URL + "/good",
Body: "{ 'test': 'data'}",
Method: "GET",
ResponseTimeout: internal.Duration{Duration: time.Second * 20},
Username: "me",
Password: "mypassword",
Headers: map[string]string{
"Content-Type": "application/json",
},
}

var acc testutil.Accumulator
err := h.Gather(&acc)
require.NoError(t, err)

expectedFields := map[string]interface{}{
"http_response_code": http.StatusOK,
"result_type": "success",
"result_code": 0,
"response_time": nil,
"content_length": nil,
}
expectedTags := map[string]interface{}{
"server": nil,
"method": "GET",
"status_code": "200",
"result": "success",
}
absentFields := []string{"response_string_match"}
checkOutput(t, &acc, expectedFields, expectedTags, absentFields, nil)
}