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

Allow disabling brearer token override from request in metrics store #4726

Merged
merged 3 commits into from
Sep 6, 2023
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
9 changes: 5 additions & 4 deletions pkg/prometheus/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,11 @@ import (

// Configuration describes the options to customize the storage behavior.
type Configuration struct {
ServerURL string
ConnectTimeout time.Duration
TLS tlscfg.Options
TokenFilePath string
ServerURL string
ConnectTimeout time.Duration
TLS tlscfg.Options
TokenFilePath string
TokenOverrideFromContext bool

SupportSpanmetricsConnector bool
MetricNamespace string
Expand Down
2 changes: 2 additions & 0 deletions plugin/metrics/prometheus/factory_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,12 +76,14 @@ func TestWithConfiguration(t *testing.T) {
"--prometheus.server-url=http://localhost:1234",
"--prometheus.connect-timeout=5s",
"--prometheus.token-file=test/test_file.txt",
"--prometheus.token-override-from-context=false",
})
require.NoError(t, err)
f.InitFromViper(v, zap.NewNop())
assert.Equal(t, "http://localhost:1234", f.options.Primary.ServerURL)
assert.Equal(t, 5*time.Second, f.options.Primary.ConnectTimeout)
assert.Equal(t, "test/test_file.txt", f.options.Primary.TokenFilePath)
assert.Equal(t, false, f.options.Primary.TokenOverrideFromContext)
})
t.Run("with space in token file path", func(t *testing.T) {
f := NewFactory()
Expand Down
2 changes: 1 addition & 1 deletion plugin/metrics/prometheus/metricsstore/reader.go
Original file line number Diff line number Diff line change
Expand Up @@ -335,7 +335,7 @@ func getHTTPRoundTripper(c *config.Configuration, logger *zap.Logger) (rt http.R
}
return bearertoken.RoundTripper{
Transport: httpTransport,
OverrideFromCtx: true,
OverrideFromCtx: c.TokenOverrideFromContext,
StaticToken: token,
}, nil
}
Expand Down
45 changes: 41 additions & 4 deletions plugin/metrics/prometheus/metricsstore/reader_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -533,6 +533,7 @@ func TestGetRoundTripperTLSConfig(t *testing.T) {
TLS: tlscfg.Options{
Enabled: tc.tlsEnabled,
},
TokenOverrideFromContext: true,
}, logger)
require.NoError(t, err)

Expand Down Expand Up @@ -560,7 +561,7 @@ func TestGetRoundTripperTLSConfig(t *testing.T) {
}
}

func TestGetRoundTripperToken(t *testing.T) {
func TestGetRoundTripperTokenFile(t *testing.T) {
const wantBearer = "token from file"

file, err := os.CreateTemp("", "token_")
Expand All @@ -572,8 +573,9 @@ func TestGetRoundTripperToken(t *testing.T) {
require.NoError(t, file.Close())

rt, err := getHTTPRoundTripper(&config.Configuration{
ConnectTimeout: time.Second,
TokenFilePath: file.Name(),
ConnectTimeout: time.Second,
TokenFilePath: file.Name(),
TokenOverrideFromContext: false,
}, nil)
require.NoError(t, err)
server := httptest.NewServer(
Expand All @@ -584,7 +586,42 @@ func TestGetRoundTripperToken(t *testing.T) {
),
)
defer server.Close()
ctx := context.Background()
ctx := bearertoken.ContextWithBearerToken(context.Background(), "tokenFromRequest")
req, err := http.NewRequestWithContext(
ctx,
http.MethodGet,
server.URL,
nil,
)
require.NoError(t, err)
resp, err := rt.RoundTrip(req)
require.NoError(t, err)
assert.Equal(t, http.StatusOK, resp.StatusCode)
}

func TestGetRoundTripperTokenFromContext(t *testing.T) {
file, err := os.CreateTemp("", "token_")
require.NoError(t, err)
defer func() { assert.NoError(t, os.Remove(file.Name())) }()
_, err = file.Write([]byte("token from file"))
require.NoError(t, err)
require.NoError(t, file.Close())

rt, err := getHTTPRoundTripper(&config.Configuration{
ConnectTimeout: time.Second,
TokenFilePath: file.Name(),
TokenOverrideFromContext: true,
}, nil)
require.NoError(t, err)
server := httptest.NewServer(
http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, "Bearer tokenFromRequest", r.Header.Get("Authorization"))
},
),
)
defer server.Close()
ctx := bearertoken.ContextWithBearerToken(context.Background(), "tokenFromRequest")
req, err := http.NewRequestWithContext(
ctx,
http.MethodGet,
Expand Down
10 changes: 7 additions & 3 deletions plugin/metrics/prometheus/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,10 @@ import (
)

const (
suffixServerURL = ".server-url"
suffixConnectTimeout = ".connect-timeout"
suffixTokenFilePath = ".token-file"
suffixServerURL = ".server-url"
suffixConnectTimeout = ".connect-timeout"
suffixTokenFilePath = ".token-file"
suffixOverrideFromContext = ".token-override-from-context"

suffixSupportSpanmetricsConnector = ".query.support-spanmetrics-connector"
suffixMetricNamespace = ".query.namespace"
Expand Down Expand Up @@ -88,6 +89,8 @@ func (opt *Options) AddFlags(flagSet *flag.FlagSet) {
"The period to wait for a connection to Prometheus when executing queries.")
flagSet.String(nsConfig.namespace+suffixTokenFilePath, defaultTokenFilePath,
"The path to a file containing the bearer token which will be included when executing queries against the Prometheus API.")
flagSet.Bool(nsConfig.namespace+suffixOverrideFromContext, true,
"Whether the bearer token should be overridden from context (incoming request)")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the phrasing is a bit confusing to me. In terms of functionality, it seems a priority list would be a more elegant solution that covers more use cases, e.g., e.g. --token-priority=context,file or --token-priority=file (the latter will achieve what this PR needs I think)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The priority is not supported by our bearertoken package

if tr.OverrideFromCtx {

I don't need the priority. I want to for the transport to always use the token regardless of what is in the context.


flagSet.Bool(nsConfig.namespace+suffixSupportSpanmetricsConnector, defaultSupportSpanmetricsConnector,
`Whether if queries should be adjusted for OpenTelemetry Collector's spanmetrics connector.'`)
Expand Down Expand Up @@ -125,6 +128,7 @@ func (opt *Options) InitFromViper(v *viper.Viper) error {
cfg.LatencyUnit = v.GetString(cfg.namespace + suffixLatencyUnit)
cfg.NormalizeCalls = v.GetBool(cfg.namespace + suffixNormalizeCalls)
cfg.NormalizeDuration = v.GetBool(cfg.namespace + suffixNormalizeDuration)
cfg.TokenOverrideFromContext = v.GetBool(cfg.namespace + suffixOverrideFromContext)

isValidUnit := map[string]bool{"ms": true, "s": true}
if _, ok := isValidUnit[cfg.LatencyUnit]; !ok {
Expand Down