Skip to content

Support bearerauthtoken header customization #38793

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

Merged
merged 3 commits into from
Mar 28, 2025
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
27 changes: 27 additions & 0 deletions .chloggen/bearerauth-header.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Use this changelog template to create an entry for release notes.

# One of 'breaking', 'deprecation', 'new_component', 'enhancement', 'bug_fix'
change_type: enhancement

# The name of the component, or a single word describing the area of concern, (e.g. filelogreceiver)
component: bearertokenauthextension

# A brief description of the change. Surround your text with quotes ("") if it needs to start with a backtick (`).
note: Allow the header name to be customized in the bearerauthtoken extension

# Mandatory: One or more tracking issues related to the change. You can use the PR number here if no issue exists.
issues: [38793]

# (Optional) One or more lines of additional information to render under the primary note.
# These lines will be padded with 2 spaces and then inserted directly into the document.
# Use pipe (|) for multiline entries.
subtext:

# If your change doesn't affect end users or the exported elements of any package,
# you should instead start your pull request title with [chore] or use the "Skip Changelog" label.
# Optional: The change log or logs in which this entry should be included.
# e.g. '[user]' or '[user, api]'
# Include 'user' if the change is relevant to end users.
# Include 'api' if there is a change to a library API.
# Default: '[user]'
change_logs: [user]
2 changes: 2 additions & 0 deletions extension/bearertokenauthextension/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ The authenticator type has to be set to `bearertokenauth`.

## Configuration

- `header`: Specifies the auth header name. Defaults to "Authorization". Optional.

- `scheme`: Specifies the auth scheme name. Defaults to "Bearer". Optional.

