Skip to content
Gasv0.10.0

gas/config

config/secretsmanager

import "github.com/gasmod/gas/config/secretsmanager"

Package secretsmanager is a config provider that loads values from AWS Secrets Manager. Each load fetches the secrets registered with the provider and merges them into one map, which the config module merges like that of any other provider.

Register each secret with an option, and pass the provider to the config module:

p := secretsmanager.NewProvider(
secretsmanager.WithSecret("myapp/config"),
secretsmanager.WithSecretAtKey("myapp/db-password", "database.password"),
secretsmanager.WithRegion("eu-west-1"),
)
cfg := config.New(config.WithProvider(p))
err := cfg.Load()
// cfg.Get("database.password") is the value of myapp/db-password

Provider implements config.Provider and config.ContextProvider. It reads no configuration keys of its own; the options set everything.

A secret is registered by its name or ARN, which goes to GetSecretValue as it is, with no version or stage, so Secrets Manager returns the current version, AWSCURRENT. Every load fetches every registered secret again, one at a time in registration order, so a load after a rotation gets the new value. A secret registered twice is fetched twice.

A secret’s value is its SecretString, or its SecretBinary when it has no string.

WithSecret takes a secret whose value is a JSON object and merges the object at the root. Any other value is an error.

WithSecretAtKey places a secret at a key, with a dot between levels as for Config.Get, so database.password is the key password in the map under database:

  • A JSON object is nested there.
  • Any other value is stored there as its text, exactly as stored: a JSON string keeps its quotes, and a number, list or null is not decoded.
  • An empty key is the root, as for WithSecret.
  • A key with an empty level, such as db..password, .db or a space, is an error.

A JSON object that holds a number too large for a float64, such as 1e400, is an error too, at a key as at the root.

JSON values have the types encoding/json decodes them to, except numbers:

  • An object is a map[string]any, a list a []any, and null nil.
  • Numbers keep their digits. An integer is an int64, or a uint64 when it is too large for one. Any other number, such as 1.5, is a float64.

Keys are trimmed and lowercased, as the config module does for every provider: those of the key passed to WithSecretAtKey, and those of a JSON object at every depth. A key of a JSON object that is empty once trimmed is dropped, with its value.

Each secret is handled on its own. Two keys of one secret that become the same, such as Host and host, are an error. Host in one secret and host in a later one are not, and the later one wins.

A dot in a key of a JSON object is part of the key and does not nest: {"database.host": "db"} holds the key database.host, which Config.Get cannot reach, as it splits its argument on dots.

Secrets are merged in registration order, a later one winning. Where two secrets hold a map under one key, the maps are merged key by key, so a secret at the root holding {"database": {"host": "db"}} and one at database.password give database both keys.

Anywhere else the later value replaces the earlier one:

  • A value replaces a map, and a map replaces a value.
  • A list replaces a list as a whole.
  • null replaces anything.

The first load builds the AWS client from the default AWS configuration, as the AWS SDK loads it, with these options over it:

  • WithRegion sets the region.
  • WithStaticCredentials sets the credentials, when both values are set. With one of them empty, the default credential chain applies.
  • WithEndpoint sets the endpoint, such as LocalStack’s.

An empty region or endpoint leaves it to the default configuration. A region missing from both the option and the default configuration does not fail the build; without an endpoint, each fetch then fails.

Later loads reuse the client, so a change to the AWS configuration after the first load does not reach the provider. A failed build is not kept: the next load tries again.

WithClient gives the provider a client to use instead, such as a *secretsmanager.Client built elsewhere or a fake, and the three options above then have no effect. A nil client builds one as without the option. Only a nil interface counts: a nil *secretsmanager.Client is used as it is, and panics on the first fetch.

A *Provider prints, with fmt and any verb, and logs, with log/slog, only its region, how many secrets it has, its timeout, and whether it has an endpoint and static credentials: never the credentials, the endpoint or the secrets’ names.

Each load runs under a context that ends after DefaultTimeout, 10 seconds, or after the duration passed to WithTimeout. Zero or a negative duration means no limit of the provider’s own.

Provider.LoadContext derives that context from the caller’s, so the caller’s values reach the client. The load ends at the caller’s deadline or the provider’s, whichever comes first. A caller that needs longer than the timeout sets a longer one with WithTimeout.

Provider.Load is LoadContext with context.Background(). The config module calls LoadContext, so Config.Load and Config.LoadWithContext are bounded the same way.

When the context ends during a fetch, the error wraps the context’s error, such as context.DeadlineExceeded.

