-
Notifications
You must be signed in to change notification settings - Fork 0
/
secretstash.go
55 lines (45 loc) · 1.35 KB
/
secretstash.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package secretstash
import (
"errors"
"fmt"
)
var (
ErrSecretNotFound = errors.New("secret not found")
ErrAtLeastOne = errors.New("at least one secret provider must be provided")
)
// SecretProvider is an interface that can be implemented by any type that can
// provide a secret.
//
//go:generate mockgen -destination=./mocks/mock_secret_provider.go -package=mocks . SecretProvider
type SecretProvider interface {
GetSecret(name string) (string, error)
}
// SecretStash is a collection of SecretProviders that can be queried for a
// secret.
type SecretStash struct {
providers []SecretProvider
}
// New returns a new SecretStash with the given providers.
func New(providers ...SecretProvider) (*SecretStash, error) {
if len(providers) == 0 {
return nil, ErrAtLeastOne
}
ans := SecretStash{
providers: providers,
}
return &ans, nil
}
// GetSecret returns the secret with the given name from the first provider that
// can provide it. If no provider can provide the secret, an ErrSecretNotFound error is returned.
func (s *SecretStash) GetSecret(name string) (string, error) {
for _, provider := range s.providers {
secret, err := provider.GetSecret(name)
if err == nil {
return secret, nil
}
if !errors.Is(err, ErrSecretNotFound) {
return "", fmt.Errorf("%s: %w", name, err)
}
}
return "", fmt.Errorf("%s: %w", name, ErrSecretNotFound)
}