forked from edgefarm/vault-plugin-secrets-nats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
paths_issue_user.go
620 lines (558 loc) · 16.6 KB
/
paths_issue_user.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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
package natsbackend
import (
"context"
"encoding/json"
"fmt"
"github.com/hashicorp/vault/sdk/framework"
"github.com/hashicorp/vault/sdk/logical"
"github.com/nats-io/jwt/v2"
"github.com/nats-io/nkeys"
"github.com/rs/zerolog/log"
"github.com/edgefarm/vault-plugin-secrets-nats/pkg/claims/user/v1alpha1"
"github.com/edgefarm/vault-plugin-secrets-nats/pkg/stm"
)
type IssueUserStorage struct {
Operator string `json:"operator"`
Account string `json:"account"`
User string `json:"user"`
UseSigningKey string `json:"useSigningKey"`
Claims v1alpha1.UserClaims `json:"claims"`
Status IssueUserStatus `json:"status"`
}
// IssueUserParameters is the user facing interface for configuring a user issue.
// Using pascal case on purpose.
// +k8s:deepcopy-gen=true
type IssueUserParameters struct {
Operator string `json:"operator"`
Account string `json:"account"`
User string `json:"user"`
UseSigningKey string `json:"useSigningKey,omitempty"`
Claims v1alpha1.UserClaims `json:"claims,omitempty"`
}
type IssueUserData struct {
Operator string `json:"operator"`
Account string `json:"account"`
User string `json:"user"`
UseSigningKey string `json:"useSigningKey"`
Claims v1alpha1.UserClaims `json:"claims"`
Status IssueUserStatus `json:"status"`
}
type IssueUserStatus struct {
User IssueStatus `json:"user"`
}
func pathUserIssue(b *NatsBackend) []*framework.Path {
return []*framework.Path{
{
Pattern: "issue/operator/" + framework.GenericNameRegex("operator") + "/account/" + framework.GenericNameRegex("account") + "/user/" + framework.GenericNameRegex("user") + "$",
Fields: map[string]*framework.FieldSchema{
"operator": {
Type: framework.TypeString,
Description: "operator identifier",
Required: false,
},
"account": {
Type: framework.TypeString,
Description: "account identifier",
Required: false,
},
"user": {
Type: framework.TypeString,
Description: "user identifier",
Required: false,
},
"useSigningKey": {
Type: framework.TypeString,
Description: "signing key identifier",
Required: false,
},
"claims": {
Type: framework.TypeMap,
Description: "User claims (jwt.UserClaims from github.com/nats-io/jwt/v2)",
Required: false,
},
},
Operations: map[logical.Operation]framework.OperationHandler{
logical.CreateOperation: &framework.PathOperation{
Callback: b.pathAddUserIssue,
},
logical.UpdateOperation: &framework.PathOperation{
Callback: b.pathAddUserIssue,
},
logical.ReadOperation: &framework.PathOperation{
Callback: b.pathReadUserIssue,
},
logical.DeleteOperation: &framework.PathOperation{
Callback: b.pathDeleteUserIssue,
},
},
HelpSynopsis: `Manages user cmd's.`,
HelpDescription: ``,
},
{
Pattern: "issue/operator/" + framework.GenericNameRegex("operator") + "/account/" + framework.GenericNameRegex("account") + "/user/?$",
Fields: map[string]*framework.FieldSchema{
"operator": {
Type: framework.TypeString,
Description: "operator identifier",
Required: false,
},
"account": {
Type: framework.TypeString,
Description: "account identifier",
Required: false,
},
},
Operations: map[logical.Operation]framework.OperationHandler{
logical.ListOperation: &framework.PathOperation{
Callback: b.pathListUserIssues,
},
},
HelpSynopsis: "pathRoleListHelpSynopsis",
HelpDescription: "pathRoleListHelpDescription",
},
}
}
func (b *NatsBackend) pathAddUserIssue(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
err := data.Validate()
if err != nil {
return logical.ErrorResponse(InvalidParametersError), logical.ErrInvalidRequest
}
jsonString, err := json.Marshal(data.Raw)
if err != nil {
return logical.ErrorResponse(DecodeFailedError), logical.ErrInvalidRequest
}
params := IssueUserParameters{}
json.Unmarshal(jsonString, ¶ms)
err = addUserIssue(ctx, req.Storage, params)
if err != nil {
return logical.ErrorResponse(AddingIssueFailedError), nil
}
return nil, nil
}
func (b *NatsBackend) pathReadUserIssue(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
err := data.Validate()
if err != nil {
return logical.ErrorResponse(InvalidParametersError), logical.ErrInvalidRequest
}
jsonString, err := json.Marshal(data.Raw)
if err != nil {
return logical.ErrorResponse(DecodeFailedError), logical.ErrInvalidRequest
}
params := IssueUserParameters{}
json.Unmarshal(jsonString, ¶ms)
issue, err := readUserIssue(ctx, req.Storage, params)
if err != nil {
return logical.ErrorResponse(ReadingIssueFailedError), nil
}
if issue == nil {
return logical.ErrorResponse(IssueNotFoundError), nil
}
return createResponseIssueUserData(issue)
}
func (b *NatsBackend) pathListUserIssues(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
err := data.Validate()
if err != nil {
return logical.ErrorResponse(InvalidParametersError), logical.ErrInvalidRequest
}
jsonString, err := json.Marshal(data.Raw)
if err != nil {
return logical.ErrorResponse(DecodeFailedError), logical.ErrInvalidRequest
}
params := IssueUserParameters{}
json.Unmarshal(jsonString, ¶ms)
entries, err := listUserIssues(ctx, req.Storage, params)
if err != nil {
return logical.ErrorResponse(ListIssuesFailedError), nil
}
return logical.ListResponse(entries), nil
}
func (b *NatsBackend) pathDeleteUserIssue(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
err := data.Validate()
if err != nil {
return logical.ErrorResponse(InvalidParametersError), logical.ErrInvalidRequest
}
var params IssueUserParameters
err = stm.MapToStruct(data.Raw, ¶ms)
if err != nil {
return logical.ErrorResponse(DecodeFailedError), logical.ErrInvalidRequest
}
// delete issue and all related nkeys and jwt
err = deleteUserIssue(ctx, req.Storage, params)
if err != nil {
return logical.ErrorResponse(DeleteIssueFailedError), nil
}
return nil, nil
}
func addUserIssue(ctx context.Context, storage logical.Storage, params IssueUserParameters) error {
log.Info().
Str("operator", params.Operator).Str("account", params.Account).Str("user", params.User).
Msgf("issue user")
// store issue
issue, err := storeUserIssue(ctx, storage, params)
if err != nil {
return err
}
return refreshUser(ctx, storage, issue)
}
func refreshUser(ctx context.Context, storage logical.Storage, issue *IssueUserStorage) error {
// create nkey and signing nkeys
err := issueUserNKeys(ctx, storage, *issue)
if err != nil {
return err
}
// create jwt
err = issueUserJWT(ctx, storage, *issue)
if err != nil {
return err
}
// create creds
err = issueUserCreds(ctx, storage, *issue)
if err != nil {
return err
}
updateUserStatus(ctx, storage, issue)
_, err = storeUserIssueUpdate(ctx, storage, issue)
if err != nil {
return err
}
if issue.User == DefaultPushUser {
// force update of operator
// so he gets updates from sys account
op, err := readOperatorIssue(ctx, storage, IssueOperatorParameters{
Operator: issue.Operator,
})
if err != nil {
return err
} else if op == nil {
log.Warn().Str("operator", issue.Operator).Str("account", issue.Account).Msg("cannot refresh operator: operator issue does not exist")
return nil
}
err = refreshAccountResolvers(ctx, storage, op)
if err != nil {
return err
}
}
return nil
}
func readUserIssue(ctx context.Context, storage logical.Storage, params IssueUserParameters) (*IssueUserStorage, error) {
path := getUserIssuePath(params.Operator, params.Account, params.User)
return getFromStorage[IssueUserStorage](ctx, storage, path)
}
func listUserIssues(ctx context.Context, storage logical.Storage, params IssueUserParameters) ([]string, error) {
path := getUserIssuePath(params.Operator, params.Account, "")
return listIssues(ctx, storage, path)
}
func deleteUserIssue(ctx context.Context, storage logical.Storage, params IssueUserParameters) error {
// get stored signing keys
issue, err := readUserIssue(ctx, storage, params)
if err != nil {
return err
}
if issue == nil {
// nothing to delete
return nil
}
// account revocation list handling for deleted user
account, err := readAccountIssue(ctx, storage, IssueAccountParameters{
Operator: issue.Operator,
Account: issue.Account,
})
if err != nil {
return err
}
if account != nil {
// add deleted user to revocation list and update the account JWT
err = addUserToRevocationList(ctx, storage, account, issue)
if err != nil {
return err
}
}
// delete user nkey
nkey := NkeyParameters{
Operator: issue.Operator,
Account: issue.Account,
User: issue.User,
}
err = deleteUserNkey(ctx, storage, nkey)
if err != nil {
return err
}
// delete user jwt
jwt := JWTParameters{
Operator: issue.Operator,
Account: issue.Account,
User: issue.User,
}
err = deleteUserJWT(ctx, storage, jwt)
if err != nil {
return err
}
// delete user creds
creds := CredsParameters{
Operator: issue.Operator,
Account: issue.Account,
User: issue.User,
}
err = deleteUserCreds(ctx, storage, creds)
if err != nil {
return err
}
// delete user issue
path := getUserIssuePath(issue.Operator, issue.Account, issue.User)
return deleteFromStorage(ctx, storage, path)
}
func storeUserIssueUpdate(ctx context.Context, storage logical.Storage, issue *IssueUserStorage) (*IssueUserStorage, error) {
path := getUserIssuePath(issue.Operator, issue.Account, issue.User)
err := storeInStorage(ctx, storage, path, issue)
if err != nil {
return nil, err
}
return issue, nil
}
func storeUserIssue(ctx context.Context, storage logical.Storage, params IssueUserParameters) (*IssueUserStorage, error) {
path := getUserIssuePath(params.Operator, params.Account, params.User)
issue, err := getFromStorage[IssueUserStorage](ctx, storage, path)
if err != nil {
return nil, err
}
if issue == nil {
issue = &IssueUserStorage{}
}
issue.Claims = params.Claims
issue.Operator = params.Operator
issue.Account = params.Account
issue.User = params.User
issue.UseSigningKey = params.UseSigningKey
err = storeInStorage(ctx, storage, path, issue)
if err != nil {
return nil, err
}
return issue, nil
}
func issueUserNKeys(ctx context.Context, storage logical.Storage, issue IssueUserStorage) error {
// issue user nkey
p := NkeyParameters{
Operator: issue.Operator,
Account: issue.Account,
User: issue.User,
}
stored, err := readUserNkey(ctx, storage, p)
if err != nil {
return err
}
if stored == nil {
err := addUserNkey(ctx, storage, p)
if err != nil {
return err
}
}
log.Info().
Str("operator", issue.Operator).Str("account", issue.Account).Str("user", issue.User).
Msg("nkey assigned")
return nil
}
func issueUserJWT(ctx context.Context, storage logical.Storage, issue IssueUserStorage) error {
// use either operator nkey or signing nkey
// to sign jwt and add issuer claim
useSigningKey := issue.UseSigningKey
var seed []byte
accountNkey, err := readAccountNkey(ctx, storage, NkeyParameters{
Operator: issue.Operator,
Account: issue.Account,
})
if err != nil {
return fmt.Errorf("could not read operator nkey: %s", err)
}
if accountNkey == nil {
log.Warn().
Str("operator", issue.Operator).Str("account", issue.Account).Str("user", issue.User).
Msgf("account nkey does not exist: %s - Cannot create jwt.", issue.Account)
return nil
}
accountKeyPair, err := nkeys.FromSeed(accountNkey.Seed)
if err != nil {
return err
}
accountPublicKey, err := accountKeyPair.PublicKey()
if err != nil {
return err
}
if useSigningKey == "" {
seed = accountNkey.Seed
} else {
signingNkey, err := readAccountSigningNkey(ctx, storage, NkeyParameters{
Operator: issue.Operator,
Account: issue.Account,
Signing: useSigningKey,
})
if err != nil {
return fmt.Errorf("could not read signing nkey: %s", err)
}
if signingNkey == nil {
log.Error().
Str("operator", issue.Operator).Str("account", issue.Account).Str("user", issue.User).
Msgf("account signing nkey does not exist: %s - Cannot create jwt.", useSigningKey)
return fmt.Errorf("account signing nkey does not exist: %s - Cannot create JWT", useSigningKey)
}
seed = signingNkey.Seed
}
signingKeyPair, err := nkeys.FromSeed(seed)
if err != nil {
return err
}
signingPublicKey, err := signingKeyPair.PublicKey()
if err != nil {
return err
}
// receive user nkey puplic key
// to add subject
data, err := readUserNkey(ctx, storage, NkeyParameters{
Operator: issue.Operator,
Account: issue.Account,
User: issue.User,
})
if err != nil {
return fmt.Errorf("could not read user nkey: %s", err)
}
if data == nil {
return fmt.Errorf("user nkey does not exist")
}
userKeyPair, err := nkeys.FromSeed(data.Seed)
if err != nil {
return err
}
userPublicKey, err := userKeyPair.PublicKey()
if err != nil {
return err
}
if useSigningKey != "" {
issue.Claims.IssuerAccount = accountPublicKey
}
issue.Claims.ClaimsData.Subject = userPublicKey
issue.Claims.ClaimsData.Issuer = signingPublicKey
natsJwt, err := v1alpha1.Convert(&issue.Claims)
if err != nil {
return fmt.Errorf("could not convert claims to nats jwt: %s", err)
}
token, err := natsJwt.Encode(signingKeyPair)
if err != nil {
return fmt.Errorf("could not encode jwt: %s", err)
}
// store jwt
err = addUserJWT(ctx, storage, JWTParameters{
Operator: issue.Operator,
Account: issue.Account,
User: issue.User,
JWTStorage: JWTStorage{
JWT: token,
},
})
if err != nil {
return err
}
log.Info().
Str("operator", issue.Operator).Str("account", issue.Account).Str("user", issue.User).
Msgf("jwt created/updated")
return nil
}
func issueUserCreds(ctx context.Context, storage logical.Storage, issue IssueUserStorage) error {
// receive user nkey seed
// to add to creds file
userNkey, err := readUserNkey(ctx, storage, NkeyParameters{
Operator: issue.Operator,
Account: issue.Account,
User: issue.User,
})
if err != nil {
return fmt.Errorf("could not read user nkey: %s", err)
}
if userNkey == nil {
return fmt.Errorf("user nkey does not exist")
}
userKeyPair, err := nkeys.FromSeed(userNkey.Seed)
if err != nil {
return err
}
seed, err := userKeyPair.Seed()
if err != nil {
return err
}
// receive jwt
userJwt, err := readUserJWT(ctx, storage, JWTParameters{
Operator: issue.Operator,
Account: issue.Account,
User: issue.User,
})
if err != nil {
return fmt.Errorf("could not read user jwt: %s", err)
}
if userJwt == nil {
log.Warn().
Str("operator", issue.Operator).Str("account", issue.Account).Str("user", issue.User).
Msgf("user jwt does not exist: %s - Cannot create creds.", issue.Account)
return nil
}
// format creds
creds, err := jwt.FormatUserConfig(userJwt.JWT, seed)
if err != nil {
return fmt.Errorf("could not format user creds: %s", err)
}
// store creds
err = addUserCreds(ctx, storage, CredsParameters{
Operator: issue.Operator,
Account: issue.Account,
User: issue.User,
CredsStorage: CredsStorage{
Creds: string(creds),
},
})
if err != nil {
return err
}
return nil
}
func getUserIssuePath(operator string, account string, user string) string {
return "issue/operator/" + operator + "/account/" + account + "/user/" + user
}
func createResponseIssueUserData(issue *IssueUserStorage) (*logical.Response, error) {
data := &IssueUserData{
Operator: issue.Operator,
Account: issue.Account,
User: issue.User,
UseSigningKey: issue.UseSigningKey,
Claims: issue.Claims,
Status: issue.Status,
}
rval := map[string]interface{}{}
err := stm.StructToMap(data, &rval)
if err != nil {
return nil, err
}
resp := &logical.Response{
Data: rval,
}
return resp, nil
}
func updateUserStatus(ctx context.Context, storage logical.Storage, issue *IssueUserStorage) {
// account status
nkey, err := readUserNkey(ctx, storage, NkeyParameters{
Operator: issue.Operator,
Account: issue.Account,
User: issue.User,
})
if err == nil && nkey != nil {
issue.Status.User.Nkey = true
} else {
issue.Status.User.Nkey = false
}
jwt, err := readUserJWT(ctx, storage, JWTParameters{
Operator: issue.Operator,
Account: issue.Account,
User: issue.User,
})
if err == nil && jwt != nil {
issue.Status.User.JWT = true
} else {
issue.Status.User.JWT = false
}
}