12 "github.com/aws/aws-sdk-go/aws"
13 "github.com/aws/aws-sdk-go/aws/awserr"
14 "github.com/aws/aws-sdk-go/aws/client"
15 "github.com/aws/aws-sdk-go/aws/corehandlers"
16 "github.com/aws/aws-sdk-go/aws/credentials"
17 "github.com/aws/aws-sdk-go/aws/credentials/stscreds"
18 "github.com/aws/aws-sdk-go/aws/defaults"
19 "github.com/aws/aws-sdk-go/aws/endpoints"
20 "github.com/aws/aws-sdk-go/aws/request"
23 // A Session provides a central location to create service clients from and
24 // store configurations and request handlers for those services.
26 // Sessions are safe to create service clients concurrently, but it is not safe
27 // to mutate the Session concurrently.
29 // The Session satisfies the service client's client.ClientConfigProvider.
32 Handlers request.Handlers
35 // New creates a new instance of the handlers merging in the provided configs
36 // on top of the SDK's default configurations. Once the Session is created it
37 // can be mutated to modify the Config or Handlers. The Session is safe to be
38 // read concurrently, but it should not be written to concurrently.
40 // If the AWS_SDK_LOAD_CONFIG environment is set to a truthy value, the New
41 // method could now encounter an error when loading the configuration. When
42 // The environment variable is set, and an error occurs, New will return a
43 // session that will fail all requests reporting the error that occurred while
44 // loading the session. Use NewSession to get the error when creating the
47 // If the AWS_SDK_LOAD_CONFIG environment variable is set to a truthy value
48 // the shared config file (~/.aws/config) will also be loaded, in addition to
49 // the shared credentials file (~/.aws/credentials). Values set in both the
50 // shared config, and shared credentials will be taken from the shared
53 // Deprecated: Use NewSession functions to create sessions instead. NewSession
54 // has the same functionality as New except an error can be returned when the
55 // func is called instead of waiting to receive an error until a request is made.
56 func New(cfgs ...*aws.Config) *Session {
57 // load initial config from environment
58 envCfg := loadEnvConfig()
60 if envCfg.EnableSharedConfig {
61 s, err := newSession(Options{}, envCfg, cfgs...)
63 // Old session.New expected all errors to be discovered when
64 // a request is made, and would report the errors then. This
65 // needs to be replicated if an error occurs while creating
67 msg := "failed to create session with AWS_SDK_LOAD_CONFIG enabled. " +
68 "Use session.NewSession to handle errors occurring during session creation."
70 // Session creation failed, need to report the error and prevent
71 // any requests from succeeding.
72 s = &Session{Config: defaults.Config()}
73 s.Config.MergeIn(cfgs...)
74 s.Config.Logger.Log("ERROR:", msg, "Error:", err)
75 s.Handlers.Validate.PushBack(func(r *request.Request) {
82 return deprecatedNewSession(cfgs...)
85 // NewSession returns a new Session created from SDK defaults, config files,
86 // environment, and user provided config files. Once the Session is created
87 // it can be mutated to modify the Config or Handlers. The Session is safe to
88 // be read concurrently, but it should not be written to concurrently.
90 // If the AWS_SDK_LOAD_CONFIG environment variable is set to a truthy value
91 // the shared config file (~/.aws/config) will also be loaded in addition to
92 // the shared credentials file (~/.aws/credentials). Values set in both the
93 // shared config, and shared credentials will be taken from the shared
94 // credentials file. Enabling the Shared Config will also allow the Session
95 // to be built with retrieving credentials with AssumeRole set in the config.
97 // See the NewSessionWithOptions func for information on how to override or
98 // control through code how the Session will be created. Such as specifying the
99 // config profile, and controlling if shared config is enabled or not.
100 func NewSession(cfgs ...*aws.Config) (*Session, error) {
102 opts.Config.MergeIn(cfgs...)
104 return NewSessionWithOptions(opts)
107 // SharedConfigState provides the ability to optionally override the state
108 // of the session's creation based on the shared config being enabled or
110 type SharedConfigState int
113 // SharedConfigStateFromEnv does not override any state of the
114 // AWS_SDK_LOAD_CONFIG env var. It is the default value of the
115 // SharedConfigState type.
116 SharedConfigStateFromEnv SharedConfigState = iota
118 // SharedConfigDisable overrides the AWS_SDK_LOAD_CONFIG env var value
119 // and disables the shared config functionality.
122 // SharedConfigEnable overrides the AWS_SDK_LOAD_CONFIG env var value
123 // and enables the shared config functionality.
127 // Options provides the means to control how a Session is created and what
128 // configuration values will be loaded.
130 type Options struct {
131 // Provides config values for the SDK to use when creating service clients
132 // and making API requests to services. Any value set in with this field
133 // will override the associated value provided by the SDK defaults,
134 // environment or config files where relevant.
136 // If not set, configuration values from from SDK defaults, environment,
137 // config will be used.
140 // Overrides the config profile the Session should be created from. If not
141 // set the value of the environment variable will be loaded (AWS_PROFILE,
142 // or AWS_DEFAULT_PROFILE if the Shared Config is enabled).
144 // If not set and environment variables are not set the "default"
145 // (DefaultSharedConfigProfile) will be used as the profile to load the
146 // session config from.
149 // Instructs how the Session will be created based on the AWS_SDK_LOAD_CONFIG
150 // environment variable. By default a Session will be created using the
151 // value provided by the AWS_SDK_LOAD_CONFIG environment variable.
153 // Setting this value to SharedConfigEnable or SharedConfigDisable
154 // will allow you to override the AWS_SDK_LOAD_CONFIG environment variable
155 // and enable or disable the shared config functionality.
156 SharedConfigState SharedConfigState
158 // Ordered list of files the session will load configuration from.
159 // It will override environment variable AWS_SHARED_CREDENTIALS_FILE, AWS_CONFIG_FILE.
160 SharedConfigFiles []string
162 // When the SDK's shared config is configured to assume a role with MFA
163 // this option is required in order to provide the mechanism that will
164 // retrieve the MFA token. There is no default value for this field. If
165 // it is not set an error will be returned when creating the session.
167 // This token provider will be called when ever the assumed role's
168 // credentials need to be refreshed. Within the context of service clients
169 // all sharing the same session the SDK will ensure calls to the token
170 // provider are atomic. When sharing a token provider across multiple
171 // sessions additional synchronization logic is needed to ensure the
172 // token providers do not introduce race conditions. It is recommend to
173 // share the session where possible.
175 // stscreds.StdinTokenProvider is a basic implementation that will prompt
176 // from stdin for the MFA token code.
178 // This field is only used if the shared configuration is enabled, and
179 // the config enables assume role wit MFA via the mfa_serial field.
180 AssumeRoleTokenProvider func() (string, error)
182 // Reader for a custom Credentials Authority (CA) bundle in PEM format that
183 // the SDK will use instead of the default system's root CA bundle. Use this
184 // only if you want to replace the CA bundle the SDK uses for TLS requests.
186 // Enabling this option will attempt to merge the Transport into the SDK's HTTP
187 // client. If the client's Transport is not a http.Transport an error will be
188 // returned. If the Transport's TLS config is set this option will cause the SDK
189 // to overwrite the Transport's TLS config's RootCAs value. If the CA
190 // bundle reader contains multiple certificates all of them will be loaded.
192 // The Session option CustomCABundle is also available when creating sessions
193 // to also enable this feature. CustomCABundle session option field has priority
194 // over the AWS_CA_BUNDLE environment variable, and will be used if both are set.
195 CustomCABundle io.Reader
198 // NewSessionWithOptions returns a new Session created from SDK defaults, config files,
199 // environment, and user provided config files. This func uses the Options
200 // values to configure how the Session is created.
202 // If the AWS_SDK_LOAD_CONFIG environment variable is set to a truthy value
203 // the shared config file (~/.aws/config) will also be loaded in addition to
204 // the shared credentials file (~/.aws/credentials). Values set in both the
205 // shared config, and shared credentials will be taken from the shared
206 // credentials file. Enabling the Shared Config will also allow the Session
207 // to be built with retrieving credentials with AssumeRole set in the config.
209 // // Equivalent to session.New
210 // sess := session.Must(session.NewSessionWithOptions(session.Options{}))
212 // // Specify profile to load for the session's config
213 // sess := session.Must(session.NewSessionWithOptions(session.Options{
214 // Profile: "profile_name",
217 // // Specify profile for config and region for requests
218 // sess := session.Must(session.NewSessionWithOptions(session.Options{
219 // Config: aws.Config{Region: aws.String("us-east-1")},
220 // Profile: "profile_name",
223 // // Force enable Shared Config support
224 // sess := session.Must(session.NewSessionWithOptions(session.Options{
225 // SharedConfigState: session.SharedConfigEnable,
227 func NewSessionWithOptions(opts Options) (*Session, error) {
229 if opts.SharedConfigState == SharedConfigEnable {
230 envCfg = loadSharedEnvConfig()
232 envCfg = loadEnvConfig()
235 if len(opts.Profile) > 0 {
236 envCfg.Profile = opts.Profile
239 switch opts.SharedConfigState {
240 case SharedConfigDisable:
241 envCfg.EnableSharedConfig = false
242 case SharedConfigEnable:
243 envCfg.EnableSharedConfig = true
246 if len(envCfg.SharedCredentialsFile) == 0 {
247 envCfg.SharedCredentialsFile = defaults.SharedCredentialsFilename()
249 if len(envCfg.SharedConfigFile) == 0 {
250 envCfg.SharedConfigFile = defaults.SharedConfigFilename()
253 // Only use AWS_CA_BUNDLE if session option is not provided.
254 if len(envCfg.CustomCABundle) != 0 && opts.CustomCABundle == nil {
255 f, err := os.Open(envCfg.CustomCABundle)
257 return nil, awserr.New("LoadCustomCABundleError",
258 "failed to open custom CA bundle PEM file", err)
261 opts.CustomCABundle = f
264 return newSession(opts, envCfg, &opts.Config)
267 // Must is a helper function to ensure the Session is valid and there was no
268 // error when calling a NewSession function.
270 // This helper is intended to be used in variable initialization to load the
271 // Session and configuration at startup. Such as:
273 // var sess = session.Must(session.NewSession())
274 func Must(sess *Session, err error) *Session {
282 func deprecatedNewSession(cfgs ...*aws.Config) *Session {
283 cfg := defaults.Config()
284 handlers := defaults.Handlers()
286 // Apply the passed in configs so the configuration can be applied to the
287 // default credential chain
289 if cfg.EndpointResolver == nil {
290 // An endpoint resolver is required for a session to be able to provide
291 // endpoints for service client configurations.
292 cfg.EndpointResolver = endpoints.DefaultResolver()
294 cfg.Credentials = defaults.CredChain(cfg, handlers)
296 // Reapply any passed in configs to override credentials if set
309 func newSession(opts Options, envCfg envConfig, cfgs ...*aws.Config) (*Session, error) {
310 cfg := defaults.Config()
311 handlers := defaults.Handlers()
313 // Get a merged version of the user provided config to determine if
315 userCfg := &aws.Config{}
316 userCfg.MergeIn(cfgs...)
318 // Ordered config files will be loaded in with later files overwriting
319 // previous config file values.
320 var cfgFiles []string
321 if opts.SharedConfigFiles != nil {
322 cfgFiles = opts.SharedConfigFiles
324 cfgFiles = []string{envCfg.SharedConfigFile, envCfg.SharedCredentialsFile}
325 if !envCfg.EnableSharedConfig {
326 // The shared config file (~/.aws/config) is only loaded if instructed
327 // to load via the envConfig.EnableSharedConfig (AWS_SDK_LOAD_CONFIG).
328 cfgFiles = cfgFiles[1:]
332 // Load additional config from file(s)
333 sharedCfg, err := loadSharedConfig(envCfg.Profile, cfgFiles)
338 if err := mergeConfigSrcs(cfg, userCfg, envCfg, sharedCfg, handlers, opts); err != nil {
349 // Setup HTTP client with custom cert bundle if enabled
350 if opts.CustomCABundle != nil {
351 if err := loadCustomCABundle(s, opts.CustomCABundle); err != nil {
359 func loadCustomCABundle(s *Session, bundle io.Reader) error {
360 var t *http.Transport
361 switch v := s.Config.HTTPClient.Transport.(type) {
362 case *http.Transport:
365 if s.Config.HTTPClient.Transport != nil {
366 return awserr.New("LoadCustomCABundleError",
367 "unable to load custom CA bundle, HTTPClient's transport unsupported type", nil)
371 t = &http.Transport{}
374 p, err := loadCertPool(bundle)
378 if t.TLSClientConfig == nil {
379 t.TLSClientConfig = &tls.Config{}
381 t.TLSClientConfig.RootCAs = p
383 s.Config.HTTPClient.Transport = t
388 func loadCertPool(r io.Reader) (*x509.CertPool, error) {
389 b, err := ioutil.ReadAll(r)
391 return nil, awserr.New("LoadCustomCABundleError",
392 "failed to read custom CA bundle PEM file", err)
395 p := x509.NewCertPool()
396 if !p.AppendCertsFromPEM(b) {
397 return nil, awserr.New("LoadCustomCABundleError",
398 "failed to load custom CA bundle PEM file", err)
404 func mergeConfigSrcs(cfg, userCfg *aws.Config, envCfg envConfig, sharedCfg sharedConfig, handlers request.Handlers, sessOpts Options) error {
405 // Merge in user provided configuration
408 // Region if not already set by user
409 if len(aws.StringValue(cfg.Region)) == 0 {
410 if len(envCfg.Region) > 0 {
411 cfg.WithRegion(envCfg.Region)
412 } else if envCfg.EnableSharedConfig && len(sharedCfg.Region) > 0 {
413 cfg.WithRegion(sharedCfg.Region)
417 // Configure credentials if not already set
418 if cfg.Credentials == credentials.AnonymousCredentials && userCfg.Credentials == nil {
419 if len(envCfg.Creds.AccessKeyID) > 0 {
420 cfg.Credentials = credentials.NewStaticCredentialsFromCreds(
423 } else if envCfg.EnableSharedConfig && len(sharedCfg.AssumeRole.RoleARN) > 0 && sharedCfg.AssumeRoleSource != nil {
425 cfgCp.Credentials = credentials.NewStaticCredentialsFromCreds(
426 sharedCfg.AssumeRoleSource.Creds,
428 if len(sharedCfg.AssumeRole.MFASerial) > 0 && sessOpts.AssumeRoleTokenProvider == nil {
429 // AssumeRole Token provider is required if doing Assume Role
431 return AssumeRoleTokenProviderNotSetError{}
433 cfg.Credentials = stscreds.NewCredentials(
436 Handlers: handlers.Copy(),
438 sharedCfg.AssumeRole.RoleARN,
439 func(opt *stscreds.AssumeRoleProvider) {
440 opt.RoleSessionName = sharedCfg.AssumeRole.RoleSessionName
442 // Assume role with external ID
443 if len(sharedCfg.AssumeRole.ExternalID) > 0 {
444 opt.ExternalID = aws.String(sharedCfg.AssumeRole.ExternalID)
447 // Assume role with MFA
448 if len(sharedCfg.AssumeRole.MFASerial) > 0 {
449 opt.SerialNumber = aws.String(sharedCfg.AssumeRole.MFASerial)
450 opt.TokenProvider = sessOpts.AssumeRoleTokenProvider
454 } else if len(sharedCfg.Creds.AccessKeyID) > 0 {
455 cfg.Credentials = credentials.NewStaticCredentialsFromCreds(
459 // Fallback to default credentials provider, include mock errors
460 // for the credential chain so user can identify why credentials
461 // failed to be retrieved.
462 cfg.Credentials = credentials.NewCredentials(&credentials.ChainProvider{
463 VerboseErrors: aws.BoolValue(cfg.CredentialsChainVerboseErrors),
464 Providers: []credentials.Provider{
465 &credProviderError{Err: awserr.New("EnvAccessKeyNotFound", "failed to find credentials in the environment.", nil)},
466 &credProviderError{Err: awserr.New("SharedCredsLoad", fmt.Sprintf("failed to load profile, %s.", envCfg.Profile), nil)},
467 defaults.RemoteCredProvider(*cfg, handlers),
476 // AssumeRoleTokenProviderNotSetError is an error returned when creating a session when the
477 // MFAToken option is not set when shared config is configured load assume a
478 // role with an MFA token.
479 type AssumeRoleTokenProviderNotSetError struct{}
481 // Code is the short id of the error.
482 func (e AssumeRoleTokenProviderNotSetError) Code() string {
483 return "AssumeRoleTokenProviderNotSetError"
486 // Message is the description of the error
487 func (e AssumeRoleTokenProviderNotSetError) Message() string {
488 return fmt.Sprintf("assume role with MFA enabled, but AssumeRoleTokenProvider session option not set.")
491 // OrigErr is the underlying error that caused the failure.
492 func (e AssumeRoleTokenProviderNotSetError) OrigErr() error {
496 // Error satisfies the error interface.
497 func (e AssumeRoleTokenProviderNotSetError) Error() string {
498 return awserr.SprintError(e.Code(), e.Message(), "", nil)
501 type credProviderError struct {
505 var emptyCreds = credentials.Value{}
507 func (c credProviderError) Retrieve() (credentials.Value, error) {
508 return credentials.Value{}, c.Err
510 func (c credProviderError) IsExpired() bool {
514 func initHandlers(s *Session) {
515 // Add the Validate parameter handler if it is not disabled.
516 s.Handlers.Validate.Remove(corehandlers.ValidateParametersHandler)
517 if !aws.BoolValue(s.Config.DisableParamValidation) {
518 s.Handlers.Validate.PushBackNamed(corehandlers.ValidateParametersHandler)
522 // Copy creates and returns a copy of the current Session, coping the config
523 // and handlers. If any additional configs are provided they will be merged
524 // on top of the Session's copied config.
526 // // Create a copy of the current Session, configured for the us-west-2 region.
527 // sess.Copy(&aws.Config{Region: aws.String("us-west-2")})
528 func (s *Session) Copy(cfgs ...*aws.Config) *Session {
529 newSession := &Session{
530 Config: s.Config.Copy(cfgs...),
531 Handlers: s.Handlers.Copy(),
534 initHandlers(newSession)
539 // ClientConfig satisfies the client.ConfigProvider interface and is used to
540 // configure the service client instances. Passing the Session to the service
541 // client's constructor (New) will use this method to configure the client.
542 func (s *Session) ClientConfig(serviceName string, cfgs ...*aws.Config) client.Config {
543 // Backwards compatibility, the error will be eaten if user calls ClientConfig
544 // directly. All SDK services will use ClientconfigWithError.
545 cfg, _ := s.clientConfigWithErr(serviceName, cfgs...)
550 func (s *Session) clientConfigWithErr(serviceName string, cfgs ...*aws.Config) (client.Config, error) {
553 var resolved endpoints.ResolvedEndpoint
556 region := aws.StringValue(s.Config.Region)
558 if endpoint := aws.StringValue(s.Config.Endpoint); len(endpoint) != 0 {
559 resolved.URL = endpoints.AddScheme(endpoint, aws.BoolValue(s.Config.DisableSSL))
560 resolved.SigningRegion = region
562 resolved, err = s.Config.EndpointResolver.EndpointFor(
564 func(opt *endpoints.Options) {
565 opt.DisableSSL = aws.BoolValue(s.Config.DisableSSL)
566 opt.UseDualStack = aws.BoolValue(s.Config.UseDualStack)
568 // Support the condition where the service is modeled but its
569 // endpoint metadata is not available.
570 opt.ResolveUnknownService = true
575 return client.Config{
577 Handlers: s.Handlers,
578 Endpoint: resolved.URL,
579 SigningRegion: resolved.SigningRegion,
580 SigningName: resolved.SigningName,
584 // ClientConfigNoResolveEndpoint is the same as ClientConfig with the exception
585 // that the EndpointResolver will not be used to resolve the endpoint. The only
586 // endpoint set must come from the aws.Config.Endpoint field.
587 func (s *Session) ClientConfigNoResolveEndpoint(cfgs ...*aws.Config) client.Config {
590 var resolved endpoints.ResolvedEndpoint
592 region := aws.StringValue(s.Config.Region)
594 if ep := aws.StringValue(s.Config.Endpoint); len(ep) > 0 {
595 resolved.URL = endpoints.AddScheme(ep, aws.BoolValue(s.Config.DisableSSL))
596 resolved.SigningRegion = region
599 return client.Config{
601 Handlers: s.Handlers,
602 Endpoint: resolved.URL,
603 SigningRegion: resolved.SigningRegion,
604 SigningName: resolved.SigningName,