From 8645ac04a8d6b4fedef5a5c4cffb0b1e83595855 Mon Sep 17 00:00:00 2001 From: Dane Strandboge <136023093+DStrand1@users.noreply.github.com> Date: Thu, 9 Jan 2025 03:00:36 -0700 Subject: [PATCH] fix(outputs.influxdb_v2): Allow overriding auth and agent headers (#16383) --- plugins/outputs/influxdb_v2/http.go | 20 ++++++++++++-------- plugins/outputs/influxdb_v2/http_test.go | 16 ++++++++++++++++ 2 files changed, 28 insertions(+), 8 deletions(-) diff --git a/plugins/outputs/influxdb_v2/http.go b/plugins/outputs/influxdb_v2/http.go index 8a622a5f4..23562be9e 100644 --- a/plugins/outputs/influxdb_v2/http.go +++ b/plugins/outputs/influxdb_v2/http.go @@ -70,17 +70,21 @@ type httpClient struct { } func (c *httpClient) Init() error { - token, err := c.token.Get() - if err != nil { - return fmt.Errorf("getting token failed: %w", err) - } - if c.headers == nil { c.headers = make(map[string]string, 2) } - c.headers["Authorization"] = "Token " + token.String() - token.Destroy() - c.headers["User-Agent"] = c.userAgent + + if _, ok := c.headers["Authorization"]; !ok { + token, err := c.token.Get() + if err != nil { + return fmt.Errorf("getting token failed: %w", err) + } + c.headers["Authorization"] = "Token " + token.String() + token.Destroy() + } + if _, ok := c.headers["User-Agent"]; !ok { + c.headers["User-Agent"] = c.userAgent + } var proxy func(*http.Request) (*url.URL, error) if c.proxy != nil { diff --git a/plugins/outputs/influxdb_v2/http_test.go b/plugins/outputs/influxdb_v2/http_test.go index 278e9d45b..dc23d3743 100644 --- a/plugins/outputs/influxdb_v2/http_test.go +++ b/plugins/outputs/influxdb_v2/http_test.go @@ -187,6 +187,22 @@ func TestExponentialBackoffCalculationWithRetryAfter(t *testing.T) { } } +func TestHeadersDoNotOverrideConfig(t *testing.T) { + testURL, err := url.Parse("https://localhost:8181") + require.NoError(t, err) + c := &httpClient{ + headers: map[string]string{ + "Authorization": "Bearer foo", + "User-Agent": "foo", + }, + // URL to make Init() happy + url: testURL, + } + require.NoError(t, c.Init()) + require.Equal(t, "Bearer foo", c.headers["Authorization"]) + require.Equal(t, "foo", c.headers["User-Agent"]) +} + // goos: linux // goarch: amd64 // pkg: github.com/influxdata/telegraf/plugins/outputs/influxdb_v2