-
Notifications
You must be signed in to change notification settings - Fork 654
/
shared_config.go
1384 lines (1152 loc) · 40.7 KB
/
shared_config.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 config
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/feature/ec2/imds"
"github.com/aws/aws-sdk-go-v2/internal/ini"
"github.com/aws/aws-sdk-go-v2/internal/shareddefaults"
"github.com/aws/smithy-go/logging"
)
const (
// Prefix to use for filtering profiles. The profile prefix should only
// exist in the shared config file, not the credentials file.
profilePrefix = `profile `
// Prefix to be used for SSO sections. These are supposed to only exist in
// the shared config file, not the credentials file.
ssoSectionPrefix = `sso-session `
// string equivalent for boolean
endpointDiscoveryDisabled = `false`
endpointDiscoveryEnabled = `true`
endpointDiscoveryAuto = `auto`
// Static Credentials group
accessKeyIDKey = `aws_access_key_id` // group required
secretAccessKey = `aws_secret_access_key` // group required
sessionTokenKey = `aws_session_token` // optional
// Assume Role Credentials group
roleArnKey = `role_arn` // group required
sourceProfileKey = `source_profile` // group required
credentialSourceKey = `credential_source` // group required (or source_profile)
externalIDKey = `external_id` // optional
mfaSerialKey = `mfa_serial` // optional
roleSessionNameKey = `role_session_name` // optional
roleDurationSecondsKey = "duration_seconds" // optional
// AWS Single Sign-On (AWS SSO) group
ssoSessionNameKey = "sso_session"
ssoRegionKey = "sso_region"
ssoStartURLKey = "sso_start_url"
ssoAccountIDKey = "sso_account_id"
ssoRoleNameKey = "sso_role_name"
// Additional Config fields
regionKey = `region`
// endpoint discovery group
enableEndpointDiscoveryKey = `endpoint_discovery_enabled` // optional
// External Credential process
credentialProcessKey = `credential_process` // optional
// Web Identity Token File
webIdentityTokenFileKey = `web_identity_token_file` // optional
// S3 ARN Region Usage
s3UseARNRegionKey = "s3_use_arn_region"
ec2MetadataServiceEndpointModeKey = "ec2_metadata_service_endpoint_mode"
ec2MetadataServiceEndpointKey = "ec2_metadata_service_endpoint"
// Use DualStack Endpoint Resolution
useDualStackEndpoint = "use_dualstack_endpoint"
// DefaultSharedConfigProfile is the default profile to be used when
// loading configuration from the config files if another profile name
// is not provided.
DefaultSharedConfigProfile = `default`
// S3 Disable Multi-Region AccessPoints
s3DisableMultiRegionAccessPointsKey = `s3_disable_multiregion_access_points`
useFIPSEndpointKey = "use_fips_endpoint"
defaultsModeKey = "defaults_mode"
// Retry options
retryMaxAttemptsKey = "max_attempts"
retryModeKey = "retry_mode"
caBundleKey = "ca_bundle"
)
// defaultSharedConfigProfile allows for swapping the default profile for testing
var defaultSharedConfigProfile = DefaultSharedConfigProfile
// DefaultSharedCredentialsFilename returns the SDK's default file path
// for the shared credentials file.
//
// Builds the shared config file path based on the OS's platform.
//
// - Linux/Unix: $HOME/.aws/credentials
// - Windows: %USERPROFILE%\.aws\credentials
func DefaultSharedCredentialsFilename() string {
return filepath.Join(shareddefaults.UserHomeDir(), ".aws", "credentials")
}
// DefaultSharedConfigFilename returns the SDK's default file path for
// the shared config file.
//
// Builds the shared config file path based on the OS's platform.
//
// - Linux/Unix: $HOME/.aws/config
// - Windows: %USERPROFILE%\.aws\config
func DefaultSharedConfigFilename() string {
return filepath.Join(shareddefaults.UserHomeDir(), ".aws", "config")
}
// DefaultSharedConfigFiles is a slice of the default shared config files that
// the will be used in order to load the SharedConfig.
var DefaultSharedConfigFiles = []string{
DefaultSharedConfigFilename(),
}
// DefaultSharedCredentialsFiles is a slice of the default shared credentials
// files that the will be used in order to load the SharedConfig.
var DefaultSharedCredentialsFiles = []string{
DefaultSharedCredentialsFilename(),
}
// SSOSession provides the shared configuration parameters of the sso-session
// section.
type SSOSession struct {
Name string
SSORegion string
SSOStartURL string
}
func (s *SSOSession) setFromIniSection(section ini.Section) {
updateString(&s.Name, section, ssoSessionNameKey)
updateString(&s.SSORegion, section, ssoRegionKey)
updateString(&s.SSOStartURL, section, ssoStartURLKey)
}
// SharedConfig represents the configuration fields of the SDK config files.
type SharedConfig struct {
Profile string
// Credentials values from the config file. Both aws_access_key_id
// and aws_secret_access_key must be provided together in the same file
// to be considered valid. The values will be ignored if not a complete group.
// aws_session_token is an optional field that can be provided if both of the
// other two fields are also provided.
//
// aws_access_key_id
// aws_secret_access_key
// aws_session_token
Credentials aws.Credentials
CredentialSource string
CredentialProcess string
WebIdentityTokenFile string
// SSO session options
SSOSessionName string
SSOSession *SSOSession
// Legacy SSO session options
SSORegion string
SSOStartURL string
// SSO fields not used
SSOAccountID string
SSORoleName string
RoleARN string
ExternalID string
MFASerial string
RoleSessionName string
RoleDurationSeconds *time.Duration
SourceProfileName string
Source *SharedConfig
// Region is the region the SDK should use for looking up AWS service endpoints
// and signing requests.
//
// region = us-west-2
Region string
// EnableEndpointDiscovery can be enabled or disabled in the shared config
// by setting endpoint_discovery_enabled to true, or false respectively.
//
// endpoint_discovery_enabled = true
EnableEndpointDiscovery aws.EndpointDiscoveryEnableState
// Specifies if the S3 service should allow ARNs to direct the region
// the client's requests are sent to.
//
// s3_use_arn_region=true
S3UseARNRegion *bool
// Specifies the EC2 Instance Metadata Service default endpoint selection
// mode (IPv4 or IPv6)
//
// ec2_metadata_service_endpoint_mode=IPv6
EC2IMDSEndpointMode imds.EndpointModeState
// Specifies the EC2 Instance Metadata Service endpoint to use. If
// specified it overrides EC2IMDSEndpointMode.
//
// ec2_metadata_service_endpoint=http://fd00:ec2::254
EC2IMDSEndpoint string
// Specifies if the S3 service should disable support for Multi-Region
// access-points
//
// s3_disable_multiregion_access_points=true
S3DisableMultiRegionAccessPoints *bool
// Specifies that SDK clients must resolve a dual-stack endpoint for
// services.
//
// use_dualstack_endpoint=true
UseDualStackEndpoint aws.DualStackEndpointState
// Specifies that SDK clients must resolve a FIPS endpoint for
// services.
//
// use_fips_endpoint=true
UseFIPSEndpoint aws.FIPSEndpointState
// Specifies which defaults mode should be used by services.
//
// defaults_mode=standard
DefaultsMode aws.DefaultsMode
// Specifies the maximum number attempts an API client will call an
// operation that fails with a retryable error.
//
// max_attempts=3
RetryMaxAttempts int
// Specifies the retry model the API client will be created with.
//
// retry_mode=standard
RetryMode aws.RetryMode
// Sets the path to a custom Credentials Authority (CA) Bundle PEM file
// that the SDK will use instead of the system's root CA bundle. Only use
// this if you want to configure the SDK to use a custom set of CAs.
//
// Enabling this option will attempt to merge the Transport into the SDK's
// HTTP client. If the client's Transport is not a http.Transport an error
// will be returned. If the Transport's TLS config is set this option will
// cause the SDK to overwrite the Transport's TLS config's RootCAs value.
//
// Setting a custom HTTPClient in the aws.Config options will override this
// setting. To use this option and custom HTTP client, the HTTP client
// needs to be provided when creating the config. Not the service client.
//
// ca_bundle=$HOME/my_custom_ca_bundle
CustomCABundle string
}
func (c SharedConfig) getDefaultsMode(ctx context.Context) (value aws.DefaultsMode, ok bool, err error) {
if len(c.DefaultsMode) == 0 {
return "", false, nil
}
return c.DefaultsMode, true, nil
}
// GetRetryMaxAttempts returns the maximum number of attempts an API client
// created Retryer should attempt an operation call before failing.
func (c SharedConfig) GetRetryMaxAttempts(ctx context.Context) (value int, ok bool, err error) {
if c.RetryMaxAttempts == 0 {
return 0, false, nil
}
return c.RetryMaxAttempts, true, nil
}
// GetRetryMode returns the model the API client should create its Retryer in.
func (c SharedConfig) GetRetryMode(ctx context.Context) (value aws.RetryMode, ok bool, err error) {
if len(c.RetryMode) == 0 {
return "", false, nil
}
return c.RetryMode, true, nil
}
// GetS3UseARNRegion returns if the S3 service should allow ARNs to direct the region
// the client's requests are sent to.
func (c SharedConfig) GetS3UseARNRegion(ctx context.Context) (value, ok bool, err error) {
if c.S3UseARNRegion == nil {
return false, false, nil
}
return *c.S3UseARNRegion, true, nil
}
// GetEnableEndpointDiscovery returns if the enable_endpoint_discovery is set.
func (c SharedConfig) GetEnableEndpointDiscovery(ctx context.Context) (value aws.EndpointDiscoveryEnableState, ok bool, err error) {
if c.EnableEndpointDiscovery == aws.EndpointDiscoveryUnset {
return aws.EndpointDiscoveryUnset, false, nil
}
return c.EnableEndpointDiscovery, true, nil
}
// GetS3DisableMultiRegionAccessPoints returns if the S3 service should disable support for Multi-Region
// access-points.
func (c SharedConfig) GetS3DisableMultiRegionAccessPoints(ctx context.Context) (value, ok bool, err error) {
if c.S3DisableMultiRegionAccessPoints == nil {
return false, false, nil
}
return *c.S3DisableMultiRegionAccessPoints, true, nil
}
// GetRegion returns the region for the profile if a region is set.
func (c SharedConfig) getRegion(ctx context.Context) (string, bool, error) {
if len(c.Region) == 0 {
return "", false, nil
}
return c.Region, true, nil
}
// GetCredentialsProvider returns the credentials for a profile if they were set.
func (c SharedConfig) getCredentialsProvider() (aws.Credentials, bool, error) {
return c.Credentials, true, nil
}
// GetEC2IMDSEndpointMode implements a EC2IMDSEndpointMode option resolver interface.
func (c SharedConfig) GetEC2IMDSEndpointMode() (imds.EndpointModeState, bool, error) {
if c.EC2IMDSEndpointMode == imds.EndpointModeStateUnset {
return imds.EndpointModeStateUnset, false, nil
}
return c.EC2IMDSEndpointMode, true, nil
}
// GetEC2IMDSEndpoint implements a EC2IMDSEndpoint option resolver interface.
func (c SharedConfig) GetEC2IMDSEndpoint() (string, bool, error) {
if len(c.EC2IMDSEndpoint) == 0 {
return "", false, nil
}
return c.EC2IMDSEndpoint, true, nil
}
// GetUseDualStackEndpoint returns whether the service's dual-stack endpoint should be
// used for requests.
func (c SharedConfig) GetUseDualStackEndpoint(ctx context.Context) (value aws.DualStackEndpointState, found bool, err error) {
if c.UseDualStackEndpoint == aws.DualStackEndpointStateUnset {
return aws.DualStackEndpointStateUnset, false, nil
}
return c.UseDualStackEndpoint, true, nil
}
// GetUseFIPSEndpoint returns whether the service's FIPS endpoint should be
// used for requests.
func (c SharedConfig) GetUseFIPSEndpoint(ctx context.Context) (value aws.FIPSEndpointState, found bool, err error) {
if c.UseFIPSEndpoint == aws.FIPSEndpointStateUnset {
return aws.FIPSEndpointStateUnset, false, nil
}
return c.UseFIPSEndpoint, true, nil
}
// GetCustomCABundle returns the custom CA bundle's PEM bytes if the file was
func (c SharedConfig) getCustomCABundle(context.Context) (io.Reader, bool, error) {
if len(c.CustomCABundle) == 0 {
return nil, false, nil
}
b, err := ioutil.ReadFile(c.CustomCABundle)
if err != nil {
return nil, false, err
}
return bytes.NewReader(b), true, nil
}
// loadSharedConfigIgnoreNotExist is an alias for loadSharedConfig with the
// addition of ignoring when none of the files exist or when the profile
// is not found in any of the files.
func loadSharedConfigIgnoreNotExist(ctx context.Context, configs configs) (Config, error) {
cfg, err := loadSharedConfig(ctx, configs)
if err != nil {
if _, ok := err.(SharedConfigProfileNotExistError); ok {
return SharedConfig{}, nil
}
return nil, err
}
return cfg, nil
}
// loadSharedConfig uses the configs passed in to load the SharedConfig from file
// The file names and profile name are sourced from the configs.
//
// If profile name is not provided DefaultSharedConfigProfile (default) will
// be used.
//
// If shared config filenames are not provided DefaultSharedConfigFiles will
// be used.
//
// Config providers used:
// * sharedConfigProfileProvider
// * sharedConfigFilesProvider
func loadSharedConfig(ctx context.Context, configs configs) (Config, error) {
var profile string
var configFiles []string
var credentialsFiles []string
var ok bool
var err error
profile, ok, err = getSharedConfigProfile(ctx, configs)
if err != nil {
return nil, err
}
if !ok {
profile = defaultSharedConfigProfile
}
configFiles, ok, err = getSharedConfigFiles(ctx, configs)
if err != nil {
return nil, err
}
credentialsFiles, ok, err = getSharedCredentialsFiles(ctx, configs)
if err != nil {
return nil, err
}
// setup logger if log configuration warning is seti
var logger logging.Logger
logWarnings, found, err := getLogConfigurationWarnings(ctx, configs)
if err != nil {
return SharedConfig{}, err
}
if found && logWarnings {
logger, found, err = getLogger(ctx, configs)
if err != nil {
return SharedConfig{}, err
}
if !found {
logger = logging.NewStandardLogger(os.Stderr)
}
}
return LoadSharedConfigProfile(ctx, profile,
func(o *LoadSharedConfigOptions) {
o.Logger = logger
o.ConfigFiles = configFiles
o.CredentialsFiles = credentialsFiles
},
)
}
// LoadSharedConfigOptions struct contains optional values that can be used to load the config.
type LoadSharedConfigOptions struct {
// CredentialsFiles are the shared credentials files
CredentialsFiles []string
// ConfigFiles are the shared config files
ConfigFiles []string
// Logger is the logger used to log shared config behavior
Logger logging.Logger
}
// LoadSharedConfigProfile retrieves the configuration from the list of files
// using the profile provided. The order the files are listed will determine
// precedence. Values in subsequent files will overwrite values defined in
// earlier files.
//
// For example, given two files A and B. Both define credentials. If the order
// of the files are A then B, B's credential values will be used instead of A's.
//
// If config files are not set, SDK will default to using a file at location `.aws/config` if present.
// If credentials files are not set, SDK will default to using a file at location `.aws/credentials` if present.
// No default files are set, if files set to an empty slice.
//
// You can read more about shared config and credentials file location at
// https://docs.aws.amazon.com/credref/latest/refdocs/file-location.html#file-location
func LoadSharedConfigProfile(ctx context.Context, profile string, optFns ...func(*LoadSharedConfigOptions)) (SharedConfig, error) {
var option LoadSharedConfigOptions
for _, fn := range optFns {
fn(&option)
}
if option.ConfigFiles == nil {
option.ConfigFiles = DefaultSharedConfigFiles
}
if option.CredentialsFiles == nil {
option.CredentialsFiles = DefaultSharedCredentialsFiles
}
// load shared configuration sections from shared configuration INI options
configSections, err := loadIniFiles(option.ConfigFiles)
if err != nil {
return SharedConfig{}, err
}
// check for profile prefix and drop duplicates or invalid profiles
err = processConfigSections(ctx, &configSections, option.Logger)
if err != nil {
return SharedConfig{}, err
}
// load shared credentials sections from shared credentials INI options
credentialsSections, err := loadIniFiles(option.CredentialsFiles)
if err != nil {
return SharedConfig{}, err
}
// check for profile prefix and drop duplicates or invalid profiles
err = processCredentialsSections(ctx, &credentialsSections, option.Logger)
if err != nil {
return SharedConfig{}, err
}
err = mergeSections(&configSections, credentialsSections)
if err != nil {
return SharedConfig{}, err
}
cfg := SharedConfig{}
profiles := map[string]struct{}{}
if err = cfg.setFromIniSections(profiles, profile, configSections, option.Logger); err != nil {
return SharedConfig{}, err
}
return cfg, nil
}
func processConfigSections(ctx context.Context, sections *ini.Sections, logger logging.Logger) error {
skipSections := map[string]struct{}{}
for _, section := range sections.List() {
if _, ok := skipSections[section]; ok {
continue
}
// drop sections from config file that do not have expected prefixes.
switch {
case strings.HasPrefix(section, profilePrefix):
// Rename sections to remove "profile " prefixing to match with
// credentials file. If default is already present, it will be
// dropped.
newName, err := renameProfileSection(section, sections, logger)
if err != nil {
return fmt.Errorf("failed to rename profile section, %w", err)
}
skipSections[newName] = struct{}{}
case strings.HasPrefix(section, ssoSectionPrefix):
case strings.EqualFold(section, "default"):
default:
// drop this section, as invalid profile name
sections.DeleteSection(section)
if logger != nil {
logger.Logf(logging.Debug, "A profile defined with name `%v` is ignored. "+
"For use within a shared configuration file, "+
"a non-default profile must have `profile ` "+
"prefixed to the profile name.",
section,
)
}
}
}
return nil
}
func renameProfileSection(section string, sections *ini.Sections, logger logging.Logger) (string, error) {
v, ok := sections.GetSection(section)
if !ok {
return "", fmt.Errorf("error processing profiles within the shared configuration files")
}
// delete section with profile as prefix
sections.DeleteSection(section)
// set the value to non-prefixed name in sections.
section = strings.TrimPrefix(section, profilePrefix)
if sections.HasSection(section) {
oldSection, _ := sections.GetSection(section)
v.Logs = append(v.Logs,
fmt.Sprintf("A non-default profile not prefixed with `profile ` found in %s, "+
"overriding non-default profile from %s",
v.SourceFile, oldSection.SourceFile))
sections.DeleteSection(section)
}
// assign non-prefixed name to section
v.Name = section
sections.SetSection(section, v)
return section, nil
}
func processCredentialsSections(ctx context.Context, sections *ini.Sections, logger logging.Logger) error {
for _, section := range sections.List() {
// drop profiles with prefix for credential files
if strings.HasPrefix(section, profilePrefix) {
// drop this section, as invalid profile name
sections.DeleteSection(section)
if logger != nil {
logger.Logf(logging.Debug,
"The profile defined with name `%v` is ignored. A profile with the `profile ` prefix is invalid "+
"for the shared credentials file.\n",
section,
)
}
}
}
return nil
}
func loadIniFiles(filenames []string) (ini.Sections, error) {
mergedSections := ini.NewSections()
for _, filename := range filenames {
sections, err := ini.OpenFile(filename)
var v *ini.UnableToReadFile
if ok := errors.As(err, &v); ok {
// Skip files which can't be opened and read for whatever reason.
// We treat such files as empty, and do not fall back to other locations.
continue
} else if err != nil {
return ini.Sections{}, SharedConfigLoadError{Filename: filename, Err: err}
}
// mergeSections into mergedSections
err = mergeSections(&mergedSections, sections)
if err != nil {
return ini.Sections{}, SharedConfigLoadError{Filename: filename, Err: err}
}
}
return mergedSections, nil
}
// mergeSections merges source section properties into destination section properties
func mergeSections(dst *ini.Sections, src ini.Sections) error {
for _, sectionName := range src.List() {
srcSection, _ := src.GetSection(sectionName)
if (!srcSection.Has(accessKeyIDKey) && srcSection.Has(secretAccessKey)) ||
(srcSection.Has(accessKeyIDKey) && !srcSection.Has(secretAccessKey)) {
srcSection.Errors = append(srcSection.Errors,
fmt.Errorf("partial credentials found for profile %v", sectionName))
}
if !dst.HasSection(sectionName) {
dst.SetSection(sectionName, srcSection)
continue
}
// merge with destination srcSection
dstSection, _ := dst.GetSection(sectionName)
// errors should be overriden if any
dstSection.Errors = srcSection.Errors
// Access key id update
if srcSection.Has(accessKeyIDKey) && srcSection.Has(secretAccessKey) {
accessKey := srcSection.String(accessKeyIDKey)
secretKey := srcSection.String(secretAccessKey)
if dstSection.Has(accessKeyIDKey) {
dstSection.Logs = append(dstSection.Logs, newMergeKeyLogMessage(sectionName, accessKeyIDKey,
dstSection.SourceFile[accessKeyIDKey], srcSection.SourceFile[accessKeyIDKey]))
}
// update access key
v, err := ini.NewStringValue(accessKey)
if err != nil {
return fmt.Errorf("error merging access key, %w", err)
}
dstSection.UpdateValue(accessKeyIDKey, v)
// update secret key
v, err = ini.NewStringValue(secretKey)
if err != nil {
return fmt.Errorf("error merging secret key, %w", err)
}
dstSection.UpdateValue(secretAccessKey, v)
// update session token
if err = mergeStringKey(&srcSection, &dstSection, sectionName, sessionTokenKey); err != nil {
return err
}
// update source file to reflect where the static creds came from
dstSection.UpdateSourceFile(accessKeyIDKey, srcSection.SourceFile[accessKeyIDKey])
dstSection.UpdateSourceFile(secretAccessKey, srcSection.SourceFile[secretAccessKey])
}
stringKeys := []string{
roleArnKey,
sourceProfileKey,
credentialSourceKey,
externalIDKey,
mfaSerialKey,
roleSessionNameKey,
regionKey,
enableEndpointDiscoveryKey,
credentialProcessKey,
webIdentityTokenFileKey,
s3UseARNRegionKey,
s3DisableMultiRegionAccessPointsKey,
ec2MetadataServiceEndpointModeKey,
ec2MetadataServiceEndpointKey,
useDualStackEndpoint,
useFIPSEndpointKey,
defaultsModeKey,
retryModeKey,
caBundleKey,
ssoSessionNameKey,
ssoAccountIDKey,
ssoRegionKey,
ssoRoleNameKey,
ssoStartURLKey,
}
for i := range stringKeys {
if err := mergeStringKey(&srcSection, &dstSection, sectionName, stringKeys[i]); err != nil {
return err
}
}
intKeys := []string{
roleDurationSecondsKey,
retryMaxAttemptsKey,
}
for i := range intKeys {
if err := mergeIntKey(&srcSection, &dstSection, sectionName, intKeys[i]); err != nil {
return err
}
}
// set srcSection on dst srcSection
*dst = dst.SetSection(sectionName, dstSection)
}
return nil
}
func mergeStringKey(srcSection *ini.Section, dstSection *ini.Section, sectionName, key string) error {
if srcSection.Has(key) {
srcValue := srcSection.String(key)
val, err := ini.NewStringValue(srcValue)
if err != nil {
return fmt.Errorf("error merging %s, %w", key, err)
}
if dstSection.Has(key) {
dstSection.Logs = append(dstSection.Logs, newMergeKeyLogMessage(sectionName, key,
dstSection.SourceFile[key], srcSection.SourceFile[key]))
}
dstSection.UpdateValue(key, val)
dstSection.UpdateSourceFile(key, srcSection.SourceFile[key])
}
return nil
}
func mergeIntKey(srcSection *ini.Section, dstSection *ini.Section, sectionName, key string) error {
if srcSection.Has(key) {
srcValue := srcSection.Int(key)
v, err := ini.NewIntValue(srcValue)
if err != nil {
return fmt.Errorf("error merging %s, %w", key, err)
}
if dstSection.Has(key) {
dstSection.Logs = append(dstSection.Logs, newMergeKeyLogMessage(sectionName, key,
dstSection.SourceFile[key], srcSection.SourceFile[key]))
}
dstSection.UpdateValue(key, v)
dstSection.UpdateSourceFile(key, srcSection.SourceFile[key])
}
return nil
}
func newMergeKeyLogMessage(sectionName, key, dstSourceFile, srcSourceFile string) string {
return fmt.Sprintf("For profile: %v, overriding %v value, defined in %v "+
"with a %v value found in a duplicate profile defined at file %v. \n",
sectionName, key, dstSourceFile, key, srcSourceFile)
}
// Returns an error if all of the files fail to load. If at least one file is
// successfully loaded and contains the profile, no error will be returned.
func (c *SharedConfig) setFromIniSections(profiles map[string]struct{}, profile string,
sections ini.Sections, logger logging.Logger) error {
c.Profile = profile
section, ok := sections.GetSection(profile)
if !ok {
return SharedConfigProfileNotExistError{
Profile: profile,
}
}
// if logs are appended to the section, log them
if section.Logs != nil && logger != nil {
for _, log := range section.Logs {
logger.Logf(logging.Debug, log)
}
}
// set config from the provided INI section
err := c.setFromIniSection(profile, section)
if err != nil {
return fmt.Errorf("error fetching config from profile, %v, %w", profile, err)
}
if _, ok := profiles[profile]; ok {
// if this is the second instance of the profile the Assume Role
// options must be cleared because they are only valid for the
// first reference of a profile. The self linked instance of the
// profile only have credential provider options.
c.clearAssumeRoleOptions()
} else {
// First time a profile has been seen. Assert if the credential type
// requires a role ARN, the ARN is also set
if err := c.validateCredentialsConfig(profile); err != nil {
return err
}
}
// if not top level profile and has credentials, return with credentials.
if len(profiles) != 0 && c.Credentials.HasKeys() {
return nil
}
profiles[profile] = struct{}{}
// validate no colliding credentials type are present
if err := c.validateCredentialType(); err != nil {
return err
}
// Link source profiles for assume roles
if len(c.SourceProfileName) != 0 {
// Linked profile via source_profile ignore credential provider
// options, the source profile must provide the credentials.
c.clearCredentialOptions()
srcCfg := &SharedConfig{}
err := srcCfg.setFromIniSections(profiles, c.SourceProfileName, sections, logger)
if err != nil {
// SourceProfileName that doesn't exist is an error in configuration.
if _, ok := err.(SharedConfigProfileNotExistError); ok {
err = SharedConfigAssumeRoleError{
RoleARN: c.RoleARN,
Profile: c.SourceProfileName,
Err: err,
}
}
return err
}
if !srcCfg.hasCredentials() {
return SharedConfigAssumeRoleError{
RoleARN: c.RoleARN,
Profile: c.SourceProfileName,
}
}
c.Source = srcCfg
}
// If the profile contains an SSO session parameter, the session MUST exist
// as a section in the config file. Load the SSO session using the name
// provided. If the session section is not found or incomplete an error
// will be returned.
if c.hasSSOTokenProviderConfiguration() {
section, ok := sections.GetSection(ssoSectionPrefix + strings.TrimSpace(c.SSOSessionName))
if !ok {
return fmt.Errorf("failed to find SSO session section, %v", c.SSOSessionName)
}
var ssoSession SSOSession
ssoSession.setFromIniSection(section)
ssoSession.Name = c.SSOSessionName
c.SSOSession = &ssoSession
}
return nil
}
// setFromIniSection loads the configuration from the profile section defined in
// the provided INI file. A SharedConfig pointer type value is used so that
// multiple config file loadings can be chained.
//
// Only loads complete logically grouped values, and will not set fields in cfg
// for incomplete grouped values in the config. Such as credentials. For example
// if a config file only includes aws_access_key_id but no aws_secret_access_key
// the aws_access_key_id will be ignored.
func (c *SharedConfig) setFromIniSection(profile string, section ini.Section) error {
if len(section.Name) == 0 {
sources := make([]string, 0)
for _, v := range section.SourceFile {
sources = append(sources, v)
}
return fmt.Errorf("parsing error : could not find profile section name after processing files: %v", sources)
}
if len(section.Errors) != 0 {
var errStatement string
for i, e := range section.Errors {
errStatement = fmt.Sprintf("%d, %v\n", i+1, e.Error())
}
return fmt.Errorf("Error using profile: \n %v", errStatement)
}
// Assume Role
updateString(&c.RoleARN, section, roleArnKey)
updateString(&c.ExternalID, section, externalIDKey)
updateString(&c.MFASerial, section, mfaSerialKey)
updateString(&c.RoleSessionName, section, roleSessionNameKey)
updateString(&c.SourceProfileName, section, sourceProfileKey)
updateString(&c.CredentialSource, section, credentialSourceKey)
updateString(&c.Region, section, regionKey)
// AWS Single Sign-On (AWS SSO)
// SSO session options
updateString(&c.SSOSessionName, section, ssoSessionNameKey)
// Legacy SSO session options
updateString(&c.SSORegion, section, ssoRegionKey)
updateString(&c.SSOStartURL, section, ssoStartURLKey)
// SSO fields not used
updateString(&c.SSOAccountID, section, ssoAccountIDKey)
updateString(&c.SSORoleName, section, ssoRoleNameKey)
if section.Has(roleDurationSecondsKey) {
d := time.Duration(section.Int(roleDurationSecondsKey)) * time.Second
c.RoleDurationSeconds = &d
}
updateString(&c.CredentialProcess, section, credentialProcessKey)
updateString(&c.WebIdentityTokenFile, section, webIdentityTokenFileKey)
updateEndpointDiscoveryType(&c.EnableEndpointDiscovery, section, enableEndpointDiscoveryKey)
updateBoolPtr(&c.S3UseARNRegion, section, s3UseARNRegionKey)
updateBoolPtr(&c.S3DisableMultiRegionAccessPoints, section, s3DisableMultiRegionAccessPointsKey)
if err := updateEC2MetadataServiceEndpointMode(&c.EC2IMDSEndpointMode, section, ec2MetadataServiceEndpointModeKey); err != nil {
return fmt.Errorf("failed to load %s from shared config, %v", ec2MetadataServiceEndpointModeKey, err)
}
updateString(&c.EC2IMDSEndpoint, section, ec2MetadataServiceEndpointKey)
updateUseDualStackEndpoint(&c.UseDualStackEndpoint, section, useDualStackEndpoint)
updateUseFIPSEndpoint(&c.UseFIPSEndpoint, section, useFIPSEndpointKey)
if err := updateDefaultsMode(&c.DefaultsMode, section, defaultsModeKey); err != nil {
return fmt.Errorf("failed to load %s from shared config, %w", defaultsModeKey, err)
}
if err := updateInt(&c.RetryMaxAttempts, section, retryMaxAttemptsKey); err != nil {
return fmt.Errorf("failed to load %s from shared config, %w", retryMaxAttemptsKey, err)
}
if err := updateRetryMode(&c.RetryMode, section, retryModeKey); err != nil {
return fmt.Errorf("failed to load %s from shared config, %w", retryModeKey, err)
}
updateString(&c.CustomCABundle, section, caBundleKey)
// Shared Credentials
creds := aws.Credentials{
AccessKeyID: section.String(accessKeyIDKey),
SecretAccessKey: section.String(secretAccessKey),
SessionToken: section.String(sessionTokenKey),
Source: fmt.Sprintf("SharedConfigCredentials: %s", section.SourceFile[accessKeyIDKey]),
}
if creds.HasKeys() {
c.Credentials = creds
}
return nil