Skip to content
Closed
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
32 changes: 32 additions & 0 deletions .chloggen/feat_basicauth-aws-secrets-manager.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# 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. receiver/filelog)
component: extension/basicauth

# A brief description of the change. Surround your text with quotes ("") if it needs to start with a backtick (`).
note: Add AWS Secrets Manager support for client credential rotation without restarting the collector.

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

# (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: |
The new `client_auth.aws_secrets_manager` option polls a JSON secret from AWS Secrets Manager
at a configurable interval (default: 1h) and swaps credentials in place when a rotation is
detected. Key names default to `username` and `password`, matching AWS's own RDS/Redshift/
DocumentDB rotation templates, and are configurable via `username_key` and `password_key`.
On poll failure the extension logs a warning and retains the last known good credentials.

# 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]
34 changes: 33 additions & 1 deletion extension/basicauthextension/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ The following are the configuration options:
- `client_auth.username_file`: Path to a file containing the username. If set, takes precedence over `username`. The file is watched for changes, allowing rotation without restarting the collector.
- `client_auth.password`: Password to use for client authentication.
- `client_auth.password_file`: Path to a file containing the password. If set, takes precedence over `password`. The file is watched for changes, allowing rotation without restarting the collector.
- `client_auth.aws_secrets_manager`: Fetch credentials from AWS Secrets Manager. Mutually exclusive with the inline/file options above. See [AWS Secrets Manager](#aws-secrets-manager) for details.

To configure the extension as a server authenticator, either one of `htpasswd.file` or `htpasswd.inline` has to be set. If both are configured, `htpasswd.inline` credentials take precedence.

Expand Down Expand Up @@ -58,6 +59,16 @@ extensions:
username_file: /etc/secrets/username
password_file: /etc/secrets/password

# AWS Secrets Manager (polled for changes, enabling rotation without restart)
basicauth/client_from_aws:
client_auth:
aws_secrets_manager:
secret_arn: arn:aws:secretsmanager:us-east-1:123456789012:secret:my-credentials
region: us-east-1 # optional; falls back to AWS_REGION / instance metadata
refresh_interval: 1h # optional; defaults to 1h
username_key: username # optional; defaults to "username"
password_key: password # optional; defaults to "password"

receivers:
otlp:
protocols:
Expand All @@ -79,4 +90,25 @@ service:
receivers: [otlp]
processors: []
exporters: [otlp_grpc]
```
```

## AWS Secrets Manager

When `client_auth.aws_secrets_manager` is set, the extension fetches credentials from AWS Secrets Manager at startup and polls for changes at the configured `refresh_interval` (default: `1h`). Credentials are swapped in place when a rotation is detected — no collector restart required.

The secret must be a JSON object containing the username and password. The default key names match AWS's own rotation templates for RDS, Redshift, DocumentDB, and ElastiCache:

```json
{
"username": "myuser",
"password": "mypassword"
}
```

Use `username_key` and `password_key` to override the field names if your secret uses different keys.

**Authentication:** The extension uses the standard AWS SDK credential chain — environment variables (`AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`), shared credentials file (`~/.aws/credentials`), IAM instance profile, ECS/EKS task role, etc. No additional configuration is needed if the collector is running on an AWS resource with an appropriate IAM role.

**Behavior on poll failure:** If a refresh fails (e.g., transient network error, temporary permission issue), the extension logs a warning and continues using the last successfully fetched credentials. The collector is not interrupted.

`aws_secrets_manager` is mutually exclusive with `username`, `username_file`, `password`, and `password_file`.
170 changes: 170 additions & 0 deletions extension/basicauthextension/aws_secrets_manager_resolver.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0

package basicauthextension // import "github.com/open-telemetry/opentelemetry-collector-contrib/extension/basicauthextension"

import (
"context"
"encoding/json"
"errors"
"fmt"
"sync/atomic"
"time"

"github.com/aws/aws-sdk-go-v2/aws"
awsconfig "github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/secretsmanager"
"go.uber.org/zap"
)

type secretsManagerClient interface {
GetSecretValue(ctx context.Context, params *secretsmanager.GetSecretValueInput, optFns ...func(*secretsmanager.Options)) (*secretsmanager.GetSecretValueOutput, error)
}

// secretCredentials holds a consistent username/password pair fetched from a single secret.
// Stored as a single atomic pointer to guarantee HTTP clients always read a matched pair.
type secretCredentials struct {
username string
password string
}

// awsSecretsManagerResolver fetches a JSON secret from AWS Secrets Manager and polls
// for changes at a configurable interval, updating credentials in place without restarting
// the collector.
type awsSecretsManagerResolver struct {
cfg *AWSSecretsManagerSettings
client secretsManagerClient
creds atomic.Pointer[secretCredentials]
onChange func()
shutdownCh chan struct{}
doneCh chan struct{}
logger *zap.Logger
}

func newAWSSecretsManagerResolver(cfg *AWSSecretsManagerSettings, logger *zap.Logger, onChange func()) *awsSecretsManagerResolver {
return &awsSecretsManagerResolver{
cfg: cfg,
logger: logger,
onChange: onChange,
}
}

func (r *awsSecretsManagerResolver) start(ctx context.Context) error {
opts := []func(*awsconfig.LoadOptions) error{}
if r.cfg.Region != "" {
opts = append(opts, awsconfig.WithRegion(r.cfg.Region))
}
cfg, err := awsconfig.LoadDefaultConfig(ctx, opts...)
if err != nil {
return fmt.Errorf("failed to load AWS config: %w", err)
}
r.client = secretsmanager.NewFromConfig(cfg)
return r.startWithClient(ctx)
}

func (r *awsSecretsManagerResolver) startWithClient(ctx context.Context) error {
if r.shutdownCh != nil {
return errors.New("already started")
}
if err := r.fetch(ctx); err != nil {
return fmt.Errorf("initial fetch from AWS Secrets Manager failed: %w", err)
}

r.shutdownCh = make(chan struct{})
r.doneCh = make(chan struct{})
go r.poll(r.cfg.refreshInterval())
return nil
}

func (r *awsSecretsManagerResolver) shutdown() {
if r.shutdownCh != nil {
close(r.shutdownCh)
<-r.doneCh
r.shutdownCh = nil
}
}

func (r *awsSecretsManagerResolver) Username() string {
if c := r.creds.Load(); c != nil {
return c.username
}
return ""
}

func (r *awsSecretsManagerResolver) Password() string {
if c := r.creds.Load(); c != nil {
return c.password
}
return ""
}

func (r *awsSecretsManagerResolver) poll(interval time.Duration) {
defer close(r.doneCh)

// cancelCtx lets in-flight AWS calls be interrupted when shutdown is requested,
// avoiding a long block waiting for the SDK timeout.
// Capture the channel value (not the field) to avoid a race with shutdown()
// zeroing r.shutdownCh after doneCh is closed.
shutdownCh := r.shutdownCh
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go func() {
<-shutdownCh
cancel()
}()

ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-r.shutdownCh:
return
case <-ticker.C:
if err := r.fetch(ctx); err != nil {
r.logger.Warn("failed to refresh credentials from AWS Secrets Manager, keeping last known values",
zap.String("secret_arn", r.cfg.SecretARN),
zap.Error(err))
}
}
}
}

