forked from kionsoftware/kion-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
711 lines (637 loc) · 18.8 KB
/
main.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
package main
import (
"errors"
"fmt"
"log"
"os"
"path/filepath"
"strings"
"time"
"github.com/kionsoftware/kion-cli/lib/helper"
"github.com/kionsoftware/kion-cli/lib/kion"
"github.com/kionsoftware/kion-cli/lib/structs"
"github.com/fatih/color"
samlTypes "github.com/russellhaering/gosaml2/types"
"github.com/urfave/cli/v2"
)
////////////////////////////////////////////////////////////////////////////////
// //
// Globals //
// //
////////////////////////////////////////////////////////////////////////////////
var (
config structs.Configuration
configPath string
configFile = ".kion.yml"
)
////////////////////////////////////////////////////////////////////////////////
// //
// Context Helpers //
// //
////////////////////////////////////////////////////////////////////////////////
// setEndpoint sets the target Kion installation to interact with. If not
// passed to the tool as an argument, set in the env, or present in the
// configuration dotfile it will prompt the user to provide it.
func setEndpoint(cCtx *cli.Context) error {
if cCtx.Value("endpoint") == "" {
kionURL, err := helper.PromptInput("Kion URL:")
if err != nil {
return err
}
err = cCtx.Set("endpoint", kionURL)
if err != nil {
return err
}
}
return nil
}
// AuthUNPW prompts for any missing credentials then auths the users against
// Kion, stores the session data, and sets the context token.
func AuthUNPW(cCtx *cli.Context) error {
var err error
un := cCtx.String("user")
pw := cCtx.String("password")
idmsID := cCtx.Uint("idms")
// prompt idms if needed
if idmsID == 0 {
idmss, err := kion.GetIDMSs(cCtx.String("endpoint"))
if err != nil {
return err
}
iNames, iMap := helper.MapIDMSs(idmss)
if len(iNames) > 1 {
idms, err := helper.PromptSelect("Select Login IDMS:", iNames)
if err != nil {
return err
}
idmsID = iMap[idms].ID
} else {
idmsID = iMap[iNames[0]].ID
}
}
// prompt username if needed
if un == "" {
un, err = helper.PromptInput("Username:")
if err != nil {
return err
}
}
// prompt password if needed
if pw == "" {
pw, err = helper.PromptPassword("Password:")
if err != nil {
return err
}
}
// auth and capture our session
config.Session, err = kion.Authenticate(cCtx.String("endpoint"), idmsID, un, pw)
if err != nil {
return err
}
config.Session.IDMSID = idmsID
config.Session.UserName = un
err = helper.SaveSession(configPath, config)
if err != nil {
return err
}
return cCtx.Set("token", config.Session.Access.Token)
}
// AuthSAML directs the user to authenticte via SAML in a web browser.
// The SAML assertion is posted to this app which is forwarded to Kion and
// exchanged for the context token.
func AuthSAML(cCtx *cli.Context) error {
var err error
samlMetadataFile := cCtx.String("saml-metadata-file")
samlServiceProviderIssuer := cCtx.String("saml-sp-issuer")
// prompt metadata url if needed
if samlMetadataFile == "" {
samlMetadataFile, err = helper.PromptInput("SAML Metadata URL:")
if err != nil {
return err
}
}
// prompt issuer if needed
if samlServiceProviderIssuer == "" {
samlServiceProviderIssuer, err = helper.PromptInput("SAML Service Provider Issuer:")
if err != nil {
return err
}
}
var samlMetadata *samlTypes.EntityDescriptor
if strings.HasPrefix(samlMetadataFile, "http") {
samlMetadata, err = kion.DownloadSAMLMetadata(samlMetadataFile)
if err != nil {
return err
}
} else {
samlMetadata, err = kion.ReadSAMLMetadataFile(samlMetadataFile)
if err != nil {
return err
}
}
authData, err := kion.AuthenticateSAML(
cCtx.String("endpoint"),
samlMetadata,
samlServiceProviderIssuer)
if err != nil {
return err
}
return cCtx.Set("token", authData.AuthToken)
}
// setAuthToken sets the token to be used for querying the Kion API. If not
// passed to the tool as an argument, set in the env, or present in the
// configuration dotfile it will prompt the users to authenticate.
func setAuthToken(cCtx *cli.Context) error {
if cCtx.Value("token") == "" {
// if we still have an active session use it
if config.Session.Access.Expiry != "" {
timeFormat := "2006-01-02T15:04:05-0700"
now := time.Now()
expiration, err := time.Parse(timeFormat, config.Session.Access.Expiry)
if err != nil {
return err
}
if expiration.After(now) {
err := cCtx.Set("token", config.Session.Access.Token)
if err != nil {
return err
}
return nil
}
// TODO: uncomment when / if the application supports refresh tokens
// see if we can use the refresh token
// refresh_exp, err := time.Parse(timeFormat, config.Session.Refresh.Expiry)
// if err != nil {
// return err
// }
// if refresh_exp.After(now) {
// un := config.Session.UserName
// idmsId := config.Session.IDMSID
// config.Session, err = kion.Authenticate(cCtx.String("endpoint"), idmsId, un, config.Session.Refresh.Token)
// if err != nil {
// return err
// }
// config.Session.UserName = un
// config.Session.IDMSID = idmsId
// err = helper.SaveSession(configPath, config)
// if err != nil {
// return err
// }
// return cCtx.Set("token", config.Session.Access.Token)
// }
}
// check un / pw were set via flags and infer auth method
if cCtx.String("user") != "" || cCtx.String("password") != "" {
err := AuthUNPW(cCtx)
return err
}
if cCtx.String("saml-metadata-file") != "" && cCtx.String("saml-sp-issuer") != "" {
err := AuthSAML(cCtx)
return err
}
// if no token or session found, prompt for desired auth method
methods := []string{
"API Key",
"Password",
"SAML",
}
authMethod, err := helper.PromptSelect("How would you like to authenticate", methods)
if err != nil {
return err
}
// handle chosen auth method
switch authMethod {
case "API Key":
apiKey, err := helper.PromptPassword("API Key:")
if err != nil {
return err
}
err = cCtx.Set("token", apiKey)
if err != nil {
return err
}
case "Password":
err := AuthUNPW(cCtx)
if err != nil {
return err
}
case "SAML":
err := AuthSAML(cCtx)
if err != nil {
return err
}
}
}
return nil
}
////////////////////////////////////////////////////////////////////////////////
// //
// Commands //
// //
////////////////////////////////////////////////////////////////////////////////
// beforeCommands run after the context is ready but before any subcommands are
// executed.
func beforeCommands(cCtx *cli.Context) error {
return nil
}
// Prompt for authentication and ensure auth token is set
func authCommand(cCtx *cli.Context) error {
// run propmts for any missing items
err := setEndpoint(cCtx)
if err != nil {
return err
}
err = setAuthToken(cCtx)
if err != nil {
return err
}
return nil
}
// genStaks generates short term access keys by walking users through an
// interactive prompt. Short term access keys are either printed to stdout or a
// subshell is created with them set in the environment.
func genStaks(cCtx *cli.Context) error {
// handle auth
err := authCommand(cCtx)
if err != nil {
return err
}
// walk user through the propt workflow to select a car
car, err := helper.CARSelector(cCtx)
if err != nil {
return err
}
// generate short term tokens
stak, err := kion.GetSTAK(cCtx.String("endpoint"), cCtx.String("token"), car.Name, car.AccountNumber)
if err != nil {
return err
}
// print or create subshell
if cCtx.Bool("print") {
return helper.PrintSTAK(os.Stdout, stak)
} else {
return helper.CreateSubShell(car.AccountNumber, car.AccountName, car.Name, stak)
}
}
// favorites generates short term access keys or launches the web console
// from stored favorites. If a favorite is found that matches the passed
// argument it is used, otherwise the user is walked through a wizard to make a
// selection.
func favorites(cCtx *cli.Context) error {
// map our favorites for ease of use
fNames, fMap := helper.MapFavs(config.Favorites)
// if arg passed is a valid favorite use it else prompt
var fav string
var err error
if fMap[cCtx.Args().First()] != (structs.Favorite{}) {
fav = cCtx.Args().First()
} else {
fav, err = helper.PromptSelect("Choose a Favorite:", fNames)
if err != nil {
return err
}
}
// handle auth
err = authCommand(cCtx)
if err != nil {
return err
}
// grab the favorite object
favorite := fMap[fav]
// determine favorite action, default to cli unless explicitly set to web
if favorite.AccessType == "web" {
var car kion.CAR
// attempt to find exact match then fallback to first match
car, err = kion.GetCARByNameAndAccount(cCtx.String("endpoint"), cCtx.String("token"), favorite.CAR, favorite.Account)
if err != nil {
car, err = kion.GetCARByName(cCtx.String("endpoint"), cCtx.String("token"), favorite.CAR)
if err != nil {
return err
}
car.AccountNumber = favorite.Account
}
url, err := kion.GetFederationURL(cCtx.String("endpoint"), cCtx.String("token"), car)
if err != nil {
return err
}
fmt.Printf("Federating into %s (%s) via %s\n", favorite.Name, favorite.Account, car.AwsIamRoleName)
return helper.OpenBrowser(url)
} else {
// generate stak
stak, err := kion.GetSTAK(cCtx.String("endpoint"), cCtx.String("token"), favorite.CAR, favorite.Account)
if err != nil {
return err
}
// print or create subshell
if cCtx.Bool("print") {
return helper.PrintSTAK(os.Stdout, stak)
} else {
return helper.CreateSubShell(favorite.Account, favorite.Name, favorite.CAR, stak)
}
}
}
// fedConsole opens the csp console for the selected account and cloud access
// role in the users default browser.
func fedConsole(cCtx *cli.Context) error {
// handle auth
err := authCommand(cCtx)
if err != nil {
return err
}
// walk user through the prompt workflow to select a car
car, err := helper.CARSelector(cCtx)
if err != nil {
return err
}
// TODO: handle arg if passed else run prompts
url, err := kion.GetFederationURL(cCtx.String("endpoint"), cCtx.String("token"), car)
if err != nil {
return err
}
return helper.OpenBrowser(url)
}
// listFavorites prints out the users stored favorites. Extra information is
// provided if the verbose flag is set.
func listFavorites(cCtx *cli.Context) error {
// map our favorites for ease of use
fNames, fMap := helper.MapFavs(config.Favorites)
// print it out
if cCtx.Bool("verbose") {
for _, f := range fMap {
accessType := f.AccessType
if accessType == "" {
accessType = "cli (Default)"
}
fmt.Printf(" %v:\n account number: %v\n cloud access role: %v\n access type: %v\n", f.Name, f.Account, f.CAR, accessType)
}
} else {
for _, f := range fNames {
fmt.Printf(" %v\n", f)
}
}
return nil
}
// runCommand generates creds for an AWS account then executes the user
// provided command with said credentials set.
func runCommand(cCtx *cli.Context) error {
if cCtx.String("fav") != "" {
// map our favorites for ease of use
_, fMap := helper.MapFavs(config.Favorites)
// if arg passed is a valid favorite use it else prompt
var fav string
var err error
if fMap[cCtx.String("fav")] != (structs.Favorite{}) {
fav = cCtx.String("fav")
} else {
return errors.New("can't find fav")
}
// handle auth
err = authCommand(cCtx)
if err != nil {
return err
}
// generate stak
favorite := fMap[fav]
stak, err := kion.GetSTAK(cCtx.String("endpoint"), cCtx.String("token"), favorite.CAR, favorite.Account)
if err != nil {
return err
}
err = helper.RunCommand(favorite.Account, favorite.Name, favorite.CAR, stak, cCtx.Args().First(), cCtx.Args().Tail()...)
if err != nil {
return err
}
} else if cCtx.String("account") != "" && cCtx.String("car") != "" {
err := authCommand(cCtx)
if err != nil {
return err
}
account, err := kion.GetAccount(cCtx.String("endpoint"), cCtx.String("token"), cCtx.String("account"))
if err != nil {
return err
}
// get a list of cloud access roles, then build a list of names and lookup map
cars, err := kion.GetCARSOnAccount(cCtx.String("endpoint"), cCtx.String("token"), account.ID)
if err != nil {
return err
}
car, err := helper.FindCARByName(cars, cCtx.String("car"))
if err != nil {
return err
}
stak, err := kion.GetSTAK(cCtx.String("endpoint"), cCtx.String("token"), car.Name, account.Number)
if err != nil {
return err
}
err = helper.RunCommand(account.Number, account.Name, car.Name, stak, cCtx.Args().First(), cCtx.Args().Tail()...)
if err != nil {
return err
}
} else {
return errors.New("must specify either --fav OR --account and --car parameters")
}
return nil
}
// afterCommands run after any subcommands are executed.
func afterCommands(cCtx *cli.Context) error {
return nil
}
////////////////////////////////////////////////////////////////////////////////
// //
// Main //
// //
////////////////////////////////////////////////////////////////////////////////
// main defines the command line utilities api. This should probably be broken
// out into its own function some day.
func main() {
// get home directory
home, err := os.UserHomeDir()
if err != nil {
log.Fatal(err)
}
// set global for config path
configPath = filepath.Join(home, configFile)
// load configuration file
err = helper.LoadConfig(configPath, &config)
if err != nil {
log.Fatal(err)
}
// prep default text for password
passwordDefaultText := ""
if config.Kion.Password != "" {
passwordDefaultText = "*****"
}
// prep default text for api key
apiKeyDefaultText := ""
if config.Kion.ApiKey != "" {
apiKeyDefaultText = "*****"
}
// convert relative path specified in config file to absolute path
samlMetadataFile := config.Kion.SamlMetadataFile
if samlMetadataFile != "" && !strings.HasPrefix(samlMetadataFile, "http") {
if !filepath.IsAbs(samlMetadataFile) {
// Resolve the file path relative to the config path, which is the home directory
samlMetadataFile = filepath.Join(filepath.Dir(configPath), samlMetadataFile)
}
}
// define app configuration
app := &cli.App{
////////////////
// Metadata //
////////////////
Name: "Kion CLI",
Version: "v0.0.2",
Usage: "Kion federation on the command line!",
EnableBashCompletion: true,
Before: beforeCommands,
After: afterCommands,
////////////////////
// Global Flags //
////////////////////
Flags: []cli.Flag{
&cli.StringFlag{
Name: "endpoint",
Aliases: []string{"e"},
Value: config.Kion.Url,
EnvVars: []string{"KION_URL"},
Usage: "Kion `URL`",
Destination: &config.Kion.Url,
},
&cli.StringFlag{
Name: "user",
Aliases: []string{"u"},
Value: config.Kion.Username,
EnvVars: []string{"KION_USERNAME"},
Usage: "`USERNAME` for authentication",
Destination: &config.Kion.Username,
},
&cli.StringFlag{
Name: "password",
Aliases: []string{"p"},
Value: config.Kion.Password,
EnvVars: []string{"KION_PASSWORD"},
Usage: "`PASSWORD` for authentication",
Destination: &config.Kion.Password,
DefaultText: passwordDefaultText,
},
&cli.StringFlag{
Name: "idms",
Aliases: []string{"i"},
Value: config.Kion.IDMS,
EnvVars: []string{"KION_IDMS_ID"},
Usage: "`IDMSID` for authentication",
Destination: &config.Kion.IDMS,
},
&cli.StringFlag{
Name: "saml-metadata-file",
Value: samlMetadataFile,
EnvVars: []string{"KION_SAML_METADATA_FILE"},
Usage: "SAML metadata `FILE` or URL",
Destination: &config.Kion.SamlMetadataFile,
},
&cli.StringFlag{
Name: "saml-sp-issuer",
Value: config.Kion.SamlIssuer,
EnvVars: []string{"KION_SAML_SP_ISSUER"},
Usage: "SAML Service Provider `ISSUER`",
Destination: &config.Kion.SamlIssuer,
},
&cli.StringFlag{
Name: "token",
Aliases: []string{"t"},
Value: config.Kion.ApiKey,
EnvVars: []string{"KION_API_KEY"},
Usage: "`TOKEN` for authentication",
Destination: &config.Kion.ApiKey,
DefaultText: apiKeyDefaultText,
},
},
////////////////
// Commands //
////////////////
Commands: []*cli.Command{
{
Name: "stak",
Aliases: []string{"s"},
Usage: "Generate short-term access keys",
Action: genStaks,
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "print",
Aliases: []string{"p"},
Usage: "print stak only",
},
},
},
{
Name: "console",
Aliases: []string{"con", "c"},
Usage: "Federate into the web console",
Action: fedConsole,
},
{
Name: "favorite",
Aliases: []string{"fav", "f"},
Usage: "Access favorites via web console or a stak for CLI usage",
ArgsUsage: "[FAVORITE_NAME]",
Action: favorites,
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "print",
Aliases: []string{"p"},
Usage: "print stak only",
},
},
BashComplete: func(cCtx *cli.Context) {
// complete if no args are passed
if cCtx.NArg() > 0 {
return
}
// else pass favorites
fNames, _ := helper.MapFavs(config.Favorites)
for _, f := range fNames {
fmt.Println(f)
}
},
Subcommands: []*cli.Command{
{
Name: "list",
Usage: "list favorites",
Action: listFavorites,
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "verbose",
Aliases: []string{"v"},
Usage: "show full favorite details",
},
},
},
},
},
{
Name: "run",
Usage: "Run a command with short-term access keys",
ArgsUsage: "[COMMAND]",
Action: runCommand,
Flags: []cli.Flag{
&cli.StringFlag{
Name: "fav",
Usage: "favorite name",
},
&cli.StringFlag{
Name: "account",
Usage: "account number",
},
&cli.StringFlag{
Name: "car",
Usage: "CAR name",
},
},
},
},
}
// TODO: extend help output to include examples
// run the app
if err := app.Run(os.Args); err != nil {
color.Red(" Error: %v", err)
}
}