forked from kionsoftware/kion-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
1215 lines (1099 loc) · 33.2 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
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
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"errors"
"fmt"
"log"
"os"
"path/filepath"
"strings"
"time"
"github.com/99designs/keyring"
"github.com/hashicorp/go-version"
"github.com/kionsoftware/kion-cli/lib/cache"
"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"
c cache.Cache
kionCliVersion string
)
////////////////////////////////////////////////////////////////////////////////
// //
// 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() error {
if config.Kion.Url == "" {
kionURL, err := helper.PromptInput("Kion URL:")
if err != nil {
return err
}
config.Kion.Url = kionURL
}
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 := config.Kion.Username
pw := config.Kion.Password
idmsID := cCtx.Uint("idms")
// prompt idms if needed
if idmsID == 0 {
idmss, err := kion.GetIDMSs(config.Kion.Url)
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
pwFoundInCache := false
if pw == "" {
// Check password cache
pw, pwFoundInCache, err = c.GetPassword(config.Kion.Url, idmsID, un)
if err != nil {
return err
}
if !pwFoundInCache {
pw, err = helper.PromptPassword("Password:")
if err != nil {
return err
}
}
}
// auth and capture our session
session, err := kion.Authenticate(config.Kion.Url, idmsID, un, pw)
if err != nil {
// Unfortunately, the remote auth endpoint doesn't provide an easy way
// of determining if an auth error was the cause of failure (it returns
// an HTTP 400 with a body that contains a message about authentication
// failues). Conservatively clear out any cached password when
// Authenticate() fails
if pwFoundInCache {
err := c.SetPassword(config.Kion.Url, idmsID, un, "")
if err != nil {
// We're already handling another error, logging
// is the best we can do
color.Red("Failed to clear password from cache, %v", err)
}
}
return err
}
session.IDMSID = idmsID
session.UserName = un
err = c.SetSession(session)
if err != nil {
return err
}
// if auth succeeded, cache the password
err = c.SetPassword(config.Kion.Url, idmsID, un, pw)
if err != nil {
return err
}
// set our token in the config
config.Kion.ApiKey = session.Access.Token
return nil
}
// AuthSAML directs the user to authenticate 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 := config.Kion.SamlMetadataFile
samlServiceProviderIssuer := config.Kion.SamlIssuer
// 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
}
}
var authData *kion.AuthData
// we only need to check for existence - the value is irrelevant
if cCtx.App.Metadata["useOldSAML"] == true {
authData, err = kion.AuthenticateSAMLOld(
config.Kion.Url,
samlMetadata,
samlServiceProviderIssuer)
if err != nil {
return err
}
} else {
authData, err = kion.AuthenticateSAML(
config.Kion.Url,
samlMetadata,
samlServiceProviderIssuer)
if err != nil {
return err
}
}
// cache the session for 9.5 minutes, tokens are valid for 10 minutes
timeFormat := "2006-01-02T15:04:05-0700"
session := kion.Session{
Access: struct {
Expiry string `json:"expiry"`
Token string `json:"token"`
}{
Token: authData.AuthToken,
Expiry: time.Now().Add(570 * time.Second).Format(timeFormat),
},
}
err = c.SetSession(session)
if err != nil {
return err
}
// set our token in the config
config.Kion.ApiKey = authData.AuthToken
return nil
}
// 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. Auth methods
// are prioritized as follows: api/bearer token -> username/password -> saml.
// If flags are set for multiple methods the highest priority method will be
// used.
func setAuthToken(cCtx *cli.Context) error {
if config.Kion.ApiKey == "" {
// if we still have an active session use it
session, found, err := c.GetSession()
if err != nil {
return err
}
if found && session.Access.Expiry != "" {
timeFormat := "2006-01-02T15:04:05-0700"
now := time.Now()
expiration, err := time.Parse(timeFormat, session.Access.Expiry)
if err != nil {
return err
}
if expiration.After(now) {
// TODO: test token is good with an endpoint that is accessible to all
// user permission levels, if you get a 401 then assume token is bad
// due to caching a cred when a users password expired, and flush the
// cache instead...
config.Kion.ApiKey = session.Access.Token
return nil
}
// TODO: uncomment when / if the application supports refresh tokens
// // see if we can use the refresh token
// refreshExp, err := time.Parse(timeFormat, session.Refresh.Expiry)
// if err != nil {
// return err
// }
// if refreshExp.After(now) {
// un := session.UserName
// idmsId := session.IDMSID
// session, err = kion.Authenticate(config.Kion.Url, idmsId, un, session.Refresh.Token)
// if err != nil {
// return err
// }
// session.UserName = un
// session.IDMSID = idmsId
// err = c.SetSession(session)
// if err != nil {
// return err
// }
// config.Kion.ApiKey = session.Access.Token
// return nil
// }
}
// check un / pw were set via flags and infer auth method
if config.Kion.Username != "" || config.Kion.Password != "" {
err := AuthUNPW(cCtx)
return err
}
// check if saml auth flags set and auth with saml if so
if config.Kion.SamlMetadataFile != "" && config.Kion.SamlIssuer != "" {
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
}
config.Kion.ApiKey = apiKey
case "Password":
err := AuthUNPW(cCtx)
if err != nil {
return err
}
case "SAML":
err := AuthSAML(cCtx)
if err != nil {
return err
}
}
}
return nil
}
// getActionAndBuffer determines the action based on the passed flags and sets
// a buffer for the associated action used to determine the cache validity.
func getActionAndBuffer(cCtx *cli.Context) (string, time.Duration) {
// grab the command usage [stak, s, setenv, savecreds, etc]
cmdUsed := cCtx.Lineage()[1].Args().Slice()[0]
var action string
var buffer time.Duration
if cCtx.Bool("credential-process") {
action = "credential-process"
buffer = 5
} else if cCtx.Bool("print") || cmdUsed == "setenv" {
action = "print"
buffer = 300
} else if cCtx.Bool("save") || cmdUsed == "savecreds" {
action = "save"
buffer = 600
} else {
action = "subshell"
buffer = 300
}
return action, buffer
}
// authStakCache handles the common pattern of authenticating the user,
// grabbing a STAK, and caching it.
func authStakCache(cCtx *cli.Context, carName string, accNum string, accAlias string) (kion.STAK, error) {
// handle auth
err := setAuthToken(cCtx)
if err != nil {
return kion.STAK{}, err
}
// generate short term tokens
stak, err := kion.GetSTAK(config.Kion.Url, config.Kion.ApiKey, carName, accNum, accAlias)
if err != nil {
return kion.STAK{}, err
}
// store the stak in the cache
err = c.SetStak(carName, accNum, accAlias, stak)
if err != nil {
return kion.STAK{}, err
}
return stak, err
}
// validateCmdStak validates the flags passed to the stak command.
func validateCmdStak(cCtx *cli.Context) error {
if (cCtx.String("account") != "" || cCtx.String("alias") != "") && cCtx.String("car") == "" {
return errors.New("must specify --car parameter when using --account or --alias")
} else if cCtx.String("car") != "" && cCtx.String("account") == "" && cCtx.String("alias") == "" {
return errors.New("must specify --account OR --alias parameter when using --car")
}
return nil
}
// validateCmdConsole validates the flags passed to the console command.
func validateCmdConsole(cCtx *cli.Context) error {
if cCtx.String("car") != "" {
if cCtx.String("account") == "" && cCtx.String("alias") == "" {
return errors.New("must specify --account or --alias parameter when using --car")
}
} else if cCtx.String("account") != "" || cCtx.String("alias") != "" {
return errors.New("must specify --car parameter when using --account or --alias")
}
return nil
}
// validateCmdRun validates the flags passed to the run command.
func validateCmdRun(cCtx *cli.Context) error {
if cCtx.String("favorite") == "" && ((cCtx.String("account") == "" && cCtx.String("alias") == "") || cCtx.String("car") == "") {
return errors.New("must specify either --fav OR --account and --car OR --alias and --car parameters")
}
return nil
}
////////////////////////////////////////////////////////////////////////////////
// //
// Commands //
// //
////////////////////////////////////////////////////////////////////////////////
// beforeCommands run after the context is ready but before any subcommands are
// executed. Currently used to test feature compatibility with targeted Kion.
func beforeCommands(cCtx *cli.Context) error {
// skip before bits if we don't need them (ie we're just printing help)
args := cCtx.Args().Slice()
if len(args) == 0 || args[0] == "help" || args[0] == "h" {
return nil
}
// switch profiles if specified
profileName := cCtx.String("profile")
if profileName != "" {
// grab all manually set global flags so we can honor them over the chosen
// profiles values
setStrings := make(map[string]string)
var disableCacheFlagged bool
setGlobalFlags := cCtx.FlagNames()
for _, flag := range setGlobalFlags {
switch flag {
case "endpoint":
setStrings["endpoint"] = config.Kion.Url
case "user":
setStrings["user"] = config.Kion.Username
case "password":
setStrings["password"] = config.Kion.Password
case "idms":
setStrings["idms"] = config.Kion.IDMS
case "saml-metadata-file":
setStrings["saml-metadata-file"] = config.Kion.SamlMetadataFile
case "saml-sp-issuer":
setStrings["saml-sp-issuer"] = config.Kion.SamlIssuer
case "token":
setStrings["token"] = config.Kion.ApiKey
case "disable-cache":
disableCacheFlagged = true
}
}
// grab the profile and if found and not empty override the default config
profile, found := config.Profiles[profileName]
if found {
config.Kion = profile.Kion
config.Favorites = profile.Favorites
} else {
return fmt.Errorf("profile not found: %s", profileName)
}
// honor any global flags that were set to maintain precedence
for key, value := range setStrings {
err := cCtx.Set(key, value)
if err != nil {
return err
}
}
if disableCacheFlagged {
config.Kion.DisableCache = true
}
}
// grab the Kion url if not already set
err := setEndpoint()
if err != nil {
return err
}
// gather the targeted Kion version
kionVer, err := kion.GetVersion(config.Kion.Url)
if err != nil {
return err
}
curVer, err := version.NewSemver(kionVer)
if err != nil {
return err
}
// api/v3/me/cloud-access-role fix constraints
v3mecarC1, _ := version.NewConstraint(">=3.6.29, < 3.7.0")
v3mecarC2, _ := version.NewConstraint(">=3.7.17, < 3.8.0")
v3mecarC3, _ := version.NewConstraint(">=3.8.9, < 3.9.0")
v3mecarC4, _ := version.NewConstraint(">=3.9.0")
// check constraints and set bool in metadata
if v3mecarC1.Check(curVer) ||
v3mecarC2.Check(curVer) ||
v3mecarC3.Check(curVer) ||
v3mecarC4.Check(curVer) {
cCtx.App.Metadata["useUpdatedCloudAccessRoleAPI"] = true
}
newSaml, _ := version.NewConstraint(">=3.8.0")
if !newSaml.Check(curVer) {
cCtx.App.Metadata["useOldSAML"] = true
}
// initialize the keyring
name := "kion-cli"
ring, err := keyring.Open(keyring.Config{
ServiceName: name,
KeyCtlScope: "session",
// osx
KeychainName: "login",
KeychainTrustApplication: true,
KeychainSynchronizable: false,
// kde wallet
KWalletAppID: name,
KWalletFolder: name,
// gnome wallet (libsecret)
LibSecretCollectionName: "login",
// windows
WinCredPrefix: name,
// password store
PassPrefix: name,
// encrypted file fallback
FileDir: "~/.kion",
FilePasswordFunc: helper.PromptPassword,
})
if err != nil {
return err
}
// initialize the cache
if config.Kion.DisableCache {
c = cache.NewNullCache(ring)
} else {
c = cache.NewCache(ring)
}
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
// sub-shell is created with them set in the environment.
func genStaks(cCtx *cli.Context) error {
// stub out placeholders
var car kion.CAR
var stak kion.STAK
// set vars for easier access
endpoint := config.Kion.Url
carName := cCtx.String("car")
accNum := cCtx.String("account")
accAlias := cCtx.String("alias")
region := cCtx.String("region")
// get command used and set cache validity buffer
action, buffer := getActionAndBuffer(cCtx)
// if we have what we need go look stuff up without prompts do it
if (accNum != "" || accAlias != "") && carName != "" {
// determine if we have a valid cached entry
cachedSTAK, found, err := c.GetStak(carName, accNum, accAlias)
if err != nil {
return err
}
getCar := true
if found && cachedSTAK.Expiration.After(time.Now().Add(-buffer*time.Second)) {
// cached stak found and is still valid
stak = cachedSTAK
if action != "subshell" && action != "save" {
// skip getting the car for everything but subshell and save
getCar = false
}
}
// grab the car if needed
if getCar {
// handle auth
err := setAuthToken(cCtx)
if err != nil {
return err
}
if accNum != "" {
car, err = kion.GetCARByNameAndAccount(endpoint, config.Kion.ApiKey, carName, accNum)
if err != nil {
return err
}
} else {
car, err = kion.GetCARByNameAndAlias(endpoint, config.Kion.ApiKey, carName, accAlias)
if err != nil {
return err
}
}
}
} else {
// handle auth
err := setAuthToken(cCtx)
if err != nil {
return err
}
// run through the car selector to fill any gaps
err = helper.CARSelector(cCtx, &car)
if err != nil {
return err
}
// rebuild cache key and determine if we have a valid cached entry
cachedSTAK, found, err := c.GetStak(car.Name, car.AccountNumber, "")
if err != nil {
return err
}
if found && cachedSTAK.Expiration.After(time.Now().Add(-buffer*time.Second)) {
// cached stak found and is still valid
stak = cachedSTAK
}
}
// grab a new stak if needed
if stak == (kion.STAK{}) {
var err error
stak, err = authStakCache(cCtx, car.Name, car.AccountNumber, car.AccountAlias)
if err != nil {
return err
}
}
// run the action
switch action {
case "credential-process":
// NOTE: do not use os.Stderr here else credentials can be written to logs
return helper.PrintCredentialProcess(os.Stdout, stak)
case "print":
return helper.PrintSTAK(os.Stdout, stak, region)
case "save":
return helper.SaveAWSCreds(stak, car)
case "subshell":
var displayAlais string
if accAlias != "" {
displayAlais = accAlias
} else {
displayAlais = car.AccountName
}
return helper.CreateSubShell(car.AccountNumber, displayAlais, car.Name, stak, region)
default:
return nil
}
}
// 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
}
}
// grab the favorite object
favorite := fMap[fav]
// determine favorite action, default to cli unless explicitly set to web
if favorite.AccessType == "web" {
// handle auth
err = setAuthToken(cCtx)
if err != nil {
return err
}
// attempt to find an exact match then fallback to the first match
car, err := kion.GetCARByNameAndAccount(config.Kion.Url, config.Kion.ApiKey, favorite.CAR, favorite.Account)
if err != nil {
car, err = kion.GetCARByName(config.Kion.Url, config.Kion.ApiKey, favorite.CAR)
if err != nil {
return err
}
car.AccountNumber = favorite.Account
}
url, err := kion.GetFederationURL(config.Kion.Url, config.Kion.ApiKey, car)
if err != nil {
return err
}
fmt.Printf("Federating into %s (%s) via %s\n", favorite.Name, favorite.Account, car.AwsIamRoleName)
return helper.OpenBrowserRedirect(url, car.AccountTypeID, favorite.Name, config.Browser)
} else {
// placeholder for our stak
var stak kion.STAK
// determine action and set required cache validity buffer
action, buffer := getActionAndBuffer(cCtx)
// check if we have a valid cached stak else grab a new one
cachedSTAK, found, err := c.GetStak(favorite.CAR, favorite.Account, "")
if err != nil {
return err
}
if found && cachedSTAK.Expiration.After(time.Now().Add(-buffer*time.Second)) {
stak = cachedSTAK
} else {
stak, err = authStakCache(cCtx, favorite.CAR, favorite.Account, "")
if err != nil {
return err
}
}
// credential process output, print, or create sub-shell
switch action {
case "credential-process":
// NOTE: do not use os.Stderr here else credentials can be written to logs
return helper.PrintCredentialProcess(os.Stdout, stak)
case "print":
return helper.PrintSTAK(os.Stdout, stak, favorite.Region)
case "subshell":
return helper.CreateSubShell(favorite.Account, favorite.Name, favorite.CAR, stak, favorite.Region)
default:
return nil
}
}
}
// fedConsole opens the CSP console for the selected account and cloud access
// role in the user's default browser.
func fedConsole(cCtx *cli.Context) error {
// handle auth
err := setAuthToken(cCtx)
if err != nil {
return err
}
// retrieve the account number, account alias, and CAR name from the context
accNum := cCtx.String("account")
accountAlias := cCtx.String("alias")
carName := cCtx.String("car")
var car kion.CAR
if carName != "" && (accNum != "" || accountAlias != "") {
// fetch the car directly using account number or alias and car name
if accNum != "" {
car, err = kion.GetCARByNameAndAccount(config.Kion.Url, config.Kion.ApiKey, carName, accNum)
if err != nil {
return fmt.Errorf("failed to get CAR for account %s and CAR %s: %v", accNum, carName, err)
}
} else {
car, err = kion.GetCARByNameAndAlias(config.Kion.Url, config.Kion.ApiKey, carName, accountAlias)
if err != nil {
return fmt.Errorf("failed to get CAR for alias %s and CAR %s: %v", accountAlias, carName, err)
}
}
} else {
// walk user through the prompt workflow to select a car
err = helper.CARSelector(cCtx, &car)
if err != nil {
return err
}
}
// grab the csp federation url
url, err := kion.GetFederationURL(config.Kion.Url, config.Kion.ApiKey, car)
if err != nil {
return err
}
return helper.OpenBrowserRedirect(url, car.AccountTypeID, car.AccountName, config.Browser)
}
// 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)"
}
region := f.Region
if region == "" {
region = "[unset]"
}
fmt.Printf(" %v:\n account number: %v\n cloud access role: %v\n access type: %v\n region: %v\n", f.Name, f.Account, f.CAR, accessType, region)
}
} 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 {
// set vars for easier access
favName := cCtx.String("favorite")
accNum := cCtx.String("account")
accAlias := cCtx.String("alias")
carName := cCtx.String("car")
region := cCtx.String("region")
// placeholder for our stak
var stak kion.STAK
// prefer favorites if specified, else use account/alias and car
if favName != "" {
// map our favorites for ease of use
_, fMap := helper.MapFavs(config.Favorites)
// if arg passed is a valid favorite use it else error out
var fav string
var err error
if fMap[favName] != (structs.Favorite{}) {
fav = favName
} else {
return errors.New("can't find favorite")
}
// grab our favorite
favorite := fMap[fav]
// check if we have a valid cached stak else grab a new one
cachedSTAK, found, err := c.GetStak(favorite.CAR, favorite.Account, "")
if err != nil {
return err
}
if found && cachedSTAK.Expiration.After(time.Now().Add(-5*time.Second)) {
stak = cachedSTAK
} else {
stak, err = authStakCache(cCtx, favorite.CAR, favorite.Account, "")
if err != nil {
return err
}
}
// take the region flag over the favorite region
targetRegion := region
if targetRegion == "" {
targetRegion = favorite.Region
}
// run the command
err = helper.RunCommand(stak, targetRegion, cCtx.Args().First(), cCtx.Args().Tail()...)
if err != nil {
return err
}
} else {
// check if we have a valid cached stak else grab a new one
cachedSTAK, found, err := c.GetStak(carName, accNum, accAlias)
if err != nil {
return err
}
if found && cachedSTAK.Expiration.After(time.Now().Add(-5*time.Second)) {
stak = cachedSTAK
} else {
stak, err = authStakCache(cCtx, carName, accNum, accAlias)
if err != nil {
return err
}
}
err = helper.RunCommand(stak, region, cCtx.Args().First(), cCtx.Args().Tail()...)
if err != nil {
return err
}
}
return nil
}
// flushCache clears the Kion CLI cache.
func flushCache(cCtx *cli.Context) error {
return c.FlushCache()
}
// 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)
}
// allow config file to be overridden by an env var, else use default
userConfigFile := os.Getenv("KION_CONFIG")
if userConfigFile != "" {
configPath = filepath.Clean(userConfigFile)
} else {
configPath = filepath.Join(home, configFile)
}
// load configuration file
err = helper.LoadConfig(configPath, &config)
if err != nil && !errors.Is(err, os.ErrNotExist) {
color.Red(" Error: %v", err)
os.Exit(1)
}
// 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: kionCliVersion,
Usage: "Kion federation on the command line!",
EnableBashCompletion: true,
Before: beforeCommands,
After: afterCommands,
Metadata: map[string]interface{}{
"useUpdatedCloudAccessRoleAPI": false,
"useOldSAML": false,
},
////////////////////
// Global Flags //
////////////////////
Flags: []cli.Flag{
&cli.StringFlag{
Name: "endpoint",
Aliases: []string{"url", "e"},
Value: config.Kion.Url,
EnvVars: []string{"KION_URL"},
Usage: "Kion `URL`",
Destination: &config.Kion.Url,
},
&cli.StringFlag{
Name: "user",
Aliases: []string{"username", "u"},
Value: config.Kion.Username,
EnvVars: []string{"KION_USERNAME", "CTKEY_USERNAME"},
Usage: "`USERNAME` for authentication",
Destination: &config.Kion.Username,
},
&cli.StringFlag{
Name: "password",
Aliases: []string{"p"},
Value: config.Kion.Password,
EnvVars: []string{"KION_PASSWORD", "CTKEY_PASSWORD"},
Usage: "`PASSWORD` for authentication",
Destination: &config.Kion.Password,
DefaultText: passwordDefaultText,
},