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-passwordProvider implements config.Provider and config.ContextProvider. It reads no configuration keys of its own; the options set everything.
Secrets
Section titled “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
Section titled “Values”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,.dbor 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.
Merging
Section titled “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
Section titled “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 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.
Printing
Section titled “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
Section titled “Timeouts”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.
Concurrency
Section titled “Concurrency”Load and LoadContext may be called from several goroutines at once, on one provider, as two Config.Load calls do.
Errors
Section titled “Errors”Errors wrap one of the package’s sentinel errors, to be tested with errors.Is:
- ErrNoSecretsConfigured: no secret was registered.
- ErrInvalidKey: a key passed to WithSecretAtKey has an empty level.
- ErrClientInitFailed: the AWS configuration could not be loaded, such as for a profile that does not exist.
- ErrSecretFetchFailed: GetSecretValue failed. The AWS error is wrapped, so errors.As finds it, such as a *types.ResourceNotFoundException for a secret that does not exist.
- 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:
no secrets configuredinvalid key "db..password" for secret myapp/db-password: a level is emptyfailed to initialize SecretsManager client: failed to get shared config profile, prodfailed 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 14failed to decode secret myapp/config: value is a JSON string, not an objectfailed 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: ...API reference
Section titled “API reference”Constants
Section titled “Constants”const ( // ProviderName is the name reported by Name. ProviderName = "AWS SecretsManager"
// DefaultTimeout bounds each load unless WithTimeout says otherwise. DefaultTimeout = 10 * time.Second)Variables
Section titled “Variables”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
Section titled “type API”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
Section titled “type Option”type Option func(*Provider)Option configures a Provider.
func WithClient
Section titled “func WithClient”func WithClient(client API) OptionWithClient 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
Section titled “func WithEndpoint”func WithEndpoint(endpoint string) OptionWithEndpoint sets the endpoint the client sends requests to, such as LocalStack’s. An empty endpoint leaves it to the default AWS configuration.
func WithRegion
Section titled “func WithRegion”func WithRegion(region string) OptionWithRegion sets the AWS region. An empty region leaves it to the default AWS configuration.
func WithSecret
Section titled “func WithSecret”func WithSecret(name string) OptionWithSecret registers a secret, by name or ARN, whose value must be a JSON object. The object is merged at the root.
func WithSecretAtKey
Section titled “func WithSecretAtKey”func WithSecretAtKey(name, key string) OptionWithSecretAtKey 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
Section titled “func WithStaticCredentials”func WithStaticCredentials(accessKeyID, secretAccessKey string) OptionWithStaticCredentials sets static AWS credentials. Unless both are set, the default AWS credential chain is used.
func WithTimeout
Section titled “func WithTimeout”func WithTimeout(d time.Duration) OptionWithTimeout 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
Section titled “type Provider”type Provider struct { // contains filtered or unexported fields}Provider loads configuration from AWS Secrets Manager, as described in the package documentation.
func NewProvider
Section titled “func NewProvider”func NewProvider(opts ...Option) *ProviderNewProvider returns a Provider configured by opts.
func (*Provider) Format
Section titled “func (*Provider) Format”func (p *Provider) Format(f fmt.State, _ rune)Format writes String, whatever the verb, so fmt never prints the secret access key.
func (*Provider) Load
Section titled “func (*Provider) Load”func (p *Provider) Load() (map[string]any, error)Load fetches the registered secrets, bounded by the provider’s timeout.
func (*Provider) LoadContext
Section titled “func (*Provider) LoadContext”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 (*Provider) LogValue
Section titled “func (*Provider) LogValue”func (p *Provider) LogValue() slog.ValueLogValue returns a group of what String prints, never the secret access key.
func (*Provider) Name
Section titled “func (*Provider) Name”func (p *Provider) Name() stringName returns ProviderName.
func (*Provider) String
Section titled “func (*Provider) String”func (p *Provider) String() stringString 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}.