- `token`: Static authorization token that needs to be sent on every gRPC client call as metadata.
Expand Down
15 changes: 9 additions & 6 deletions extension/bearertokenauthextension/bearertokenauth.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ package bearertokenauthextension // import "github.com/open-telemetry/openteleme
import (
"context"
"crypto/subtle"
"errors"
"fmt"
"net/http"
"os"
Expand All @@ -30,7 +29,7 @@ type PerRPCAuth struct {

// GetRequestMetadata returns the request metadata to be used with the RPC.
func (c *PerRPCAuth) GetRequestMetadata(context.Context, ...string) (map[string]string, error) {
return map[string]string{"authorization": c.auth.authorizationValue()}, nil
return map[string]string{strings.ToLower(c.auth.header): c.auth.authorizationValue()}, nil
}

// RequireTransportSecurity always returns true for this implementation. Passing bearer tokens in plain-text connections is a bad idea.
Expand All @@ -47,6 +46,7 @@ var (

// BearerTokenAuth is an implementation of extensionauth interfaces. It embeds a static authorization "bearer" token in every rpc call.
type BearerTokenAuth struct {
header string
scheme string
authorizationValuesAtomic atomic.Value

Expand All @@ -61,6 +61,7 @@ func newBearerTokenAuth(cfg *Config, logger *zap.Logger) *BearerTokenAuth {
logger.Warn("a filename is specified. Configured token(s) is ignored!")
}
a := &BearerTokenAuth{
header: cfg.Header,
scheme: cfg.Scheme,
filename: cfg.Filename,
logger: logger,
Expand Down Expand Up @@ -211,19 +212,20 @@ func (b *BearerTokenAuth) PerRPCCredentials() (credentials.PerRPCCredentials, er
// RoundTripper is not implemented by BearerTokenAuth
func (b *BearerTokenAuth) RoundTripper(base http.RoundTripper) (http.RoundTripper, error) {
return &BearerAuthRoundTripper{
header: b.header,
baseTransport: base,
auth: b,
}, nil
}

// Authenticate checks whether the given context contains valid auth data. Validates tokens from clients trying to access the service (incoming requests)
func (b *BearerTokenAuth) Authenticate(ctx context.Context, headers map[string][]string) (context.Context, error) {
auth, ok := headers["authorization"]
auth, ok := headers[strings.ToLower(b.header)]
if !ok {
auth, ok = headers["Authorization"]
auth, ok = headers[b.header]
}
if !ok || len(auth) == 0 {
return ctx, errors.New("missing or empty authorization header")
return ctx, fmt.Errorf("missing or empty authorization header: %s", b.header)
}
token := auth[0] // Extract token from authorization header
expectedTokens := b.authorizationValues()
Expand All @@ -237,6 +239,7 @@ func (b *BearerTokenAuth) Authenticate(ctx context.Context, headers map[string][

// BearerAuthRoundTripper intercepts and adds Bearer token Authorization headers to each http request.
type BearerAuthRoundTripper struct {
header string
baseTransport http.RoundTripper
auth *BearerTokenAuth
}
Expand All @@ -247,6 +250,6 @@ func (interceptor *BearerAuthRoundTripper) RoundTrip(req *http.Request) (*http.R
if req2.Header == nil {
req2.Header = make(http.Header)
}
req2.Header.Set("Authorization", interceptor.auth.authorizationValue())
req2.Header.Set(interceptor.header, interceptor.auth.authorizationValue())
return interceptor.baseTransport.RoundTrip(req2)
}
63 changes: 63 additions & 0 deletions extension/bearertokenauthextension/bearertokenauth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"net/http"
"os"
"path/filepath"
"strings"
"testing"
"time"

Expand Down Expand Up @@ -384,3 +385,65 @@ func TestBearerTokenMultipleTokensInFile(t *testing.T) {

assert.NoError(t, bauth.Shutdown(context.Background()))
}

func TestCustomHeaderRoundTrip(t *testing.T) {
cfg := createDefaultConfig().(*Config)
cfg.Header = "X-Custom-Authorization"
cfg.Scheme = ""
cfg.BearerToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."

bauth := newBearerTokenAuth(cfg, nil)
assert.NotNil(t, bauth)

base := &mockRoundTripper{}
c, err := bauth.RoundTripper(base)
assert.NoError(t, err)
assert.NotNil(t, c)

request := &http.Request{Method: http.MethodGet}
resp, err := c.RoundTrip(request)
assert.NoError(t, err)
authHeaderValue := resp.Header.Get(cfg.Header)
assert.Equal(t, authHeaderValue, string(cfg.BearerToken))
}

func TestCustomHeaderGetRequestMetadata(t *testing.T) {
cfg := createDefaultConfig().(*Config)
cfg.Header = "X-Custom-Authorization"
cfg.Scheme = ""
cfg.BearerToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."

bauth := newBearerTokenAuth(cfg, nil)
assert.NotNil(t, bauth)

assert.NoError(t, bauth.Start(context.Background(), componenttest.NewNopHost()))
credential, err := bauth.PerRPCCredentials()

assert.NoError(t, err)
assert.NotNil(t, credential)

md, err := credential.GetRequestMetadata(context.Background())
expectedMd := map[string]string{
strings.ToLower(cfg.Header): string(cfg.BearerToken),
}
assert.Equal(t, expectedMd, md)
assert.NoError(t, err)
}

func TestCustomHeaderAuthenticate(t *testing.T) {
cfg := createDefaultConfig().(*Config)
cfg.Header = "X-Custom-Authorization"
cfg.Scheme = ""
cfg.BearerToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."

bauth := newBearerTokenAuth(cfg, nil)
assert.NotNil(t, bauth)

ctx := context.Background()
assert.NoError(t, bauth.Start(ctx, componenttest.NewNopHost()))

_, err := bauth.Authenticate(ctx, map[string][]string{cfg.Header: {string(cfg.BearerToken)}})
assert.NoError(t, err)

assert.NoError(t, bauth.Shutdown(context.Background()))
}
3 changes: 3 additions & 0 deletions extension/bearertokenauthextension/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ import (

// Config specifies how the Per-RPC bearer token based authentication data should be obtained.
type Config struct {
// Header specifies the auth-header for the token. Defaults to "Authorization"
Header string `mapstructure:"header,omitempty"`

// Scheme specifies the auth-scheme for the token. Defaults to "Bearer"
Scheme string `mapstructure:"scheme,omitempty"`

Expand Down
16 changes: 16 additions & 0 deletions extension/bearertokenauthextension/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,34 +32,39 @@ func TestLoadConfig(t *testing.T) {
{
id: component.NewIDWithName(metadata.Type, "sometoken"),
expected: &Config{
Header: defaultHeader,
Scheme: defaultScheme,
BearerToken: "sometoken",
},
},
{
id: component.NewIDWithName(metadata.Type, "withscheme"),
expected: &Config{
Header: defaultHeader,
Scheme: "MyScheme",
BearerToken: "my-token",
},
},
{
id: component.NewIDWithName(metadata.Type, "multipletokens"),
expected: &Config{
Header: defaultHeader,
Scheme: "Bearer",
Tokens: []configopaque.String{"token1", "thistokenalsoworks"},
},
},
{
id: component.NewIDWithName(metadata.Type, "withfilename"),
expected: &Config{
Header: defaultHeader,
Scheme: "Bearer",
Filename: "file-containing.token",
},
},
{
id: component.NewIDWithName(metadata.Type, "both"),
expected: &Config{
Header: defaultHeader,
Scheme: "Bearer",
BearerToken: "ignoredtoken",
Filename: "file-containing.token",
Expand All @@ -68,6 +73,7 @@ func TestLoadConfig(t *testing.T) {
{
id: component.NewIDWithName(metadata.Type, "tokensandtoken"),
expected: &Config{
Header: defaultHeader,
Scheme: "Bearer",
BearerToken: "sometoken",
Tokens: []configopaque.String{"token1", "thistokenalsoworks"},
Expand All @@ -77,12 +83,22 @@ func TestLoadConfig(t *testing.T) {
{
id: component.NewIDWithName(metadata.Type, "withtokensandfilename"),
expected: &Config{
Header: defaultHeader,
Scheme: "Bearer",
Tokens: []configopaque.String{"ignoredtoken1", "ignoredtoken2"},
Filename: "file-containing.token",
},
},
{
id: component.NewIDWithName(metadata.Type, "withheader"),
expected: &Config{
Header: "X-Custom-Authorization",
Scheme: "",
BearerToken: "my-token",
},
},
}

for _, tt := range tests {
t.Run(tt.id.String(), func(t *testing.T) {
cm, err := confmaptest.LoadConf(filepath.Join("testdata", "config.yaml"))
Expand Down
2 changes: 2 additions & 0 deletions extension/bearertokenauthextension/factory.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
)

const (
defaultHeader = "Authorization"
defaultScheme = "Bearer"
)

Expand All @@ -28,6 +29,7 @@ func NewFactory() extension.Factory {

func createDefaultConfig() component.Config {
return &Config{
Header: defaultHeader,
Scheme: defaultScheme,
}
}
Expand Down
2 changes: 1 addition & 1 deletion extension/bearertokenauthextension/factory_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import (

func TestFactory_CreateDefaultConfig(t *testing.T) {
cfg := createDefaultConfig()
assert.Equal(t, &Config{Scheme: defaultScheme}, cfg)
assert.Equal(t, &Config{Header: defaultHeader, Scheme: defaultScheme}, cfg)
assert.NoError(t, componenttest.CheckConfigStruct(cfg))
}

Expand Down
4 changes: 4 additions & 0 deletions extension/bearertokenauthextension/testdata/config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,7 @@ bearertokenauth/tokensandtoken:
- "token1"
- "thistokenalsoworks"
token: "my-token"
bearertokenauth/withheader:
header: "X-Custom-Authorization"
scheme: ""
token: "my-token"
Loading