## Search

Page index: https://gasmod.dev/llms.txt. Add index.md to any page URL for its Markdown.

This site has a search endpoint: https://context7.com/api/v2/ask?siteKey=ask_b845b566cb63bd033e9c576d&query=<URL-encoded question>. It returns documentation that answers the question, with a source link for each part. No API key is needed. If nothing matches, it says so.

# config/secretsmanager

> Package secretsmanager is a config provider that loads values from AWS Secrets Manager.

The Markdown of https://gasmod.dev/reference/config/secretsmanager/ from the Gas documentation, whose index for LLMs is https://gasmod.dev/llms.txt

```go
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.

## Usage

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

```go
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](#Provider) implements config.Provider and config.ContextProvider. It
reads no configuration keys of its own; the options set everything.

## Secrets

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.

## Values

[WithSecret](#WithSecret) takes a secret whose value is a JSON object and merges the
object at the root. Any other value is an error.

[WithSecretAtKey](#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](https://pkg.go.dev/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

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.

## Merging

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.

## Client

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

- [WithRegion](#WithRegion) sets the region.
- [WithStaticCredentials](#WithStaticCredentials) sets the credentials, when both values are
set. With one of them empty, the default credential chain applies.
- [WithEndpoint](#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](#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.

## Printing

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.

## Timeouts

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

[Provider.LoadContext](#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](#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](https://pkg.go.dev/context#DeadlineExceeded).

## Concurrency

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

## Errors

Errors wrap one of the package's sentinel errors, to be tested with
[errors.Is](https://pkg.go.dev/errors#Is):

- [ErrNoSecretsConfigured](#ErrNoSecretsConfigured): no secret was registered.
- [ErrInvalidKey](#ErrInvalidKey): a key passed to WithSecretAtKey has an empty level.
- [ErrClientInitFailed](#ErrClientInitFailed): the AWS configuration could not be loaded, such
as for a profile that does not exist.
- [ErrSecretFetchFailed](#ErrSecretFetchFailed): GetSecretValue failed. The AWS error is
wrapped, so [errors.As](https://pkg.go.dev/errors#As) finds it, such as a
\*types.ResourceNotFoundException for a secret that does not exist.
- [ErrSecretDecodeFailed](#ErrSecretDecodeFailed): a secret at the root is not a JSON object, or
two keys of a secret conflict.

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:

```go
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](#ProviderName):

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


## API reference

### Constants

<a id="ProviderName"></a><a id="DefaultTimeout"></a>

```go
const (
	// ProviderName is the name reported by Name.
	ProviderName = "AWS SecretsManager"

	// DefaultTimeout bounds each load unless WithTimeout says otherwise.
	DefaultTimeout = 10 * time.Second
)
```

### Variables

<a id="ErrNoSecretsConfigured"></a><a id="ErrInvalidKey"></a><a id="ErrClientInitFailed"></a><a id="ErrSecretFetchFailed"></a><a id="ErrSecretDecodeFailed"></a>

```go
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")
)
```

<a id="API"></a><a id="API.GetSecretValue"></a>

### type API

```go
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.

<a id="Option"></a>

### type Option

```go
type Option func(*Provider)
```

Option configures a Provider.

<a id="WithClient"></a>

#### func WithClient

```go
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.

<a id="WithEndpoint"></a>

#### func WithEndpoint

```go
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.

<a id="WithRegion"></a>

#### func WithRegion

```go
func WithRegion(region string) Option
```

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

<a id="WithSecret"></a>

#### func WithSecret

```go
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.

<a id="WithSecretAtKey"></a>

#### func WithSecretAtKey

```go
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.

<a id="WithStaticCredentials"></a>

#### func WithStaticCredentials

```go
func WithStaticCredentials(accessKeyID, secretAccessKey string) Option
```

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

<a id="WithTimeout"></a>

#### func WithTimeout

```go
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.

<a id="Provider"></a>

### type Provider

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

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

<a id="NewProvider"></a>

#### func NewProvider

```go
func NewProvider(opts ...Option) *Provider
```

NewProvider returns a Provider configured by opts.

<a id="Provider.Format"></a>

#### func (*Provider) Format

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

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

<a id="Provider.Load"></a>

#### func (*Provider) Load

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

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

<a id="Provider.LoadContext"></a>

#### func (*Provider) LoadContext

```go
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.

<a id="Provider.LogValue"></a>

#### func (*Provider) LogValue

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

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

<a id="Provider.Name"></a>

#### func (*Provider) Name

```go
func (p *Provider) Name() string
```

Name returns ProviderName.

<a id="Provider.String"></a>

#### func (*Provider) String

```go
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}`.
