-
Notifications
You must be signed in to change notification settings - Fork 319
/
config_privatekey.go
76 lines (63 loc) · 1.81 KB
/
config_privatekey.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
76
// Copyright (c) 2022 IoTeX Foundation
// This source code is provided 'as is' and no warranties are given as to title or non-infringement, merchantability
// or fitness for purpose and, to the extent permitted by law, all liability for your use of the code is disclaimed.
// This source code is governed by Apache License 2.0 that can be found in the LICENSE file.
package blockchain
import (
"time"
"github.com/hashicorp/vault/api"
"github.com/pkg/errors"
)
const defaultHTTPTimeout = 10 * time.Second
// ErrVault vault error
var ErrVault = errors.New("vault error")
type (
hashiCorpVault struct {
Address string `yaml:"address"`
Token string `yaml:"token"`
Path string `yaml:"path"`
Key string `yaml:"key"`
}
vaultPrivKeyLoader struct {
cfg *hashiCorpVault
*vaultClient
}
vaultSecretReader interface {
Read(path string) (*api.Secret, error)
}
vaultClient struct {
cli vaultSecretReader
}
)
func (l *vaultPrivKeyLoader) load() (string, error) {
secret, err := l.cli.Read(l.cfg.Path)
if err != nil {
return "", errors.Wrap(err, "failed to read vault secret")
}
if secret == nil {
return "", errors.Wrap(ErrVault, "secret does not exist")
}
value, ok := secret.Data[l.cfg.Key]
if !ok {
return "", errors.Wrap(ErrVault, "secret value does not exist")
}
v, ok := value.(string)
if !ok {
return "", errors.Wrap(ErrVault, "invalid secret value type")
}
return v, nil
}
func newVaultPrivKeyLoader(cfg *hashiCorpVault) (*vaultPrivKeyLoader, error) {
conf := api.DefaultConfig()
conf.Address = cfg.Address
conf.Timeout = defaultHTTPTimeout
cli, err := api.NewClient(conf)
if err != nil {
return nil, errors.Wrap(err, "failed to init vault client")
}
cli.SetToken(cfg.Token)
return &vaultPrivKeyLoader{
vaultClient: &vaultClient{cli: cli.Logical()},
cfg: cfg,
}, nil
}