forked from knadh/koanf
/
vault.go
75 lines (58 loc) · 1.73 KB
/
vault.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// Package vault implements a koanf.Provider for Hashicorp Vault KV secrets engine
// and provides it to koanf to be parsed by a koanf.Parser.
package vault
import (
"errors"
"net/http"
"time"
"github.com/hashicorp/vault/api"
"github.com/knadh/koanf/maps"
)
type Config struct {
// Vault server address
Address string
// Vault static token
Token string
// Secret data path
Path string
// If FlatPaths is true, then the loaded configuration is not split into
// hierarchical maps based on the delimiter. The keys including the delimiter,
// eg: app.db.name stays as-is in the confmap.
FlatPaths bool
// Delim is the delimiter to use
// when specifying config key paths, for instance a . for `parent.child.key`
// or a / for `parent/child/key`.
Delim string
// Internal HTTP client timeout
Timeout time.Duration
}
type Vault struct {
client *api.Client
cfg Config
}
// Provider returns a provider that takes a Vault config.
func Provider(cfg Config) *Vault {
httpClient := &http.Client{Timeout: cfg.Timeout}
client, err := api.NewClient(&api.Config{Address: cfg.Address, HttpClient: httpClient})
if err != nil {
return nil
}
client.SetToken(cfg.Token)
return &Vault{client: client, cfg: cfg}
}
// ReadBytes is not supported by the vault provider.
func (r *Vault) ReadBytes() ([]byte, error) {
return nil, errors.New("vault provider does not support this method")
}
// Read fetches the configuration from the source and returns a nested config map.
func (r *Vault) Read() (map[string]interface{}, error) {
secret, err := r.client.Logical().Read(r.cfg.Path)
if err != nil {
return nil, err
}
if !r.cfg.FlatPaths {
data := maps.Unflatten(secret.Data, r.cfg.Delim)
return data, nil
}
return secret.Data, nil
}