github.com/iotexproject/iotex-core@v1.14.1-rc1/blockchain/config_privatekey.go (about) 1 // Copyright (c) 2022 IoTeX Foundation 2 // This source code is provided 'as is' and no warranties are given as to title or non-infringement, merchantability 3 // or fitness for purpose and, to the extent permitted by law, all liability for your use of the code is disclaimed. 4 // This source code is governed by Apache License 2.0 that can be found in the LICENSE file. 5 6 package blockchain 7 8 import ( 9 "time" 10 11 "github.com/hashicorp/vault/api" 12 "github.com/pkg/errors" 13 ) 14 15 const defaultHTTPTimeout = 10 * time.Second 16 17 // ErrVault vault error 18 var ErrVault = errors.New("vault error") 19 20 type ( 21 hashiCorpVault struct { 22 Address string `yaml:"address"` 23 Token string `yaml:"token"` 24 Path string `yaml:"path"` 25 Key string `yaml:"key"` 26 } 27 28 vaultPrivKeyLoader struct { 29 cfg *hashiCorpVault 30 *vaultClient 31 } 32 33 vaultSecretReader interface { 34 Read(path string) (*api.Secret, error) 35 } 36 37 vaultClient struct { 38 cli vaultSecretReader 39 } 40 ) 41 42 func (l *vaultPrivKeyLoader) load() (string, error) { 43 secret, err := l.cli.Read(l.cfg.Path) 44 if err != nil { 45 return "", errors.Wrap(err, "failed to read vault secret") 46 } 47 if secret == nil { 48 return "", errors.Wrap(ErrVault, "secret does not exist") 49 } 50 value, ok := secret.Data[l.cfg.Key] 51 if !ok { 52 return "", errors.Wrap(ErrVault, "secret value does not exist") 53 } 54 v, ok := value.(string) 55 if !ok { 56 return "", errors.Wrap(ErrVault, "invalid secret value type") 57 } 58 59 return v, nil 60 } 61 62 func newVaultPrivKeyLoader(cfg *hashiCorpVault) (*vaultPrivKeyLoader, error) { 63 conf := api.DefaultConfig() 64 conf.Address = cfg.Address 65 conf.Timeout = defaultHTTPTimeout 66 cli, err := api.NewClient(conf) 67 if err != nil { 68 return nil, errors.Wrap(err, "failed to init vault client") 69 } 70 cli.SetToken(cfg.Token) 71 72 return &vaultPrivKeyLoader{ 73 vaultClient: &vaultClient{cli: cli.Logical()}, 74 cfg: cfg, 75 }, nil 76 }