func (r *awsSecretsManagerResolver) fetch(ctx context.Context) error {
resp, err := r.client.GetSecretValue(ctx, &secretsmanager.GetSecretValueInput{
SecretId: aws.String(r.cfg.SecretARN),
})
if err != nil {
return fmt.Errorf("GetSecretValue: %w", err)
}
if resp.SecretString == nil {
return fmt.Errorf("secret %q has no string value", r.cfg.SecretARN)
}

var fields map[string]string
if err := json.Unmarshal([]byte(*resp.SecretString), &fields); err != nil {
return fmt.Errorf("unmarshal secret JSON: %w", err)
}

usernameKey := r.cfg.usernameKey()
passwordKey := r.cfg.passwordKey()

newUsername, ok := fields[usernameKey]
if !ok {
return fmt.Errorf("key %q not found in secret %q", usernameKey, r.cfg.SecretARN)
}
newPassword, ok := fields[passwordKey]
if !ok {
return fmt.Errorf("key %q not found in secret %q", passwordKey, r.cfg.SecretARN)
}

// Store both credentials atomically so HTTP clients always read a matched pair.
old := r.creds.Load()
if old != nil && old.username == newUsername && old.password == newPassword {
return nil
}
r.creds.Store(&secretCredentials{username: newUsername, password: newPassword})
if r.onChange != nil {
r.onChange()
}
return nil
}
Loading
Loading