static_provider.go raw

   1  package credentials
   2  
   3  import (
   4  	"context"
   5  
   6  	"github.com/aws/aws-sdk-go-v2/aws"
   7  )
   8  
   9  const (
  10  	// StaticCredentialsName provides a name of Static provider
  11  	StaticCredentialsName = "StaticCredentials"
  12  )
  13  
  14  // StaticCredentialsEmptyError is emitted when static credentials are empty.
  15  type StaticCredentialsEmptyError struct{}
  16  
  17  func (*StaticCredentialsEmptyError) Error() string {
  18  	return "static credentials are empty"
  19  }
  20  
  21  // A StaticCredentialsProvider is a set of credentials which are set, and will
  22  // never expire.
  23  type StaticCredentialsProvider struct {
  24  	Value aws.Credentials
  25  	// These values are for reporting purposes and are not meant to be set up directly
  26  	Source []aws.CredentialSource
  27  }
  28  
  29  // ProviderSources returns the credential chain that was used to construct this provider
  30  func (s StaticCredentialsProvider) ProviderSources() []aws.CredentialSource {
  31  	if s.Source == nil {
  32  		return []aws.CredentialSource{aws.CredentialSourceCode} // If no source has been set, assume this is used directly which means hardcoded creds
  33  	}
  34  	return s.Source
  35  }
  36  
  37  // NewStaticCredentialsProvider return a StaticCredentialsProvider initialized with the AWS
  38  // credentials passed in.
  39  func NewStaticCredentialsProvider(key, secret, session string) StaticCredentialsProvider {
  40  	return StaticCredentialsProvider{
  41  		Value: aws.Credentials{
  42  			AccessKeyID:     key,
  43  			SecretAccessKey: secret,
  44  			SessionToken:    session,
  45  		},
  46  	}
  47  }
  48  
  49  // Retrieve returns the credentials or error if the credentials are invalid.
  50  func (s StaticCredentialsProvider) Retrieve(_ context.Context) (aws.Credentials, error) {
  51  	v := s.Value
  52  	if v.AccessKeyID == "" || v.SecretAccessKey == "" {
  53  		return aws.Credentials{
  54  			Source: StaticCredentialsName,
  55  		}, &StaticCredentialsEmptyError{}
  56  	}
  57  
  58  	if len(v.Source) == 0 {
  59  		v.Source = StaticCredentialsName
  60  	}
  61  
  62  	return v, nil
  63  }
  64