/
generateprofile.go
736 lines (669 loc) · 16.5 KB
/
generateprofile.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
730
731
732
733
734
735
736
/*
* Copyright 2018-2023 The NATS Authors
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cmd
import (
"encoding/json"
"errors"
"fmt"
"net/url"
"os"
"path/filepath"
"strings"
"github.com/nats-io/jwt/v2"
"github.com/nats-io/nsc/v2/cmd/store"
"github.com/spf13/cobra"
)
func createProfileCmd() *cobra.Command {
var params ProfileCmdParams
var cmd = &cobra.Command{
Use: "profile",
Short: "Generate a profile from nsc 'URL' that can be used by tooling",
Example: `profile nsc://operator
nsc profile nsc://operator/account
nsc profile nsc://operator/account/user
nsc profile nsc://operator/account/user?names&seeds&keys
nsc profile nsc://operator/account/user?operatorSeed&accountSeed&userSeed
nsc profile nsc://operator/account/user?operatorKey&accountKey&userKey
nsc profile nsc://operator?key&seed
nsc profile nsc://operator/account?key&seed
nsc profile nsc://operator/account/user?key&seed&name
nsc profile nsc://operator/account/user?store=/a/.nsc/nats&keystore=/foo/.nkeys
Output of the program looks like:
{
"user_creds": "<filepath>",
"operator" : {
"service": "hostport"
}
}
The user_creds is printed if an user is specified
Other options (as query string arguments):
keystore=<dir> that specifies the location of the keystore
store=<dir> that specifies a directory that contains the named operator
[user|account|operator]Key - includes the public key for user, account,
operator, If no prefix (user/account/operator is provided, it targets
the last object in the configuration path)
keys - includes the public keys for all entities (same as
userKey&accountKey&operatorKey)
[user|account|operator]Seed=<optional public key> - include the seed for
user, account, operator, if an argument is provided, the seed for the
specified public key is provided - this allows targeting a signing key.
If no prefix (user/account/operator is provided, it targets the last
object in the configuration path)
seeds - includes the private keys for all entities (same as
userSeed&accountSeed&operatorSeed)
[user|account|operator]Name - includes the friendly name for the for
user, account, operator, If no prefix (user/account/operator is provided,
it targets the last object in the configuration path)
names - includes the friendly names for all the entities (same as
userName&accountName&operatorName)
`,
Args: cobra.MinimumNArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
us := args[0]
u, err := ParseNscURL(us)
if err != nil {
return fmt.Errorf("error parsing %q: %w", us, err)
}
config := GetConfig()
oldSR := config.StoreRoot
oldOp := config.Operator
oldAc := config.Account
defer func() {
_ = config.setStoreRoot(oldSR)
if oldOp != "" {
_ = config.SetOperator(oldOp)
}
if oldAc != "" {
_ = config.SetAccount(oldAc)
}
}()
params.nscu = u
q, err := u.query()
if err != nil {
return fmt.Errorf("error parsing query %q: %w", us, err)
}
if len(q) > 0 {
v, ok := q["store"]
if ok {
sr, err := Expand(v)
if err != nil {
return err
}
if err := config.setStoreRoot(sr); err != nil {
return err
}
if err := config.SetOperator(u.operator); err != nil {
return err
}
}
storeDir, ok := q[keystoreDir]
if ok {
ks, err := Expand(storeDir)
if err != nil {
return err
}
store.KeyStorePath = ks
}
}
if u.operator != "" {
if err := config.SetOperator(u.operator); err != nil {
return err
}
}
if u.account != "" {
if err := config.SetAccount(u.account); err != nil {
return err
}
}
return RunAction(cmd, args, ¶ms)
},
}
cmd.Flags().StringVarP(¶ms.outputFile, "output-file", "o", "--", "output file, '--' is stdout")
return cmd
}
func init() {
generateCmd.AddCommand(createProfileCmd())
}
type Arg string
const (
prefix = "nsc://"
operatorKey Arg = "operatorkey"
accountKey Arg = "accountkey"
userKey Arg = "userkey"
key Arg = "key"
allKeys Arg = "keys"
operatorSeed Arg = "operatorseed"
accountSeed Arg = "accountseed"
userSeed Arg = "userseed"
seed Arg = "seed"
allSeeds Arg = "seeds"
operatorName Arg = "operatorname"
accountName Arg = "accountname"
userName Arg = "username"
name Arg = "name"
allNames Arg = "names"
keystoreDir Arg = "keystore"
storeDir Arg = "store"
)
type ProfileCmdParams struct {
nscu *NscURL
results *Profile
conf *ToolConfig
oc *jwt.OperatorClaims
ac *jwt.AccountClaims
uc *jwt.UserClaims
outputFile string
}
type Details struct {
Service []string `json:"service,omitempty"`
Name string `json:"name,omitempty"`
Seed string `json:"seed,omitempty"`
Key string `json:"id,omitempty"`
}
type Profile struct {
UserCreds string `json:"user_creds,omitempty"`
Operator *Details `json:"operator,omitempty"`
Account *Details `json:"account,omitempty"`
User *Details `json:"user,omitempty"`
}
type NscURL struct {
operator string
account string
user string
qs string
}
type stringSet struct {
set map[string]string
}
func newStringSet() *stringSet {
var s stringSet
s.set = make(map[string]string)
return &s
}
func (u *stringSet) add(s string) {
u.set[strings.ToLower(s)] = s
}
func (u *stringSet) contains(s string) bool {
return u.set[strings.ToLower(s)] != ""
}
func (u *NscURL) getOperator() (string, error) {
return url.QueryUnescape(u.operator)
}
func (u *NscURL) getAccount() (string, error) {
return url.QueryUnescape(u.account)
}
func (u *NscURL) getUser() (string, error) {
return url.QueryUnescape(u.user)
}
func (u *NscURL) query() (map[Arg]string, error) {
q := strings.ToLower(u.qs)
m := make(map[Arg]string)
for _, e := range strings.Split(q, "&") {
kv := strings.Split(e, "=")
k := strings.ToLower(kv[0])
v := ""
if len(kv) == 2 {
s, err := url.QueryUnescape(kv[1])
if err != nil {
return nil, err
}
v = s
}
m[Arg(k)] = v
}
return m, nil
}
func ParseNscURL(u string) (*NscURL, error) {
var v NscURL
s := u
if !strings.HasPrefix(strings.ToLower(u), prefix) {
return nil, errors.New("invalid nsc url: expecting 'nsc://'")
}
s = s[len(prefix):]
qs := strings.Index(s, "?")
if qs > 0 {
v.qs = s[qs+1:]
s = s[:qs]
}
if s == "" {
return nil, errors.New("invalid nsc url: expecting an operator name")
}
a := strings.Split(s, "/")
if len(a) >= 1 {
v.operator = a[0]
}
if len(a) >= 2 {
v.account = a[1]
}
if len(a) >= 3 {
v.user = a[2]
}
return &v, nil
}
func (p *ProfileCmdParams) SetDefaults(_ ActionCtx) error {
return nil
}
func (p *ProfileCmdParams) PreInteractive(_ ActionCtx) error {
return nil
}
func (p *ProfileCmdParams) Load(_ ActionCtx) error {
return nil
}
func (p *ProfileCmdParams) PostInteractive(_ ActionCtx) error {
return nil
}
func (p *ProfileCmdParams) loadNames(c jwt.Claims) *stringSet {
names := newStringSet()
cd := c.Claims()
names.add(cd.Name)
names.add(cd.Subject)
payload := c.Payload()
_, ok := payload.(jwt.Operator)
if ok && p.conf.Operator != "" {
names.add(p.conf.Operator)
}
return names
}
// checkLoadOperator is used to check if the operator in the nsc: URL is a
// known operator, and thus needs to work no matter what the current context
// is; it will mutate the ctx Store appropriately and store away a conf.
func (p *ProfileCmdParams) checkLoadOperator(ctx ActionCtx) error {
p.conf = GetConfig()
var err error
// There's a sync mutex inside the store, we should try to only load each once.
allOperators := make(map[string]*store.Store)
aliases := make(map[string]string)
// We work with lower-cased aliases
lcURLOperator := strings.ToLower(p.nscu.operator)
// We need to be sure that we load all operators known to the local nsc store.
// Using ctx.StoreCtx().Store would only load the _current_ operator.
// We do still need to let the O.. nkey form be used though.
for _, opName := range p.conf.ListOperators() {
s, err := store.LoadStore(filepath.Join(p.conf.StoreRoot, opName))
if err != nil {
continue
}
oc, err := s.ReadOperatorClaim()
if err != nil {
continue
}
allOperators[strings.ToLower(opName)] = s
aliases[opName] = opName
aliases[strings.ToLower(opName)] = opName
for alias := range p.loadNames(oc).set {
allOperators[alias] = s
aliases[alias] = opName
}
}
if _, ok := allOperators[lcURLOperator]; !ok {
return fmt.Errorf("invalid operator %q: not known to current system", p.nscu.operator)
}
p.conf.Operator = aliases[lcURLOperator]
ctx.StoreCtx().Store = allOperators[lcURLOperator]
oc, err := ctx.StoreCtx().Store.ReadOperatorClaim()
if err != nil {
return fmt.Errorf("could not use alternative operator %q: %w", p.nscu.operator, err)
}
p.nscu.operator = oc.Name
p.oc = oc
return nil
}
func (p *ProfileCmdParams) checkLoadAccount(ctx ActionCtx) error {
if p.nscu.account == "" {
return nil
}
names, err := p.conf.ListAccounts()
if err != nil {
return err
}
m := make(map[string]string)
for _, n := range names {
m[strings.ToLower(n)] = n
}
an := m[strings.ToLower(p.nscu.account)]
if an != "" {
ac, err := ctx.StoreCtx().Store.ReadAccountClaim(an)
if err != nil {
return err
}
p.nscu.account = ac.Name
p.ac = ac
return nil
}
for _, n := range names {
ac, err := ctx.StoreCtx().Store.ReadAccountClaim(n)
if err != nil {
continue
}
aliases := p.loadNames(ac)
if aliases.contains(p.nscu.account) {
p.nscu.account = ac.Name
p.ac = ac
return nil
}
}
return fmt.Errorf("invalid account %q: account was not found", p.nscu.account)
}
func (p *ProfileCmdParams) checkLoadUser(ctx ActionCtx) error {
if p.nscu.user == "" {
return nil
}
names, err := ctx.StoreCtx().Store.ListEntries(store.Accounts, p.nscu.account, store.Users)
if err != nil {
return err
}
m := make(map[string]string)
for _, n := range names {
m[strings.ToLower(n)] = n
}
un := m[strings.ToLower(p.nscu.user)]
if un != "" {
uc, err := ctx.StoreCtx().Store.ReadUserClaim(p.nscu.account, un)
if err != nil {
return err
}
p.nscu.user = uc.Name
p.uc = uc
return nil
}
for _, n := range names {
uc, err := ctx.StoreCtx().Store.ReadUserClaim(p.nscu.account, n)
if err != nil {
continue
}
aliases := p.loadNames(uc)
if aliases.contains(p.nscu.user) {
p.nscu.user = uc.Name
p.uc = uc
return nil
}
}
return fmt.Errorf("invalid user %q: user was not found", p.nscu.user)
}
func (p *ProfileCmdParams) Validate(ctx ActionCtx) error {
if err := p.checkLoadOperator(ctx); err != nil {
return err
}
if err := p.checkLoadAccount(ctx); err != nil {
return err
}
return p.checkLoadUser(ctx)
}
func (p *ProfileCmdParams) addOperatorKeys() {
p.results.Operator.Key = p.oc.Subject
}
func (p *ProfileCmdParams) addAccountKeys() {
if p.results.Account == nil {
p.results.Account = &Details{}
}
p.results.Account.Key = p.ac.Subject
}
func (p *ProfileCmdParams) addUserKeys() {
if p.results.User == nil {
p.results.User = &Details{}
}
p.results.User.Key = p.uc.Subject
}
func (p *ProfileCmdParams) addKeys() error {
q, err := p.nscu.query()
if err != nil {
return err
}
if len(q) == 0 {
return nil
}
_, keys := q[allKeys]
_, ok := q[operatorKey]
if ok || keys {
p.addOperatorKeys()
}
_, ok = q[accountKey]
if ok || keys {
p.addAccountKeys()
}
_, ok = q[userKey]
if ok || keys {
p.addUserKeys()
}
_, ok = q[key]
if ok {
if p.nscu.user != "" {
p.addUserKeys()
} else if p.nscu.account != "" {
p.addAccountKeys()
} else {
p.addOperatorKeys()
}
}
return nil
}
func (p *ProfileCmdParams) getKeys(claim jwt.Claims) []string {
var keys []string
if claim != nil {
keys = append(keys, claim.Claims().Subject)
var payload = claim.Payload()
oc, ok := payload.(*jwt.Operator)
if ok {
keys = append(keys, oc.SigningKeys...)
}
ac, ok := payload.(*jwt.Account)
if ok {
keys = append(keys, ac.SigningKeys.Keys()...)
}
}
return keys
}
func (p *ProfileCmdParams) resolveSeed(ctx ActionCtx, s string, keys []string) (string, error) {
ks := ctx.StoreCtx().KeyStore
if s != "" {
found := false
s = strings.ToUpper(s)
for _, k := range keys {
if s == k {
found = true
break
}
}
if !found {
return "", fmt.Errorf("%q was not found", s)
}
if ks.HasPrivateKey(s) {
seed, err := ks.GetSeed(s)
if seed != "" && err == nil {
return seed, err
}
} else {
return "", fmt.Errorf("no seed was found for %q", keys[0])
}
}
for _, v := range keys {
if ks.HasPrivateKey(v) {
seed, err := ks.GetSeed(v)
if seed != "" && err == nil {
return seed, err
}
}
}
return "", fmt.Errorf("no seed was found for %q", keys[0])
}
func (p *ProfileCmdParams) addOperatorSeed(ctx ActionCtx, v string) error {
seed, err := p.resolveSeed(ctx, v, p.getKeys(p.oc))
if err != nil {
return err
}
p.results.Operator.Seed = seed
return nil
}
func (p *ProfileCmdParams) addAccountSeed(ctx ActionCtx, v string) error {
seed, err := p.resolveSeed(ctx, v, p.getKeys(p.ac))
if err != nil {
return err
}
if p.results.Account == nil {
p.results.Account = &Details{}
}
p.results.Account.Seed = seed
return nil
}
func (p *ProfileCmdParams) addUserSeed(ctx ActionCtx, v string) error {
seed, err := p.resolveSeed(ctx, v, p.getKeys(p.uc))
if err != nil {
return err
}
if p.results.User == nil {
p.results.User = &Details{}
}
p.results.User.Seed = seed
return nil
}
func (p *ProfileCmdParams) addSeeds(ctx ActionCtx) error {
q, err := p.nscu.query()
if err != nil {
return err
}
if len(q) == 0 {
return nil
}
_, seeds := q[allSeeds]
v, ok := q[operatorSeed]
if ok || seeds {
err := p.addOperatorSeed(ctx, v)
if err != nil {
return err
}
}
v, ok = q[accountSeed]
if ok || seeds {
err := p.addAccountSeed(ctx, v)
if err != nil {
return err
}
}
v, ok = q[userSeed]
if ok || seeds {
err := p.addUserSeed(ctx, v)
if err != nil {
return err
}
}
_, ok = q[seed]
if ok {
if p.nscu.user != "" {
err := p.addUserSeed(ctx, "")
if err != nil {
return err
}
}
if p.nscu.account != "" {
err := p.addAccountSeed(ctx, "")
if err != nil {
return err
}
}
if p.nscu.operator != "" {
err := p.addOperatorSeed(ctx, "")
if err != nil {
return err
}
}
}
return nil
}
func (p *ProfileCmdParams) addOperatorName() {
p.results.Operator.Name = p.conf.Operator
}
func (p *ProfileCmdParams) addAccountName() {
if p.results.Account == nil {
p.results.Account = &Details{}
}
p.results.Account.Name = p.ac.Name
}
func (p *ProfileCmdParams) addUserName() {
if p.results.User == nil {
p.results.User = &Details{}
}
p.results.User.Name = p.uc.Name
}
func (p *ProfileCmdParams) addNames() error {
q, err := p.nscu.query()
if err != nil {
return err
}
if len(q) == 0 {
return nil
}
_, names := q[allNames]
_, ok := q[operatorName]
if ok || names {
p.addOperatorName()
}
_, ok = q[accountName]
if ok || names {
p.addAccountName()
}
_, ok = q[userName]
if ok || names {
p.addUserName()
}
_, ok = q[name]
if ok {
if p.nscu.user != "" {
p.addUserName()
}
if p.nscu.account != "" {
p.addAccountName()
}
if p.nscu.operator != "" {
p.addOperatorName()
}
}
return nil
}
func (p *ProfileCmdParams) Run(ctx ActionCtx) (store.Status, error) {
p.results = &Profile{}
p.results.Operator = &Details{}
p.results.Operator.Service = p.oc.OperatorServiceURLs
if p.nscu.user != "" {
creds := ctx.StoreCtx().KeyStore.CalcUserCredsPath(p.nscu.account, p.nscu.user)
if _, err := os.Stat(creds); os.IsNotExist(err) {
// nothing
} else {
p.results.UserCreds = creds
}
}
if err := p.addNames(); err != nil {
return nil, err
}
if err := p.addKeys(); err != nil {
return nil, err
}
if err := p.addSeeds(ctx); err != nil {
return nil, err
}
v, err := json.MarshalIndent(p.results, "", " ")
v = append(v, '\n')
if err != nil {
return nil, err
}
if err := Write(p.outputFile, v); err != nil {
return nil, err
}
var s store.Status
if !IsStdOut(p.outputFile) {
s = store.OKStatus("wrote tool configuration to %#q", AbbrevHomePaths(p.outputFile))
}
return s, nil
}