static_provider.go 1.8 KB

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