Load and LoadContext may be called from several goroutines at once, on one provider, as two Config.Load calls do.

Errors wrap one of the package’s sentinel errors, to be tested with errors.Is:

The first two are reported before the client is built, and the third before any secret is fetched. The first error stops the load, and no later secret is fetched.

An error about one secret names it. The provider adds no part of a secret’s value to an error: a decode error gives the offset of a JSON syntax error or the kind of JSON value, and a key conflict names the two keys:

no secrets configured
invalid key "db..password" for secret myapp/db-password: a level is empty
failed to initialize SecretsManager client: failed to get shared config profile, prod
failed to fetch secret myapp/config: operation error Secrets Manager: GetSecretValue, ...
failed to decode secret myapp/config: value is not valid JSON: syntax error after byte 14
failed to decode secret myapp/config: value is a JSON string, not an object
failed to decode secret myapp/config: database: conflicting keys: "Host" and "host"

The config module wraps the error once more and names the provider by ProviderName:

failed to load from provider AWS SecretsManager: failed to fetch secret myapp/config: ...

const (
// ProviderName is the name reported by Name.
ProviderName = "AWS SecretsManager"
// DefaultTimeout bounds each load unless WithTimeout says otherwise.
DefaultTimeout = 10 * time.Second
)

var (
// ErrNoSecretsConfigured indicates that no secret was registered.
ErrNoSecretsConfigured = errors.New("no secrets configured")
// ErrInvalidKey indicates that a key passed to WithSecretAtKey has an
// empty level.
ErrInvalidKey = errors.New("invalid key")
// ErrClientInitFailed indicates that the AWS configuration could not be
// loaded to build the client.
ErrClientInitFailed = errors.New("failed to initialize SecretsManager client")
// ErrSecretFetchFailed indicates that GetSecretValue failed for a secret.
ErrSecretFetchFailed = errors.New("failed to fetch secret")
// ErrSecretDecodeFailed indicates that a secret's value could not be
// turned into configuration values.
ErrSecretDecodeFailed = errors.New("failed to decode secret")
)

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

API is the part of the AWS Secrets Manager client that Provider uses. *secretsmanager.Client implements it.

type Option func(*Provider)

Option configures a Provider.

func WithClient(client API) Option

WithClient makes the provider use client instead of building one, so WithRegion, WithStaticCredentials and WithEndpoint have no effect. A nil client builds one as without this option.

func WithEndpoint(endpoint string) Option

WithEndpoint sets the endpoint the client sends requests to, such as LocalStack’s. An empty endpoint leaves it to the default AWS configuration.

func WithRegion(region string) Option

WithRegion sets the AWS region. An empty region leaves it to the default AWS configuration.

func WithSecret(name string) Option

WithSecret registers a secret, by name or ARN, whose value must be a JSON object. The object is merged at the root.

func WithSecretAtKey(name, key string) Option

WithSecretAtKey registers a secret, by name or ARN, placed at the dot-separated key. A JSON object is nested there, and any other value is stored there as its text. An empty key is the root, as for WithSecret, and a key with an empty level fails the load with ErrInvalidKey.

func WithStaticCredentials(accessKeyID, secretAccessKey string) Option

WithStaticCredentials sets static AWS credentials. Unless both are set, the default AWS credential chain is used.

func WithTimeout(d time.Duration) Option

WithTimeout sets how long a load may take, through Load or LoadContext. Zero or a negative duration means no limit of the provider’s own.

Default: DefaultTimeout.

type Provider struct {
// contains filtered or unexported fields
}

Provider loads configuration from AWS Secrets Manager, as described in the package documentation.

func NewProvider(opts ...Option) *Provider

NewProvider returns a Provider configured by opts.

func (p *Provider) Format(f fmt.State, _ rune)

Format writes String, whatever the verb, so fmt never prints the secret access key.

func (p *Provider) Load() (map[string]any, error)

Load fetches the registered secrets, bounded by the provider’s timeout.

func (p *Provider) LoadContext(ctx context.Context) (map[string]any, error)

LoadContext fetches the registered secrets under ctx, bounded by the provider’s timeout as well.

func (p *Provider) LogValue() slog.Value

LogValue returns a group of what String prints, never the secret access key.

func (p *Provider) Name() string

Name returns ProviderName.

func (p *Provider) String() string

String describes the Provider without its credentials, its endpoint or its secrets’ names: its region, how many secrets it has, its timeout, and whether it has an endpoint and static credentials, such as secretsmanager.Provider{region: "eu-west-1", secrets: 1, timeout: 10s, endpoint: false, staticCredentials: true}.