-
Notifications
You must be signed in to change notification settings - Fork 7
/
backend.go
335 lines (298 loc) · 7.93 KB
/
backend.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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
package natsbackend
import (
"context"
"fmt"
"strings"
"sync"
"time"
"github.com/edgefarm/vault-plugin-secrets-nats/pkg/stm"
"github.com/hashicorp/vault/sdk/framework"
"github.com/hashicorp/vault/sdk/logical"
)
// natsBackend defines an object that
// extends the Vault backend and stores the
// target API's client.
type NatsBackend struct {
*framework.Backend
lock sync.RWMutex
client *NatsClient
}
func Factory(ctx context.Context, conf *logical.BackendConfig) (logical.Backend, error) {
b := backend()
if err := b.Setup(ctx, conf); err != nil {
return nil, err
}
return b, nil
}
// backend defines the target API backend
// for Vault. It must include each path
// and the secrets it will store.
func backend() *NatsBackend {
var b = NatsBackend{}
b.Backend = &framework.Backend{
Help: strings.TrimSpace(backendHelp),
PathsSpecial: &logical.Paths{
LocalStorage: []string{},
SealWrapStorage: []string{
"config",
"role/*",
},
},
Paths: framework.PathAppend(
pathNkey(&b),
pathJWT(&b),
pathIssue(&b),
pathCreds(&b),
[]*framework.Path{},
),
Secrets: []*framework.Secret{
// b.hashiCupsToken(),
},
BackendType: logical.TypeLogical,
Invalidate: b.invalidate,
WALRollbackMinAge: 30 * time.Second,
PeriodicFunc: b.periodicFunc,
}
return &b
}
// backendHelp should contain help information for the backend
const backendHelp = `
The HashiCups secrets backend dynamically generates user tokens.
After mounting this backend, credentials to manage HashiCups user tokens
must be configured with the "config/" endpoints.
`
// reset clears any client configuration for a new
// backend to be configured
func (b *NatsBackend) reset() {
b.lock.Lock()
defer b.lock.Unlock()
b.client = nil
}
// invalidate clears an existing client configuration in
// the backend
func (b *NatsBackend) invalidate(ctx context.Context, key string) {
if key == "config" {
b.reset()
}
}
// getClient locks the backend as it configures and creates a
// a new client for the target API
func (b *NatsBackend) getClient(ctx context.Context, s logical.Storage) (*NatsClient, error) {
b.lock.RLock()
unlockFunc := b.lock.RUnlock
defer func() { unlockFunc() }()
if b.client != nil {
return b.client, nil
}
b.lock.RUnlock()
b.lock.Lock()
unlockFunc = b.lock.Unlock
return b.client, nil
}
func (b *NatsBackend) put(ctx context.Context, s logical.Storage, path string, data interface{}) error {
b.lock.Lock()
defer b.lock.Unlock()
entry, err := logical.StorageEntryJSON(path, data)
if err != nil {
return fmt.Errorf("error creating storage entry: %w", err)
}
if err := s.Put(ctx, entry); err != nil {
return fmt.Errorf("error writing to backend: %w", err)
}
return nil
}
func getFromStorage[T any](ctx context.Context, s logical.Storage, path string) (*T, error) {
if path == "" {
return nil, fmt.Errorf("missing path")
}
// get data entry from storage backend
entry, err := s.Get(ctx, path)
if err != nil {
return nil, fmt.Errorf("error retrieving Data: %w", err)
}
if entry == nil {
return nil, nil
}
// convert json data to T
var t T
if err := entry.DecodeJSON(&t); err != nil {
return nil, fmt.Errorf("error decoding JWT data: %w", err)
}
return &t, nil
}
func deleteFromStorage(ctx context.Context, s logical.Storage, path string) error {
if err := s.Delete(ctx, path); err != nil {
return fmt.Errorf("error deleting data: %w", err)
}
return nil
}
func storeInStorage[T any](ctx context.Context, s logical.Storage, path string, t *T) error {
entry, err := logical.StorageEntryJSON(path, t)
if err != nil {
return err
}
if err := s.Put(ctx, entry); err != nil {
return err
}
return nil
}
func readOperation[T any](ctx context.Context, s logical.Storage, path string) (*logical.Response, error) {
t, err := getFromStorage[T](ctx, s, path)
if err != nil {
return nil, err
}
if t == nil {
return nil, nil
}
var groupMap map[string]interface{}
err = stm.StructToMap(t, &groupMap)
if err != nil {
return nil, err
}
return &logical.Response{
Data: groupMap,
}, nil
}
func (b *NatsBackend) periodicFunc(ctx context.Context, sys *logical.Request) error {
b.Logger().Info("Periodic: starting periodic func for syncing accounts to nats")
operators, err := listOperatorIssues(ctx, sys.Storage)
if err != nil {
return err
}
for _, operator := range operators {
operatorIssue, err := readOperatorIssue(ctx, sys.Storage, IssueOperatorParameters{
Operator: operator,
})
if err != nil {
return err
}
if operatorIssue != nil {
b.Logger().Debug(fmt.Sprintf("Periodic: operator %s selected for auto sync to account server", operator))
accountNames, err := listAccountIssues(ctx, sys.Storage, operator)
if err != nil {
return err
}
for _, account := range accountNames {
if err = b.periodicRefreshAccountIssues(ctx, sys.Storage, operator); err != nil {
b.Logger().Info(err.Error())
}
if err = b.periodicRefreshUserIssues(ctx, sys.Storage, operator, account); err != nil {
b.Logger().Info(err.Error())
}
if operatorIssue.SyncAccountServer {
b.Logger().Debug(fmt.Sprintf("Periodic: account %s in operator %s syncing to acount server", account, operator))
accountIssue, err := readAccountIssue(ctx, sys.Storage, IssueAccountParameters{
Operator: operator,
Account: account,
})
if err != nil {
b.Logger().Info(err.Error())
}
if err = refreshAccountResolver(ctx, sys.Storage, accountIssue, AccountResolverActionPush); err != nil {
return err
}
_, err = storeAccountIssueUpdate(ctx, sys.Storage, accountIssue)
if err != nil {
return err
}
} else {
b.Logger().Info(fmt.Sprintf("Periodic: operator %s not configured for auto syncing to account server. Skipping.", operator))
continue
}
}
}
}
return nil
}
func (b *NatsBackend) periodicRefreshUserIssues(ctx context.Context, storage logical.Storage, operator string, account string) error {
issuesList, err := listUserIssues(ctx, storage, IssueUserParameters{
Operator: operator,
Account: account,
})
if err != nil {
return err
}
for _, issueName := range issuesList {
issue, err := readUserIssue(ctx, storage, IssueUserParameters{
Operator: operator,
Account: account,
User: issueName,
})
if err != nil {
return err
}
jwtMissing := false
nkeyMissing := false
jwt, err := readUserJWT(ctx, storage, JWTParameters{
Operator: operator,
Account: account,
User: issueName,
})
if err != nil {
return err
}
if !issue.Status.User.JWT || jwt == nil {
jwtMissing = true
}
nkey, err := readUserNkey(ctx, storage, NkeyParameters{
Operator: operator,
Account: account,
User: issueName,
})
if err != nil {
return err
}
if !issue.Status.User.Nkey || nkey == nil {
nkeyMissing = true
}
if jwtMissing || nkeyMissing {
if err := refreshUser(ctx, storage, issue); err != nil {
return err
}
}
}
return nil
}
func (b *NatsBackend) periodicRefreshAccountIssues(ctx context.Context, storage logical.Storage, operator string) error {
issuesList, err := listAccountIssues(ctx, storage, operator)
if err != nil {
return err
}
for _, issueName := range issuesList {
issue, err := readAccountIssue(ctx, storage, IssueAccountParameters{
Operator: operator,
Account: issueName,
})
if err != nil {
return err
}
jwtMissing := false
nkeyMissing := false
jwt, err := readAccountJWT(ctx, storage, JWTParameters{
Operator: operator,
Account: issueName,
})
if err != nil {
return err
}
if !issue.Status.Account.JWT || jwt == nil {
jwtMissing = true
}
nkey, err := readAccountNkey(ctx, storage, NkeyParameters{
Operator: operator,
Account: issueName,
})
if err != nil {
return err
}
if !issue.Status.Account.Nkey || nkey == nil {
nkeyMissing = true
}
if jwtMissing || nkeyMissing {
if err := refreshAccount(ctx, storage, issue); err != nil {
return err
}
}
}
return nil
}