Skip to content

[extension/header_setter] Expose auth attributes #38441

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 12, 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/feature-headersetter-auth-attr.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: headersetterextension

# A brief description of the change. Surround your text with quotes ("") if it needs to start with a backtick (`).
note: Add support for setting headers based on authentication data

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

# (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]
4 changes: 3 additions & 1 deletion extension/headerssetterextension/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,10 @@ The following settings are required:
- `from_context`: The header value is looked up from the request metadata,
such as HTTP headers, using the property value as the key (likely a header
name).
- `from_attribute`: The header value is taken from the request's authentication data,
may include attributes like `subject` and `membership`.

The `value` and `from_context,default_value` properties are mutually exclusive.
The `value`,`from_context,default_value` and `from_attribute,default_value` properties are mutually exclusive.

In order for `from_context` to work, other components in the pipeline also need to be configured appropriately:
* If a [batch processor][batch-processor] is present in the pipeline, it must be configured to [preserve client metadata][batch-processor-preserve-metadata].
Expand Down
21 changes: 12 additions & 9 deletions extension/headerssetterextension/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,20 +10,21 @@ import (
var (
errMissingHeader = fmt.Errorf("missing header name")
errMissingHeadersConfig = fmt.Errorf("missing headers configuration")
errMissingSource = fmt.Errorf("missing header source, must be 'from_context' or 'value'")
errConflictingSources = fmt.Errorf("invalid header source, must either 'from_context' or 'value'")
errMissingSource = fmt.Errorf("missing header source, must be 'from_context', 'from_attribute' or 'value'")
errConflictingSources = fmt.Errorf("invalid header source, must either 'from_context', 'from_attribute' or 'value'")
)

type Config struct {
HeadersConfig []HeaderConfig `mapstructure:"headers"`
}

type HeaderConfig struct {
Action ActionValue `mapstructure:"action"`
Key *string `mapstructure:"key"`
Value *string `mapstructure:"value"`
FromContext *string `mapstructure:"from_context"`
DefaultValue *string `mapstructure:"default_value"`
Action ActionValue `mapstructure:"action"`
Key *string `mapstructure:"key"`
Value *string `mapstructure:"value"`
FromContext *string `mapstructure:"from_context"`
FromAttribute *string `mapstructure:"from_attribute"`
DefaultValue *string `mapstructure:"default_value"`
}

// ActionValue is the enum to capture the four types of actions to perform on a header
Expand Down Expand Up @@ -55,10 +56,12 @@ func (cfg *Config) Validate() error {
}

if header.Action != DELETE {
if header.FromContext == nil && header.Value == nil {
if header.FromContext == nil && header.FromAttribute == nil && header.Value == nil {
return errMissingSource
}
if header.FromContext != nil && header.Value != nil {
if (header.FromContext != nil && header.FromAttribute != nil) ||
(header.FromContext != nil && header.Value != nil) ||
(header.Value != nil && header.FromAttribute != nil) {
return errConflictingSources
}
}
Expand Down
14 changes: 12 additions & 2 deletions extension/headerssetterextension/extension.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,21 @@ func newHeadersSetterExtension(cfg *Config, logger *zap.Logger) (extensionauth.C
headers := make([]Header, 0, len(cfg.HeadersConfig))
for _, header := range cfg.HeadersConfig {
var s source.Source
if header.Value != nil {
switch {
case header.Value != nil:
s = &source.StaticSource{
Value: *header.Value,
}
} else if header.FromContext != nil {
case header.FromAttribute != nil:
defaultValue := ""
if header.DefaultValue != nil {
defaultValue = *header.DefaultValue
}
s = &source.AttributeSource{
Key: *header.FromAttribute,
DefaultValue: defaultValue,
}
case header.FromContext != nil:
defaultValue := ""
if header.DefaultValue != nil {
defaultValue = *header.DefaultValue
Expand Down
36 changes: 36 additions & 0 deletions extension/headerssetterextension/internal/source/attribute.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0

package source // import "github.com/open-telemetry/opentelemetry-collector-contrib/extension/headerssetterextension/internal/source"

import (
"context"
"encoding/json"

"go.opentelemetry.io/collector/client"
)

var _ Source = (*ContextSource)(nil)

type AttributeSource struct {
Key string
DefaultValue string
}

func (ts *AttributeSource) Get(ctx context.Context) (string, error) {
cl := client.FromContext(ctx)
attr := cl.Auth.GetAttribute(ts.Key)

switch a := attr.(type) {
case string:
return a, nil
case nil:
return "", nil
default:
b, err := json.Marshal(attr)
if err != nil {
return "", err
}
return string(b), nil
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0

package source

import (
"context"
"testing"

"github.com/stretchr/testify/assert"
"go.opentelemetry.io/collector/client"
)

type authData struct {
attrs map[string]any
}

func (a authData) GetAttribute(s string) any {
return a.attrs[s]
}

func (a authData) GetAttributeNames() []string {
keys := make([]string, len(a.attrs))
for key := range a.attrs {
keys = append(keys, key)
}
return keys
}

func TestAttributeSourceSuccessString(t *testing.T) {
ts := &AttributeSource{Key: "X-Scope-OrgID"}
cl := client.FromContext(context.Background())
cl.Auth = authData{attrs: map[string]any{"X-Scope-OrgID": "acme"}}
ctx := client.NewContext(context.Background(), cl)

val, err := ts.Get(ctx)

assert.NoError(t, err)
assert.Equal(t, "acme", val)
}

func TestAttributeSourceSuccessStruct(t *testing.T) {
ts := &AttributeSource{Key: "X-Scope-OrgID"}
cl := client.FromContext(context.Background())
cl.Auth = authData{attrs: map[string]any{"X-Scope-OrgID": struct {
Foo string
}{
Foo: "bar",
}}}
ctx := client.NewContext(context.Background(), cl)

val, err := ts.Get(ctx)

assert.NoError(t, err)
assert.Equal(t, "{\"Foo\":\"bar\"}", val)
}

func TestAttributeSourceNotFound(t *testing.T) {
ts := &AttributeSource{Key: "X-Scope-OrgID"}
cl := client.FromContext(context.Background())
cl.Auth = authData{attrs: map[string]any{"Not-Scope-OrgID": "acme"}}
ctx := client.NewContext(context.Background(), cl)

val, err := ts.Get(ctx)

assert.NoError(t, err)
assert.Empty(t, val)
}