-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathpaths_issue_operator.go
729 lines (655 loc) · 19.7 KB
/
paths_issue_operator.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
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
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"
accountv1 "github.com/edgefarm/vault-plugin-secrets-nats/pkg/claims/account/v1alpha1"
"github.com/edgefarm/vault-plugin-secrets-nats/pkg/claims/common"
operatorv1 "github.com/edgefarm/vault-plugin-secrets-nats/pkg/claims/operator/v1alpha1"
"github.com/edgefarm/vault-plugin-secrets-nats/pkg/stm"
)
type IssueOperatorStorage struct {
Operator string `json:"operator"`
CreateSystemAccount bool `json:"createSystemAccount"`
SyncAccountServer bool `json:"syncAccountServer"`
Claims operatorv1.OperatorClaims `json:"claims"`
}
// IssueOperatorParameters
// +k8s:deepcopy-gen=true
type IssueOperatorParameters struct {
Operator string `json:"operator"`
CreateSystemAccount bool `json:"createSystemAccount,omitempty"`
SyncAccountServer bool `json:"syncAccountServer,omitempty"`
Claims operatorv1.OperatorClaims `json:"claims,omitempty"`
}
type IssueOperatorData struct {
Operator string `json:"operator"`
CreateSystemAccount bool `json:"createSystemAccount"`
SyncAccountServer bool `json:"syncAccountServer"`
Claims operatorv1.OperatorClaims `json:"claims"`
Status IssueOperatorStatus `json:"status"`
}
type IssueOperatorStatus struct {
Operator IssueStatus `json:"operator"`
SystemAccount IssueStatus `json:"systemAccount"`
SystemAccountUser IssueStatus `json:"systemAccountUser"`
}
type IssueStatus struct {
Nkey bool `json:"nkey"`
JWT bool `json:"jwt"`
}
func pathOperatorIssue(b *NatsBackend) []*framework.Path {
return []*framework.Path{
{
Pattern: "issue/operator/" + framework.GenericNameRegex("operator") + "$",
Fields: map[string]*framework.FieldSchema{
"operator": {
Type: framework.TypeString,
Description: "operator identifier",
Required: false,
},
"createSystemAccount": {
Type: framework.TypeBool,
Description: "Create system account (default: false)",
Required: false,
},
"claims": {
Type: framework.TypeMap,
Description: "Operator claims (jwt.OperatorClaims from github.com/nats-io/jwt/v2)",
Required: false,
},
"syncAccountServer": {
Type: framework.TypeBool,
Description: "Sync account jwt's with account server",
Required: false,
},
},
Operations: map[logical.Operation]framework.OperationHandler{
logical.CreateOperation: &framework.PathOperation{
Callback: b.pathAddOperatorIssue,
},
logical.UpdateOperation: &framework.PathOperation{
Callback: b.pathAddOperatorIssue,
},
logical.ReadOperation: &framework.PathOperation{
Callback: b.pathReadOperatorIssue,
},
logical.DeleteOperation: &framework.PathOperation{
Callback: b.pathDeleteOperatorIssue,
},
},
HelpSynopsis: `Manages operator issueing.`,
HelpDescription: ``,
},
{
Pattern: "issue/operator/?$",
Operations: map[logical.Operation]framework.OperationHandler{
logical.ListOperation: &framework.PathOperation{
Callback: b.pathListOperatorIssues,
},
},
HelpSynopsis: "pathRoleListHelpSynopsis",
HelpDescription: "pathRoleListHelpDescription",
},
}
}
func (b *NatsBackend) pathAddOperatorIssue(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 := IssueOperatorParameters{}
json.Unmarshal(jsonString, ¶ms)
err = addOperatorIssue(ctx, req.Storage, params)
if err != nil {
return logical.ErrorResponse(AddingIssueFailedError + ":" + err.Error()), nil
}
return nil, nil
}
func (b *NatsBackend) pathReadOperatorIssue(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 := IssueOperatorParameters{}
json.Unmarshal(jsonString, ¶ms)
issue, err := readOperatorIssue(ctx, req.Storage, params)
if err != nil {
return logical.ErrorResponse(ReadingIssueFailedError), nil
}
if issue == nil {
return logical.ErrorResponse(IssueNotFoundError), nil
}
status := getIssueOperatorStatus(ctx, req.Storage, issue)
return createResponseIssueOperatorData(issue, status)
}
func (b *NatsBackend) pathListOperatorIssues(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
err := data.Validate()
if err != nil {
return logical.ErrorResponse(InvalidParametersError), logical.ErrInvalidRequest
}
entries, err := listOperatorIssues(ctx, req.Storage)
if err != nil {
return logical.ErrorResponse(ListIssuesFailedError), nil
}
return logical.ListResponse(entries), nil
}
func (b *NatsBackend) pathDeleteOperatorIssue(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 := IssueOperatorParameters{}
json.Unmarshal(jsonString, ¶ms)
// delete issue and all related nkeys and jwt
err = deleteOperatorIssue(ctx, req.Storage, params)
if err != nil {
return logical.ErrorResponse(DeleteIssueFailedError), nil
}
return nil, nil
}
func addOperatorIssue(ctx context.Context, storage logical.Storage, params IssueOperatorParameters) error {
log.Info().
Str("operator", params.Operator).
Msgf("issue operator")
// store issue
issue, err := storeOperatorIssue(ctx, storage, params)
if err != nil {
return err
}
err = refreshOperator(ctx, storage, issue)
if err != nil {
return err
}
return refreshAccountResolvers(ctx, storage, issue)
}
func refreshAccountResolvers(ctx context.Context, storage logical.Storage, issue *IssueOperatorStorage) error {
if !issue.SyncAccountServer || issue.Claims.AccountServerURL == "" {
log.Info().Msgf("%s: account server sync disabled", issue.Operator)
return nil
}
pushUser, err := readUserIssue(ctx, storage, IssueUserParameters{
Operator: issue.Operator,
Account: DefaultSysAccountName,
User: DefaultPushUser,
})
if err != nil {
return err
}
if pushUser != nil {
if pushUser.Status.User.JWT {
accounts, err := listAccountIssues(ctx, storage, issue.Operator)
if err != nil {
return err
}
for _, account := range accounts {
err = refreshAccountResolverPush(ctx, storage, &IssueAccountStorage{
Operator: issue.Operator,
Account: account,
})
if err != nil {
return err
}
}
} else {
// todo warning push user does not exist
log.Warn().Str("operator", issue.Operator).Msg("cannot refresh account resolvers, push user has no JWT yet")
}
} else {
// todo warning does not exist
log.Warn().Str("operator", issue.Operator).Msg("cannot refresh account resolvers, push user does not exist")
}
return nil
}
func refreshOperator(ctx context.Context, storage logical.Storage, issue *IssueOperatorStorage) error {
// create nkey and signing nkeys
err := issueOperatorNkeys(ctx, storage, *issue)
if err != nil {
return err
}
// create jwt
err = issueOperatorJWT(ctx, storage, *issue)
if err != nil {
return err
}
if issue.CreateSystemAccount {
// create system account
err := issueSystemAccount(ctx, storage, *issue)
if err != nil {
return err
}
}
return nil
}
func readOperatorIssue(ctx context.Context, storage logical.Storage, params IssueOperatorParameters) (*IssueOperatorStorage, error) {
path := getOperatorIssuePath(params.Operator)
return getFromStorage[IssueOperatorStorage](ctx, storage, path)
}
func listOperatorIssues(ctx context.Context, storage logical.Storage) ([]string, error) {
path := getOperatorIssuePath("")
return listIssues(ctx, storage, path)
}
func deleteOperatorIssue(ctx context.Context, storage logical.Storage, params IssueOperatorParameters) error {
// get stored signing keys
issue, err := readOperatorIssue(ctx, storage, params)
if err != nil {
return err
}
if issue == nil {
// nothing to delete
return nil
}
// delete operator nkey
nkey := NkeyParameters{
Operator: issue.Operator,
}
err = deleteOperatorNkey(ctx, storage, nkey)
if err != nil {
return err
}
// delete operator siginig nkeys
for _, signingKey := range issue.Claims.SigningKeys {
nkey := NkeyParameters{
Operator: issue.Operator,
Signing: signingKey,
}
err := deleteOperatorSigningNkey(ctx, storage, nkey)
if err != nil {
return err
}
}
// if generated, delete system account
if issue.CreateSystemAccount {
err := deleteUserIssue(ctx, storage, IssueUserParameters{
Operator: issue.Operator,
Account: DefaultSysAccountName,
User: DefaultPushUser,
})
if err != nil {
return err
}
err = deleteAccountIssue(ctx, storage, IssueAccountParameters{
Operator: issue.Operator,
Account: DefaultSysAccountName,
})
if err != nil {
return err
}
}
// delete operator jwt
jwt := JWTParameters{
Operator: issue.Operator,
}
err = deleteOperatorJWT(ctx, storage, jwt)
if err != nil {
return err
}
// delete operator issue
path := getOperatorIssuePath(params.Operator)
return deleteFromStorage(ctx, storage, path)
}
func storeOperatorIssue(ctx context.Context, storage logical.Storage, params IssueOperatorParameters) (*IssueOperatorStorage, error) {
path := getOperatorIssuePath(params.Operator)
issue, err := getFromStorage[IssueOperatorStorage](ctx, storage, path)
if err != nil {
return nil, err
}
if issue == nil {
issue = &IssueOperatorStorage{}
} else {
// diff current and incomming signing keys
// delete removed signing keys
for _, signingKey := range issue.Claims.SigningKeys {
contains := func(a []string, x string) bool {
for _, n := range a {
if x == n {
return true
}
}
return false
}
if !contains(params.Claims.SigningKeys, signingKey) {
p := NkeyParameters{
Operator: params.Operator,
Signing: signingKey,
}
err := deleteOperatorSigningNkey(ctx, storage, p)
if err != nil {
return nil, err
}
}
}
}
issue.Claims = params.Claims
issue.Operator = params.Operator
issue.CreateSystemAccount = params.CreateSystemAccount
issue.Claims.SigningKeys = params.Claims.SigningKeys
issue.Claims.AccountServerURL = params.Claims.AccountServerURL
issue.SyncAccountServer = params.SyncAccountServer
err = storeInStorage(ctx, storage, path, issue)
if err != nil {
return nil, err
}
return issue, nil
}
func issueOperatorNkeys(ctx context.Context, storage logical.Storage, issue IssueOperatorStorage) error {
var refreshAccounts bool
// issue operator nkey
p := NkeyParameters{
Operator: issue.Operator,
}
stored, err := readOperatorNkey(ctx, storage, p)
if err != nil {
return err
}
if stored == nil {
err := addOperatorNkey(ctx, storage, p)
if err != nil {
return err
}
refreshAccounts = true
}
// issue operator siginig nkeys
for _, signingKey := range issue.Claims.SigningKeys {
p := NkeyParameters{
Operator: issue.Operator,
Signing: signingKey,
}
stored, err := readOperatorSigningNkey(ctx, storage, p)
if err != nil {
return err
}
if stored == nil {
err := addOperatorSigningNkey(ctx, storage, p)
if err != nil {
return err
}
refreshAccounts = true
}
}
if refreshAccounts {
// force update of all existing accounts
// so they can use the new operator nkey to sign their jwt
log.Info().Str("operator", issue.Operator).Msg("managed nkeys modified, all accounts will be updated")
err = updateAccountIssues(ctx, storage, issue)
if err != nil {
log.Err(err).Str("operator", issue.Operator).Msg("failed to update accounts")
return err
}
}
log.Info().
Str("operator", issue.Operator).Msgf("nkey assigned")
return nil
}
func issueOperatorJWT(ctx context.Context, storage logical.Storage, issue IssueOperatorStorage) error {
// receive operator nkey and puplic key
data, err := readOperatorNkey(ctx, storage, NkeyParameters{
Operator: issue.Operator,
})
if err != nil {
return fmt.Errorf("could not read operator nkey: %s", err)
}
operatorKeyPair, err := nkeys.FromSeed(data.Seed)
if err != nil {
return err
}
operatorPublicKey, err := operatorKeyPair.PublicKey()
if err != nil {
return err
}
// receive public key of system account
sysAccountPublicKey := ""
data, err = readAccountNkey(ctx, storage, NkeyParameters{
Operator: issue.Operator,
Account: DefaultSysAccountName,
})
if err != nil {
return fmt.Errorf("could not read system account nkey: %s", err)
}
if data != nil {
// log.Warn().
// Str("operator", issue.Operator).
// Msgf("system account nkey does not exist: %s - Cannot create jwt.", DefaultSysAccountName)
// return nil
// } else {
sysAccountKeyPair, err := nkeys.FromSeed(data.Seed)
if err != nil {
return fmt.Errorf("could not convert system account nkey to kp: %s", err)
}
sysAccountPublicKey, err = sysAccountKeyPair.PublicKey()
if err != nil {
return fmt.Errorf("could not extract pulic key from system account nkey: %s", err)
}
}
// receive public keys of signing keys
var signingPublicKeys []string
for _, signingKey := range issue.Claims.SigningKeys {
data, err := readOperatorSigningNkey(ctx, storage, NkeyParameters{
Operator: issue.Operator,
Signing: signingKey,
})
if err != nil {
return err
}
if data == nil {
log.Warn().
Str("operator", issue.Operator).
Msgf("signing nkey does not exist: %s - Cannot create jwt.", signingKey)
continue
}
signingKeyPair, err := nkeys.FromSeed(data.Seed)
if err != nil {
return err
}
signingKey, err := signingKeyPair.PublicKey()
if err != nil {
return err
}
signingPublicKeys = append(signingPublicKeys, signingKey)
}
issue.Claims.ClaimsData.Subject = operatorPublicKey
issue.Claims.ClaimsData.Issuer = operatorPublicKey
issue.Claims.Operator.SystemAccount = sysAccountPublicKey
issue.Claims.Operator.SigningKeys = signingPublicKeys
natsJwt := operatorv1.Convert(&issue.Claims)
token, err := natsJwt.Encode(operatorKeyPair)
if err != nil {
return fmt.Errorf("could not encode operator jwt: %s", err)
}
// store operator jwt
err = addOperatorJWT(ctx, storage, JWTParameters{
Operator: issue.Operator,
JWTStorage: JWTStorage{
JWT: token,
},
})
if err != nil {
return err
}
log.Info().
Str("operator", issue.Operator).
Msgf("jwt created/updated")
return nil
}
func issueSystemAccount(ctx context.Context, storage logical.Storage, issue IssueOperatorStorage) error {
// create system account jwt and nkey
err := addAccountIssue(ctx, storage, IssueAccountParameters{
Operator: issue.Operator,
Account: DefaultSysAccountName,
Claims: accountv1.AccountClaims{
Account: accountv1.Account{
Imports: []accountv1.Import{},
Exports: []accountv1.Export{
{
Name: "account-monitoring-services",
Subject: "$SYS.REQ.ACCOUNT.*.*",
Type: "Service",
ResponseType: jwt.ResponseTypeStream,
AccountTokenPosition: 4,
Info: common.Info{
Description: `Request account specific monitoring services for: SUBSZ, CONNZ, LEAFZ, JSZ and INFO`,
InfoURL: "https://docs.nats.io/nats-server/configuration/sys_accounts",
},
},
{
Name: "account-monitoring-streams",
Subject: "$SYS.ACCOUNT.*.>",
Type: "Stream",
AccountTokenPosition: 3,
Info: common.Info{
Description: `Account specific monitoring stream`,
InfoURL: "https://docs.nats.io/nats-server/configuration/sys_accounts",
},
},
},
Limits: accountv1.OperatorLimits{
NatsLimits: common.NatsLimits{
Subs: -1,
Data: -1,
Payload: -1,
},
AccountLimits: accountv1.AccountLimits{
Imports: -1,
Exports: -1,
WildcardExports: true,
Conn: -1,
LeafNodeConn: -1,
},
},
DefaultPermissions: common.Permissions{
Pub: common.Permission{
Allow: []string{},
Deny: []string{},
},
Sub: common.Permission{
Allow: []string{},
Deny: []string{},
},
},
},
},
})
if err != nil {
return err
}
// create system account user jwt and nkey
err = addUserIssue(ctx, storage, IssueUserParameters{
Operator: issue.Operator,
Account: DefaultSysAccountName,
User: DefaultPushUser,
})
if err != nil {
return err
}
return nil
}
func updateAccountIssues(ctx context.Context, storage logical.Storage, issue IssueOperatorStorage) error {
accounts, err := listAccountIssues(ctx, storage, issue.Operator)
if err != nil {
return err
}
for _, account := range accounts {
acc, err := readAccountIssue(ctx, storage, IssueAccountParameters{
Operator: issue.Operator,
Account: account,
})
if err != nil {
return err
}
if acc == nil {
return err
}
err = refreshAccount(ctx, storage, acc)
if err != nil {
return err
}
}
return nil
}
func getOperatorIssuePath(operator string) string {
return "issue/operator/" + operator
}
func getIssueOperatorStatus(ctx context.Context, storage logical.Storage, issue *IssueOperatorStorage) *IssueOperatorStatus {
var status IssueOperatorStatus
// operator status
nkey, err := readOperatorNkey(ctx, storage, NkeyParameters{
Operator: issue.Operator,
})
if err == nil && nkey != nil {
status.Operator.Nkey = true
}
jwt, err := readOperatorJWT(ctx, storage, JWTParameters{
Operator: issue.Operator,
})
if err == nil && jwt != nil {
status.Operator.JWT = true
}
// sys account status
nkey, err = readAccountNkey(ctx, storage, NkeyParameters{
Operator: issue.Operator,
Account: DefaultSysAccountName,
})
if err == nil && nkey != nil {
status.SystemAccount.Nkey = true
}
jwt, err = readAccountJWT(ctx, storage, JWTParameters{
Operator: issue.Operator,
Account: DefaultSysAccountName,
})
if err == nil && jwt != nil {
status.SystemAccount.JWT = true
}
// sys account user status
nkey, err = readUserNkey(ctx, storage, NkeyParameters{
Operator: issue.Operator,
Account: DefaultSysAccountName,
User: DefaultPushUser,
})
if err == nil && nkey != nil {
status.SystemAccountUser.Nkey = true
}
jwt, err = readUserJWT(ctx, storage, JWTParameters{
Operator: issue.Operator,
Account: DefaultSysAccountName,
User: DefaultPushUser,
})
if err == nil && jwt != nil {
status.SystemAccountUser.JWT = true
}
return &status
}
func createResponseIssueOperatorData(issue *IssueOperatorStorage, status *IssueOperatorStatus) (*logical.Response, error) {
data := &IssueOperatorData{
Operator: issue.Operator,
CreateSystemAccount: issue.CreateSystemAccount,
SyncAccountServer: issue.SyncAccountServer,
Claims: issue.Claims,
Status: *status,
}
rval := map[string]interface{}{}
err := stm.StructToMap(data, &rval)
if err != nil {
return nil, err
}
resp := &logical.Response{
Data: rval,
}
return resp, nil
}