Path: blob/main/component/otelcol/auth/bearer/bearer_test.go
5414 views
package bearer_test12import (3"context"4"net/http"5"net/http/httptest"6"testing"7"time"89"github.com/grafana/agent/component/otelcol/auth"10"github.com/grafana/agent/component/otelcol/auth/bearer"11"github.com/grafana/agent/pkg/flow/componenttest"12"github.com/grafana/agent/pkg/river"13"github.com/grafana/agent/pkg/util"14"github.com/stretchr/testify/assert"15"github.com/stretchr/testify/require"16"go.opentelemetry.io/collector/config/configauth"17)1819// Test performs a basic integration test which runs the otelcol.auth.bearer20// component and ensures that it can be used for authentication.21func Test(t *testing.T) {22// Create an HTTP server which will assert that bearer auth has been injected23// into the request.24srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {25authHeader := r.Header.Get("Authorization")26assert.Equal(t, "Bearer foobar", authHeader, "auth header didn't match")2728w.WriteHeader(http.StatusOK)29}))30defer srv.Close()3132ctx := componenttest.TestContext(t)33ctx, cancel := context.WithTimeout(ctx, time.Minute)34defer cancel()3536l := util.TestLogger(t)3738// Create and run our component39ctrl, err := componenttest.NewControllerFromID(l, "otelcol.auth.bearer")40require.NoError(t, err)4142cfg := `43token = "foobar"44`45var args bearer.Arguments46require.NoError(t, river.Unmarshal([]byte(cfg), &args))4748go func() {49err := ctrl.Run(ctx, args)50require.NoError(t, err)51}()5253require.NoError(t, ctrl.WaitRunning(time.Second), "component never started")54require.NoError(t, ctrl.WaitExports(time.Second), "component never exported anything")5556// Get the authentication extension from our component and use it to make a57// request to our test server.58exports := ctrl.Exports().(auth.Exports)59require.NotNil(t, exports.Handler.Extension, "handler extension is nil")6061clientAuth, ok := exports.Handler.Extension.(configauth.ClientAuthenticator)62require.True(t, ok, "handler does not implement configauth.ClientAuthenticator")6364rt, err := clientAuth.RoundTripper(http.DefaultTransport)65require.NoError(t, err)66cli := &http.Client{Transport: rt}6768// Wait until the request finishes. We don't assert anything else here; our69// HTTP handler won't write the response until it ensures that the bearer70// auth was found.71req, err := http.NewRequestWithContext(ctx, http.MethodGet, srv.URL, nil)72require.NoError(t, err)73resp, err := cli.Do(req)74require.NoError(t, err, "HTTP request failed")75require.Equal(t, http.StatusOK, resp.StatusCode)76}777879