-
Notifications
You must be signed in to change notification settings - Fork 34
/
webssoauth.go
1229 lines (1084 loc) · 34.3 KB
/
webssoauth.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
/*
* Copyright (c) 2022-Present, Okta, Inc.
*
* 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 webssoauth
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
osexec "os/exec"
"path/filepath"
"regexp"
"strings"
"sync"
"time"
"github.com/AlecAivazis/survey/v2"
"github.com/AlecAivazis/survey/v2/core"
"github.com/AlecAivazis/survey/v2/terminal"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/iam"
"github.com/aws/aws-sdk-go/service/sts"
"github.com/cenkalti/backoff/v4"
"github.com/google/shlex"
"github.com/mdp/qrterminal"
brwsr "github.com/pkg/browser"
"golang.org/x/net/html"
oaws "github.com/okta/okta-aws-cli/internal/aws"
boff "github.com/okta/okta-aws-cli/internal/backoff"
"github.com/okta/okta-aws-cli/internal/config"
"github.com/okta/okta-aws-cli/internal/exec"
"github.com/okta/okta-aws-cli/internal/okta"
"github.com/okta/okta-aws-cli/internal/output"
"github.com/okta/okta-aws-cli/internal/paginator"
"github.com/okta/okta-aws-cli/internal/utils"
)
const (
amazonAWS = "amazon_aws"
accept = "Accept"
nameKey = "name"
saml2Attribute = "saml2:attribute"
samlAttributesRole = "https://aws.amazon.com/SAML/Attributes/Role"
askIDPError = "error asking for IdP selection: %w"
noRoleError = "provider %q has no roles to choose from"
noIDPsError = "no IdPs to choose from"
idpValueNotSelectedError = "failed to select IdP value"
askRoleError = "error asking for role selection: %w"
noRolesError = "no roles chosen for provider %q"
chooseIDP = "Choose an IdP:"
chooseRole = "Choose a Role:"
idpSelectedTemplate = ` {{color "default+hb"}}IdP: {{color "reset"}}{{color "cyan"}}{{ .IDP }}{{color "reset"}}`
roleSelectedTemplate = ` {{color "default+hb"}}Role: {{color "reset"}}{{color "cyan"}}{{ .Role }}{{color "reset"}}`
dotOktaDir = ".okta"
tokenFileName = "awscli-access-token.json"
arnLabelPrintFmt = " %q: %q\n"
arnPrintFmt = " %q\n"
)
type idpTemplateData struct {
IDP string
}
type roleTemplateData struct {
Role string
}
// WebSSOAuthentication Encapsulates the work of getting temporary IAM
// credentials through Okta's Web SSO authentication with an Okta AWS Federation
// Application.
//
// The overall API interactions are as follows:
// - CLI starts device authorization at /oauth2/v1/device/authorize
// - CLI polls for access token from device auth at /oauth2/v1/token
// - Access token granted by Okta once user is authorized
//
// - CLI presents access token to Okta AWS Fed app for a SAML assertion at /login/token/sso
// - CLI presents SAML assertion to AWS STS for temporary AWS IAM creds
type WebSSOAuthentication struct {
config *config.Config
fedAppAlreadySelected bool
}
// idpAndRole IdP and role pairs
type idpAndRole struct {
idp string
role string
region string
}
var stderrIsOutAskOpt = func(options *survey.AskOptions) error {
options.Stdio = terminal.Stdio{
In: os.Stdin,
Out: os.Stderr,
Err: os.Stderr,
}
return nil
}
// NewWebSSOAuthentication New Web SSO Authentication constructor
func NewWebSSOAuthentication(cfg *config.Config) (token *WebSSOAuthentication, err error) {
token = &WebSSOAuthentication{
config: cfg,
}
if token.isClassicOrg() {
return nil, NewClassicOrgError(cfg.OrgDomain())
}
if cfg.IsProcessCredentialsFormat() {
if cfg.AWSIAMIdP() == "" || cfg.AWSIAMRole() == "" || !cfg.OpenBrowser() {
return nil, fmt.Errorf("arguments --%s , --%s , and --%s must be set for %q format", config.AWSIAMIdPFlag, config.AWSIAMRoleFlag, config.OpenBrowserFlag, cfg.Format())
}
}
// Check if exec arg is present and that there are args for it before doing any work
if cfg.Exec() {
if _, err := exec.NewExec(); err != nil {
return nil, err
}
}
return token, nil
}
// EstablishIAMCredentials Steps to establish an AWS session token.
func (w *WebSSOAuthentication) EstablishIAMCredentials() error {
clientID := w.config.OIDCAppID()
var at *okta.AccessToken
var apps []*okta.Application
var err error
at = w.cachedAccessToken()
if at == nil {
deviceAuth, err := w.authorize()
if err != nil {
return err
}
w.promptAuthentication(deviceAuth)
at, err = w.accessToken(deviceAuth)
if err != nil {
return err
}
at.Expiry = time.Now().Add(time.Duration(at.ExpiresIn) * time.Second).Format(time.RFC3339)
w.cacheAccessToken(at)
}
if w.config.FedAppID() != "" {
return w.establishTokenWithFedAppID(clientID, w.config.FedAppID(), at, w.config.AWSRegion())
}
apps, err = w.listFedApps(clientID, at)
if err != nil {
return err
}
if len(apps) == 0 {
errMsg := `
There aren't any AWS Federation Applications associated with OIDC App %q.
Check if it has %q scopes and is the allowed web SSO client for an AWS
Federation app. Or, invoke okta-aws-cli including the client ID of the
AWS Federation App with --aws-acct-fed-app-id FED_APP_ID
`
return fmt.Errorf(errMsg, clientID, "okta.apps.read or okta.users.read.self")
}
var fedAppID string
if len(apps) == 1 {
// only one app, we don't need to prompt selection of idp / fed app
fedAppID = apps[0].ID
} else if w.config.AllProfiles() {
// special case, we're going to run the table and get all profiles for all apps
errArr := []error{}
for _, app := range apps {
if err = w.establishTokenWithFedAppID(clientID, app.ID, at, w.config.AWSRegion()); err != nil {
errArr = append(errArr, err)
}
}
return errors.Join(errArr...)
} else {
// Here, we do want to prompt for selection of the Fed App.
// If the app is making use of "Role value pattern" on AWS settings we
// won't get the real ARN until we establish the web sso token.
w.fedAppAlreadySelected = true
fedAppID, err = w.selectFedApp(apps)
if err != nil {
return err
}
}
return w.establishTokenWithFedAppID(clientID, fedAppID, at, w.config.AWSRegion())
}
// choiceFriendlyLabelIDP returns a friendly choice for pretty printing IDP
// labels. alternative value is the default value to return if a friendly
// determination can not be made.
func (w *WebSSOAuthentication) choiceFriendlyLabelIDP(alt, arn string, idps map[string]string) string {
if idps == nil {
return alt
}
if label, ok := idps[arn]; ok {
if w.config.Debug() {
w.consolePrint(" found IdP ARN %q having friendly label %q\n", arn, label)
}
return label
}
// treat ARN values as regexps
for arnRegexp, label := range idps {
if ok, _ := regexp.MatchString(arnRegexp, arn); ok {
return label
}
}
if w.config.Debug() {
w.consolePrint(" did not find friendly label for IdP ARN\n")
w.consolePrint(arnPrintFmt, arn)
w.consolePrint(" in okta.yaml awscli.idps map:\n")
for arn, label := range idps {
w.consolePrint(arnLabelPrintFmt, arn, label)
}
}
return alt
}
func (w *WebSSOAuthentication) selectFedApp(apps []*okta.Application) (string, error) {
idps := make(map[string]*okta.Application)
choices := make([]string, len(apps))
var selected string
var configIDPs map[string]string
oktaConfig, err := config.OktaConfig()
if err == nil {
configIDPs = oktaConfig.AWSCLI.IDPS
}
for i, app := range apps {
choiceLabel := w.choiceFriendlyLabelIDP(app.Label, app.Settings.App.IdentityProviderARN, configIDPs)
// reverse case when
// when choiceLabel == w.configAWSIAMIfP()
// --aws-iam-idp "S3 IdP"
idpARN := w.config.AWSIAMIdP()
if choiceLabel == w.config.AWSIAMIdP() {
idpARN = app.Settings.App.IdentityProviderARN
}
if app.Settings.App.IdentityProviderARN != "" && idpARN == app.Settings.App.IdentityProviderARN {
if !w.config.IsProcessCredentialsFormat() {
idpData := idpTemplateData{
IDP: choiceLabel,
}
rich, _, err := core.RunTemplate(idpSelectedTemplate, idpData)
if err != nil {
return "", err
}
fmt.Fprintln(os.Stderr, rich)
}
return app.ID, nil
}
choices[i] = choiceLabel
idps[choiceLabel] = app
}
prompt := &survey.Select{
Message: chooseIDP,
Options: choices,
}
err = survey.AskOne(prompt, &selected, survey.WithValidator(survey.Required), stderrIsOutAskOpt)
if err != nil {
return "", fmt.Errorf(askIDPError, err)
}
if selected == "" {
return "", errors.New(idpValueNotSelectedError)
}
return idps[selected].ID, nil
}
func (w *WebSSOAuthentication) establishTokenWithFedAppID(clientID, fedAppID string, at *okta.AccessToken, region string) error {
at, err := w.fetchSSOWebToken(clientID, fedAppID, at)
if err != nil {
return err
}
assertion, err := w.fetchSAMLAssertion(at)
if err != nil {
return err
}
idpRolesMap, err := w.extractIDPAndRolesMapFromAssertion(assertion)
if err != nil {
return err
}
if !w.config.AllProfiles() {
iar, err := w.promptForIdpAndRole(idpRolesMap)
if err != nil {
return err
}
iar.region = region
cc, err := w.awsAssumeRoleWithSAML(iar, assertion, region)
if err != nil {
return err
}
err = output.RenderAWSCredential(w.config, cc)
if err != nil {
return err
}
if w.config.Exec() {
exe, _ := exec.NewExec()
if err := exe.Run(cc); err != nil {
return err
}
}
} else {
ccch := w.fetchAllAWSCredentialsWithSAMLRole(idpRolesMap, assertion, region)
for cc := range ccch {
err = output.RenderAWSCredential(w.config, cc)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to render credential %s: %s\n", cc.Profile, err)
continue
}
}
}
return nil
}
// awsAssumeRoleWithSAML Get AWS Credentials with an STS Assume Role With SAML AWS
// API call.
func (w *WebSSOAuthentication) awsAssumeRoleWithSAML(iar *idpAndRole, assertion, region string) (cc *oaws.CredentialContainer, err error) {
awsCfg := aws.NewConfig().WithHTTPClient(w.config.HTTPClient())
if region != "" {
awsCfg = awsCfg.WithRegion(region)
}
sess, err := session.NewSession(awsCfg)
if err != nil {
err = fmt.Errorf("AWS API session error: %w", err)
return
}
svc := sts.New(sess)
input := &sts.AssumeRoleWithSAMLInput{
DurationSeconds: aws.Int64(w.config.AWSSessionDuration()),
PrincipalArn: aws.String(iar.idp),
RoleArn: aws.String(iar.role),
SAMLAssertion: aws.String(assertion),
}
svcResp, err := svc.AssumeRoleWithSAML(input)
if err != nil {
err = fmt.Errorf("STS Assume Role With SAML API error; given idp: %q, role: %q, error: %w", iar.idp, iar.role, err)
return
}
cc = &oaws.CredentialContainer{
AccessKeyID: *svcResp.Credentials.AccessKeyId,
SecretAccessKey: *svcResp.Credentials.SecretAccessKey,
SessionToken: *svcResp.Credentials.SessionToken,
Expiration: svcResp.Credentials.Expiration,
}
if !w.config.AllProfiles() && w.config.Profile() != "" {
cc.Profile = w.config.Profile()
return cc, nil
}
var profileName, idpName, roleName string
if _, after, found := strings.Cut(iar.idp, "/"); found {
idpName = after
}
if _, after, found := strings.Cut(iar.role, "/"); found {
roleName = after
}
sessCopy := sess.Copy(&aws.Config{
Credentials: credentials.NewStaticCredentials(
cc.AccessKeyID,
cc.SecretAccessKey,
cc.SessionToken,
),
})
if p, err := w.fetchAWSAccountAlias(sessCopy); err != nil {
org := "org"
fmt.Fprintf(os.Stderr, "unable to determine account alias, setting alias name to %q\n", org)
profileName = org
} else {
profileName = p
}
cc.Profile = fmt.Sprintf("%s-%s-%s", profileName, idpName, roleName)
return cc, nil
}
// choiceFriendlyLabelRole returns a friendly choice for pretty printing Role
// labels. The ARN default value to return if a friendly determination can not
// be made.
func (w *WebSSOAuthentication) choiceFriendlyLabelRole(arn string, roles map[string]string) string {
if roles == nil {
return arn
}
if label, ok := roles[arn]; ok {
if w.config.Debug() {
w.consolePrint(" found Role ARN %q having friendly label %q\n", arn, label)
}
return label
}
// reverse case when friendly role name is given
// --aws-iam-role "OK S3 Read"
for _, roleLabel := range roles {
if arn == roleLabel {
return roleLabel
}
}
// treat ARN values as regexps
for arnRegexp, label := range roles {
if ok, _ := regexp.MatchString(arnRegexp, arn); ok {
return label
}
}
if w.config.Debug() {
w.consolePrint(" did not find friendly label for Role ARN\n")
w.consolePrint(arnPrintFmt, arn)
w.consolePrint(" in okta.yaml awscli.roles map:\n")
for arn, label := range roles {
w.consolePrint(arnLabelPrintFmt, arn, label)
}
}
return arn
}
// promptForRole prompt operator for the AWS Role ARN given a slice of Role ARNs
func (w *WebSSOAuthentication) promptForRole(idp string, roleARNs []string) (roleARN string, err error) {
oktaConfig, err := config.OktaConfig()
var configRoles map[string]string
if err == nil {
configRoles = oktaConfig.AWSCLI.ROLES
}
if len(roleARNs) == 1 || w.config.AWSIAMRole() != "" {
roleARN = w.config.AWSIAMRole()
if len(roleARNs) == 1 {
roleARN = roleARNs[0]
}
roleLabel := w.choiceFriendlyLabelRole(roleARN, configRoles)
roleData := roleTemplateData{
Role: roleLabel,
}
// reverse case when friendly role name alias is given as the input value
// --aws-iam-role "OK S3 Read"
if roleLabel == roleARN {
for rARN, rLbl := range configRoles {
if roleARN == rLbl {
roleARN = rARN
break
}
}
}
if !w.config.IsProcessCredentialsFormat() {
rich, _, err := core.RunTemplate(roleSelectedTemplate, roleData)
if err != nil {
return "", err
}
fmt.Fprintln(os.Stderr, rich)
}
return roleARN, nil
}
promptRoles := []string{}
labelsARNs := map[string]string{}
for _, arn := range roleARNs {
roleLabel := w.choiceFriendlyLabelRole(arn, configRoles)
promptRoles = append(promptRoles, roleLabel)
labelsARNs[roleLabel] = arn
}
prompt := &survey.Select{
Message: chooseRole,
Options: promptRoles,
}
var selected string
err = survey.AskOne(prompt, &selected, survey.WithValidator(survey.Required), stderrIsOutAskOpt)
if err != nil {
return "", fmt.Errorf(askRoleError, err)
}
roleARN = labelsARNs[selected]
if roleARN == "" {
return "", fmt.Errorf(noRolesError, idp)
}
return roleARN, nil
}
// promptForIDP prompt operator for the AWS IdP ARN given a slice of IdP ARNs.
// If the fedApp has already been selected via an ask one survey we don't need
// to pretty print out the IdP name again.
func (w *WebSSOAuthentication) promptForIDP(idpARNs []string) (idpARN string, err error) {
var configIDPs map[string]string
if oktaConfig, cErr := config.OktaConfig(); cErr == nil {
configIDPs = oktaConfig.AWSCLI.IDPS
}
if len(idpARNs) == 0 {
return idpARN, errors.New(noIDPsError)
}
if len(idpARNs) == 1 || w.config.AWSIAMIdP() != "" {
idpARN = w.config.AWSIAMIdP()
if len(idpARNs) == 1 {
idpARN = idpARNs[0]
}
if w.fedAppAlreadySelected {
return idpARN, nil
}
idpLabel := w.choiceFriendlyLabelIDP(idpARN, idpARN, configIDPs)
idpData := idpTemplateData{
IDP: idpLabel,
}
rich, _, err := core.RunTemplate(idpSelectedTemplate, idpData)
if err != nil {
return "", err
}
fmt.Fprintln(os.Stderr, rich)
return idpARN, nil
}
idpChoices := make(map[string]string, len(idpARNs))
idpChoiceLabels := make([]string, len(idpARNs))
for i, arn := range idpARNs {
idpLabel := w.choiceFriendlyLabelIDP(arn, arn, configIDPs)
idpChoices[idpLabel] = arn
idpChoiceLabels[i] = idpLabel
}
var idpChoice string
prompt := &survey.Select{
Message: chooseIDP,
Options: idpChoiceLabels,
}
err = survey.AskOne(prompt, &idpChoice, survey.WithValidator(survey.Required), stderrIsOutAskOpt)
if err != nil {
return idpARN, fmt.Errorf(askIDPError, err)
}
idpARN = idpChoices[idpChoice]
if idpARN == "" {
return idpARN, errors.New(idpValueNotSelectedError)
}
return idpARN, nil
}
// promptForIdpAndRole UX to prompt operator for the AWS role whose credentials
// will be utilized.
func (w *WebSSOAuthentication) promptForIdpAndRole(idpRoles map[string][]string) (iar *idpAndRole, err error) {
idps := make([]string, 0, len(idpRoles))
for idp := range idpRoles {
idps = append(idps, idp)
}
idp, err := w.promptForIDP(idps)
if err != nil {
return nil, err
}
roles := idpRoles[idp]
role, err := w.promptForRole(idp, roles)
if err != nil {
return nil, err
}
iar = &idpAndRole{
idp: idp,
role: role,
}
return iar, nil
}
// extractIDPAndRolesMapFromAssertion Get AWS IdP and Roles from SAML assertion. Result
// a map string string slice keyed by the IdP ARN value and slice of ARN role
// values.
func (w *WebSSOAuthentication) extractIDPAndRolesMapFromAssertion(encoded string) (irmap map[string][]string, err error) {
assertion, err := base64.StdEncoding.DecodeString(encoded)
if err != nil {
return nil, err
}
doc, err := html.Parse(strings.NewReader(string(assertion)))
if err != nil {
return nil, err
}
irmap = make(map[string][]string)
if role, ok := findSAMLRoleAttibute(doc); ok {
pairs := findSAMLIdPRoleValues(role)
for _, pair := range pairs {
idpRole := strings.Split(pair, ",")
idp := idpRole[0]
if _, found := irmap[idp]; !found {
irmap[idp] = []string{}
}
if len(idpRole) == 1 {
continue
}
roles := irmap[idp]
role := idpRole[1]
roles = append(roles, role)
irmap[idp] = roles
}
}
return irmap, nil
}
// fetchSAMLAssertion Gets the SAML assertion from Okta API /login/token/sso
func (w *WebSSOAuthentication) fetchSAMLAssertion(at *okta.AccessToken) (assertion string, err error) {
params := url.Values{"token": {at.AccessToken}}
apiURL := fmt.Sprintf("https://%s/login/token/sso?%s", w.config.OrgDomain(), params.Encode())
req, err := http.NewRequest(http.MethodGet, apiURL, nil)
if err != nil {
return assertion, err
}
req.Header.Add(accept, "text/html")
req.Header.Add(utils.UserAgentHeader, config.UserAgentValue)
req.Header.Add(utils.XOktaAWSCLIOperationHeader, utils.XOktaAWSCLIWebOperation)
resp, err := w.config.HTTPClient().Do(req)
if err != nil {
return assertion, err
}
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("fetching SAML assertion received API response %q", resp.Status)
}
doc, err := html.Parse(resp.Body)
if err != nil {
return assertion, err
}
if assertion, ok := findSAMLResponse(doc); ok {
return assertion, nil
}
return assertion, fmt.Errorf("could not find SAML assertion in API call %q", apiURL)
}
// fetchSSOWebToken see:
// https://developer.okta.com/docs/reference/api/oidc/#token
func (w *WebSSOAuthentication) fetchSSOWebToken(clientID, awsFedAppID string, at *okta.AccessToken) (token *okta.AccessToken, err error) {
apiURL := fmt.Sprintf(okta.OAuthV1TokenEndpointFormat, w.config.OrgDomain())
data := url.Values{
"client_id": {clientID},
"actor_token": {at.AccessToken},
"actor_token_type": {"urn:ietf:params:oauth:token-type:access_token"},
"subject_token": {at.IDToken},
"subject_token_type": {"urn:ietf:params:oauth:token-type:id_token"},
"grant_type": {"urn:ietf:params:oauth:grant-type:token-exchange"},
"requested_token_type": {"urn:okta:oauth:token-type:web_sso_token"},
"audience": {fmt.Sprintf("urn:okta:apps:%s", awsFedAppID)},
}
body := strings.NewReader(data.Encode())
req, err := http.NewRequest(http.MethodPost, apiURL, body)
if err != nil {
return nil, err
}
req.Header.Add(accept, utils.ApplicationJSON)
req.Header.Add(utils.ContentType, utils.ApplicationXFORM)
req.Header.Add(utils.UserAgentHeader, config.UserAgentValue)
req.Header.Add(utils.XOktaAWSCLIOperationHeader, utils.XOktaAWSCLIWebOperation)
resp, err := w.config.HTTPClient().Do(req)
if err != nil {
return nil, err
}
err = okta.NewAPIError(resp)
if err != nil {
return nil, err
}
token = &okta.AccessToken{}
err = json.NewDecoder(resp.Body).Decode(token)
if err != nil {
return nil, err
}
return
}
// promptAuthentication UX to display activation URL and code.
func (w *WebSSOAuthentication) promptAuthentication(da *okta.DeviceAuthorization) {
var qrBuf []byte
qrCode := ""
if w.config.QRCode() {
qrBuf = make([]byte, 4096)
buf := bytes.NewBufferString("")
qrterminal.GenerateHalfBlock(da.VerificationURIComplete, qrterminal.L, buf)
if _, err := buf.Read(qrBuf); err == nil {
qrCode = fmt.Sprintf(utils.PassThroughStringNewLineFMT, qrBuf)
}
}
prompt := `%s the following URL to begin Okta device authorization for the AWS CLI
%s%s
`
openMsg := "Open"
if w.config.OpenBrowser() {
openMsg = "Web browser will open"
}
w.consolePrint(prompt, openMsg, qrCode, da.VerificationURIComplete)
if w.config.OpenBrowserCommand() != "" {
bCmd := w.config.OpenBrowserCommand()
if bCmd != "" {
bArgs, err := splitArgs(bCmd)
if err != nil {
w.consolePrint("Browser command %q is invalid: %v\n", bCmd, err)
return
}
bArgs = append(bArgs, da.VerificationURIComplete)
cmd := osexec.Command(bArgs[0], bArgs[1:]...)
out, err := cmd.Output()
if err != nil {
w.consolePrint("Failed to open activation URL with given browser: %v\n", err)
w.consolePrint(" %s\n", strings.Join(bArgs, " "))
}
if len(out) > 0 {
w.consolePrint("browser output:\n%s\n", string(out))
}
}
} else if w.config.OpenBrowser() {
brwsr.Stdout = os.Stderr
if err := brwsr.OpenURL(da.VerificationURIComplete); err != nil {
w.consolePrint("Failed to open activation URL with system browser: %v\n", err)
}
}
}
// listFedApps Lists Okta AWS Fed Apps that are active. Errors after that occur
// after getting anything other than a 403 on /api/v1/apps will be retried on
// the fall back to /api/v1/users/me/appLinks . Requires assoicated OIDC app has
// been granted okta.apps.read to its scope.
func (w *WebSSOAuthentication) listFedApps(clientID string, at *okta.AccessToken) ([]*okta.Application, error) {
apiURL, err := url.Parse(fmt.Sprintf("https://%s/api/v1/apps", w.config.OrgDomain()))
if err != nil {
return nil, err
}
headers := map[string]string{
accept: utils.ApplicationJSON,
utils.ContentType: utils.ApplicationJSON,
utils.UserAgentHeader: config.UserAgentValue,
utils.XOktaAWSCLIOperationHeader: utils.XOktaAWSCLIWebOperation,
"Authorization": fmt.Sprintf("%s %s", at.TokenType, at.AccessToken),
}
params := map[string]string{
"limit": "200",
"q": amazonAWS,
"filter": `status eq "ACTIVE"`,
}
pgntr := paginator.NewPaginator(w.config.HTTPClient(), apiURL, &headers, ¶ms)
allApps := make([]*okta.Application, 0)
resp, err := pgntr.GetItems(&allApps)
if resp.StatusCode == http.StatusForbidden {
// fall back to using app links, that endpoint doesn't have pagination
// so there isn't anything to DRY up between the two kinds of API calls
return w.listFedAppsFromAppLinks(&headers)
}
if err != nil {
return nil, err
}
for resp.HasNextPage() {
var nextApps []*okta.Application
resp, err = resp.Next(&nextApps)
if err != nil {
return nil, err
}
allApps = append(allApps, nextApps...)
}
apps := make([]*okta.Application, 0)
for _, app := range allApps {
// even though the query was for AWS fed apps check just in case
if app.Name != amazonAWS {
continue
}
// even though the query filted on active status check just in case
if app.Status != "ACTIVE" {
continue
}
// only apps that that have client the web sso client
if app.Settings.App.WebSSOClientID != clientID {
continue
}
apps = append(apps, app)
}
return apps, nil
}
// listFedAppsFromAppLinks Lists Okta AWS Fed Apps assign to the current user
// via appLinks Requires assoicated OIDC app has been granted
// okta.users.read.self to its scope.
func (w *WebSSOAuthentication) listFedAppsFromAppLinks(headers *map[string]string) ([]*okta.Application, error) {
// appLinks doesn't have pagination/limit, filter, or query parameters
apiURL, err := url.Parse(fmt.Sprintf("https://%s/api/v1/users/me/appLinks", w.config.OrgDomain()))
if err != nil {
return nil, err
}
pgntr := paginator.NewPaginator(w.config.HTTPClient(), apiURL, headers, nil)
allApps := make([]*okta.ApplicationLink, 0)
_, err = pgntr.GetItems(&allApps)
if err != nil {
return nil, err
}
apps := make([]*okta.Application, 0)
for _, appLink := range allApps {
if appLink.Name != amazonAWS {
continue
}
app := okta.Application{
ID: appLink.ID,
Name: appLink.Name,
Label: appLink.Label,
}
apps = append(apps, &app)
}
return apps, nil
}
// accessToken see:
// https://developer.okta.com/docs/reference/api/oidc/#token
func (w *WebSSOAuthentication) accessToken(deviceAuth *okta.DeviceAuthorization) (at *okta.AccessToken, err error) {
clientID := w.config.OIDCAppID()
apiURL := fmt.Sprintf(okta.OAuthV1TokenEndpointFormat, w.config.OrgDomain())
req, err := http.NewRequest(http.MethodPost, apiURL, nil)
if err != nil {
return nil, err
}
req.Header.Add(accept, utils.ApplicationJSON)
req.Header.Add(utils.ContentType, utils.ApplicationXFORM)
req.Header.Add(utils.UserAgentHeader, config.UserAgentValue)
req.Header.Add(utils.XOktaAWSCLIOperationHeader, utils.XOktaAWSCLIWebOperation)
var bodyBytes []byte
// Keep polling if Status Code is 400 and apiError.Error ==
// "authorization_pending". Done if status code is 200. Else error.
poll := func() error {
data := url.Values{
"client_id": {clientID},
"device_code": {deviceAuth.DeviceCode},
"grant_type": {"urn:ietf:params:oauth:grant-type:device_code"},
}
body := strings.NewReader(data.Encode())
req.Body = io.NopCloser(body)
resp, err := w.config.HTTPClient().Do(req)
bodyBytes, _ = io.ReadAll(resp.Body)
if err != nil {
return backoff.Permanent(fmt.Errorf("fetching access token polling received API err %w", err))
}
if resp.StatusCode == http.StatusOK {
// done
return nil
}
if resp.StatusCode == http.StatusBadRequest {
// continue polling if status code is 400 and "error" is "authorization_pending"
apiErr, err := apiErr(bodyBytes)
if err != nil {
return backoff.Permanent(fmt.Errorf("fetching access token polling received unexpected API error body %q", string(bodyBytes)))
}
if apiErr.ErrorType != "authorization_pending" && apiErr.ErrorType != "slow_down" {
return backoff.Permanent(fmt.Errorf("fetching access token polling received unexpected API polling error %q - %q", apiErr.ErrorType, apiErr.ErrorDescription))
}
return errors.New("continue polling")
}
return backoff.Permanent(fmt.Errorf("fetching access token polling received unexpected API status %q %q", resp.Status, string(bodyBytes)))
}
bOff := boff.NewBackoff(context.Background())
err = backoff.Retry(poll, bOff)
if err != nil {
return nil, err
}
at = &okta.AccessToken{}
err = json.NewDecoder(bytes.NewReader(bodyBytes)).Decode(at)
if err != nil {
return nil, err
}
return
}
// authorize see:
// https://developer.okta.com/docs/reference/api/oidc/#device-authorize
func (w *WebSSOAuthentication) authorize() (*okta.DeviceAuthorization, error) {
clientID := w.config.OIDCAppID()
apiURL := fmt.Sprintf("https://%s/oauth2/v1/device/authorize", w.config.OrgDomain())
data := url.Values{
"client_id": {clientID},
"scope": {"openid okta.apps.sso okta.apps.read okta.users.read.self"},
}
body := strings.NewReader(data.Encode())
req, err := http.NewRequest(http.MethodPost, apiURL, body)
if err != nil {
return nil, err
}
req.Header.Add(accept, utils.ApplicationJSON)
req.Header.Add(utils.ContentType, utils.ApplicationXFORM)
req.Header.Add(utils.UserAgentHeader, config.UserAgentValue)
req.Header.Add(utils.XOktaAWSCLIOperationHeader, utils.XOktaAWSCLIWebOperation)
resp, err := w.config.HTTPClient().Do(req)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("authorize received API response %q", resp.Status)
}
ct := resp.Header.Get(utils.ContentType)
if !strings.Contains(ct, utils.ApplicationJSON) {
return nil, fmt.Errorf("authorize non-JSON API response content type %q", ct)
}
var da okta.DeviceAuthorization
err = json.NewDecoder(resp.Body).Decode(&da)
if err != nil {
return nil, err
}
return &da, nil
}
func findSAMLResponse(n *html.Node) (val string, found bool) {
if n == nil {
return
}
if n.Type == html.ElementNode && n.Data == "input" {
for _, a := range n.Attr {
if a.Key == nameKey && a.Val == "SAMLResponse" {
found = true
}
if a.Key == "value" {
val = a.Val
}
}
if found {
return
}
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
if val, found = findSAMLResponse(c); found {
return
}
}
return