-
Notifications
You must be signed in to change notification settings - Fork 14
/
secret_key.go
95 lines (77 loc) · 2.63 KB
/
secret_key.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package config
import (
"encoding/base64"
"fmt"
"sort"
"strings"
)
const (
SecretKeyEncodingBase64 = "base64"
)
type SecretKeyConfig struct {
Encoding *string `yaml:"encoding" mapstructure:"encoding" json:"encoding"`
Alias *string `yaml:"alias,omitempty" mapstructure:"alias,omitempty" json:"alias,omitempty"`
KeyStore *string `yaml:"keyStore,omitempty" mapstructure:"keyStore,omitempty" json:"keyStore,omitempty"`
KeyStorePassword *SensitiveString `yaml:"keyStorePassword,omitempty" mapstructure:"keyStorePassword,omitempty" json:"keyStorePassword,omitempty"`
Value *SensitiveString `yaml:"value,omitempty" mapstructure:"value,omitempty" json:"value,omitempty"`
}
var SecretKeyValidators = map[string]func(cfg *SecretKeyConfig) error{
SecretKeyEncodingBase64: validateBase64Value,
}
func (s *SecretKeyConfig) Validate() error {
if s == nil {
return nil
}
if s.Encoding == nil {
return fmt.Errorf("encoding config missing")
}
if validateFn, ok := SecretKeyValidators[strings.ToLower(*s.Encoding)]; ok {
return validateFn(s)
}
validEncoding := make([]string, 0, len(SecretKeyValidators))
for encoding := range SecretKeyValidators {
validEncoding = append(validEncoding, encoding)
}
sort.Strings(validEncoding)
return fmt.Errorf("encoding `%s` is invalid, must be one of %+q", *s.Encoding, validEncoding)
}
func validateBase64Value(cfg *SecretKeyConfig) error {
if cfg.Value == nil {
return fmt.Errorf("value config missing")
}
if _, err := base64.StdEncoding.DecodeString(cfg.Value.Value()); err != nil {
return fmt.Errorf("value config is invalid")
}
return nil
}
type SecretKey struct {
SensitiveString
}
var SecretKeyReader = map[string]func(cfg *SecretKeyConfig) ([]byte, error){
SecretKeyEncodingBase64: readBase64Value,
}
func MakeSecretKey(cfg *SecretKeyConfig) (*SecretKey, error) {
if cfg == nil {
return nil, fmt.Errorf("secret key load error, config is nil")
}
if err := cfg.Validate(); err != nil {
return nil, err
}
readFn, ok := SecretKeyReader[strings.ToLower(*cfg.Encoding)]
if !ok {
validEncoding := make([]string, 0, len(SecretKeyReader))
for encoding := range SecretKeyReader {
validEncoding = append(validEncoding, encoding)
}
sort.Strings(validEncoding)
return nil, fmt.Errorf("secret key load error, encoding `%s` is invalid, must be one of %+q", *cfg.Encoding, validEncoding)
}
key, err := readFn(cfg)
if err != nil {
return nil, err
}
return &SecretKey{NewSensitiveString(string(key))}, nil
}
func readBase64Value(cfg *SecretKeyConfig) ([]byte, error) {
return base64.StdEncoding.DecodeString(cfg.Value.Value())
}