-
Notifications
You must be signed in to change notification settings - Fork 2
/
secret.go
209 lines (174 loc) · 5.17 KB
/
secret.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
package credentialexchange
import (
"encoding/json"
"errors"
"fmt"
"os"
"strings"
"time"
"github.com/werf/lockgate"
"github.com/werf/lockgate/pkg/file_locker"
"github.com/zalando/go-keyring"
ini "gopkg.in/ini.v1"
)
var (
ErrUnableToLoadAWSCred = errors.New("unable to laod AWS credential")
ErrCannotLockDir = errors.New("unable to create lock dir")
ErrUnableToRetrieveSections = errors.New("unable to retrieve sections")
ErrUnableToLoadDueToLock = errors.New("cannot load secret due to lock error")
ErrUnableToAcquireLock = errors.New("cannot acquire lock")
ErrUnmarshallingSecret = errors.New("cannot unmarshal secret")
ErrFailedToClearSecretStorage = errors.New("failed to clear secret storage on OS")
)
// AWSRole aws role attributes
type AWSRole struct {
RoleARN string
PrincipalARN string
Name string
Duration int
}
// SecretStore
type SecretStore struct {
AWSCredentials *AWSCredentials
AWSCredJson string
keyring keyring.Keyring
roleArn string
lockDir string
locker lockgate.Locker
lockResource string
secretService string
secretUser string
}
func (s *SecretStore) WithLocker(locker lockgate.Locker) *SecretStore {
s.locker = locker
return s
}
func (s *SecretStore) WithKeyring(keyring keyring.Keyring) *SecretStore {
s.keyring = keyring
return s
}
// keyRingImpl is the default keyring implementation
type keyRingImpl struct{}
func (k *keyRingImpl) Set(service, user, password string) error {
return keyring.Set(service, user, password)
}
func (k *keyRingImpl) Get(service, user string) (string, error) {
return keyring.Get(service, user)
}
func (k *keyRingImpl) Delete(service, user string) error {
return keyring.Delete(service, user)
}
func NewSecretStore(roleArn, namer, baseDir, username string) (*SecretStore, error) {
lockDir := baseDir + "/aws-clie-auth-lock"
locker, err := file_locker.NewFileLocker(lockDir)
if err != nil {
return nil, fmt.Errorf("cannot setup lock dir: %s", lockDir)
}
return &SecretStore{
lockDir: lockDir,
locker: locker,
keyring: &keyRingImpl{},
lockResource: namer,
secretService: namer,
roleArn: roleArn,
secretUser: username,
}, nil
}
func (s *SecretStore) ensureLock() (func(), error) {
acquired, lock, err := s.locker.Acquire(s.lockResource, lockgate.AcquireOptions{Shared: false, Timeout: 1 * time.Minute})
if err != nil {
return nil, fmt.Errorf("%s, %w", err, ErrUnableToAcquireLock)
}
if !acquired {
return nil, fmt.Errorf("%s, %w", err, ErrUnableToLoadDueToLock)
}
return func() {
if acquired {
if err := s.locker.Release(lock); err != nil {
fmt.Fprintf(os.Stderr, "")
}
}
}, nil
}
func (s *SecretStore) load() error {
release, err := s.ensureLock()
if err != nil {
return err
}
defer release()
creds := &AWSCredentials{}
jsonStr, err := s.keyring.Get(s.secretService, s.secretUser)
if err != nil {
if errors.Is(err, keyring.ErrNotFound) {
return nil
}
return err
}
if err := json.Unmarshal([]byte(jsonStr), &creds); err != nil {
return fmt.Errorf("%s, %w", err, ErrUnmarshallingSecret)
}
if err := WriteIniSection(s.roleArn); err != nil {
return err
}
s.AWSCredentials = creds
s.AWSCredJson = jsonStr
return nil
}
func (s *SecretStore) save() error {
release, err := s.ensureLock()
if err != nil {
return err
}
defer release()
if err := WriteIniSection(s.roleArn); err != nil {
return err
}
return s.keyring.Set(s.secretService, s.secretUser, s.AWSCredJson)
}
func (s *SecretStore) AWSCredential() (*AWSCredentials, error) {
if err := s.load(); err != nil {
return nil, fmt.Errorf("secret store: %s, %w", err, ErrUnableToLoadAWSCred)
}
if s.AWSCredentials == nil && s.AWSCredJson == "" {
return nil, nil
}
return s.AWSCredentials, nil
}
func (s *SecretStore) SaveAWSCredential(cred *AWSCredentials) error {
s.AWSCredentials = cred
jsonStr, err := json.Marshal(cred)
if err != nil {
return err
}
s.AWSCredJson = string(jsonStr)
return s.save()
}
func (s *SecretStore) Clear() error {
return s.keyring.Delete(s.secretService, s.secretUser)
}
// ClearAll loops through all the sections in the INI file
// deletes them from the keychain implementation on the OS
func (s *SecretStore) ClearAll() error {
srvSections := []string{}
cfg, err := ini.Load(ConfigIniFile(""))
if err != nil {
return fmt.Errorf("unable to get sections from ini: %s, %w", err, ErrUnableToRetrieveSections)
}
for _, v := range cfg.Section(INI_CONF_SECTION).ChildSections() {
srvSections = append(srvSections, strings.Replace(v.Name(), fmt.Sprintf("%s.", INI_CONF_SECTION), "", -1))
}
for _, v := range srvSections {
if err := s.keyring.Delete(fmt.Sprintf("%s-%s", SELF_NAME, v), s.secretUser); err != nil {
return fmt.Errorf("%s, %w", err, ErrFailedToClearSecretStorage)
}
}
return nil
}
// RoleKeyConverter converts a role to a key used for storing in key store
func RoleKeyConverter(role string) string {
return strings.ReplaceAll(strings.ReplaceAll(role, ":", "_"), "/", "____")
}
// KeyRoleConverter Converts a key back to a role
func KeyRoleConverter(key string) string {
return strings.ReplaceAll(strings.ReplaceAll(key, "____", "/"), "_", ":")
}