awsbase

package module
v1.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 9, 2022 License: MPL-2.0 Imports: 29 Imported by: 37

README

aws-sdk-go-base

An opinionated AWS Go SDK library for consistent authentication configuration between projects and additional helper functions. This library was originally started in HashiCorp Terraform, migrated with the Terraform AWS Provider during the Terraform 0.10 Core and Provider split, and now is offered as a separate library to allow easier dependency management in the Terraform ecosystem.

NOTE: This library is not currently designed or intended for usage outside the Terraform S3 Backend and the Terraform AWS Provider.

Requirements

Development

Testing this project can be done through Go standard library functionality or if Make is available:

$ go test -v ./...
# Optionally if Make is available; both run the same testing
$ make test

Code quality assurance uses golangci-lint:

$ golangci-lint run ./...
# Optionally if Make is available; both run the same linting
$ make lint

Release Process

  • Push a new vX.Y.Z tag to the repository
  • Close associated vX.Y.Z milestone
  • For Terraform AWS Provider: Renovate will automatically detect the update and submit a dependency pull request (usually within an hour)
  • For Terraform S3 Backend: Submit a new dependency pull request by running:
go get github.com/hashicorp/aws-sdk-go-base@vX.Y.Z
go mod tidy
go mod vendor

Documentation

Index

Constants

View Source
const (
	MockEc2MetadataAccessKey    = `Ec2MetadataAccessKey`
	MockEc2MetadataSecretKey    = `Ec2MetadataSecretKey`
	MockEc2MetadataSessionToken = `Ec2MetadataSessionToken`

	MockEcsCredentialsAccessKey    = `EcsCredentialsAccessKey`
	MockEcsCredentialsSecretKey    = `EcsCredentialsSecretKey`
	MockEcsCredentialsSessionToken = `EcsCredentialsSessionToken`

	MockEnvAccessKey    = `EnvAccessKey`
	MockEnvSecretKey    = `EnvSecretKey`
	MockEnvSessionToken = `EnvSessionToken`

	MockStaticAccessKey = `StaticAccessKey`
	MockStaticSecretKey = `StaticSecretKey`

	MockStsAssumeRoleAccessKey                               = `AssumeRoleAccessKey`
	MockStsAssumeRoleArn                                     = `arn:aws:iam::555555555555:role/AssumeRole`
	MockStsAssumeRoleExternalId                              = `AssumeRoleExternalId`
	MockStsAssumeRoleInvalidResponseBodyInvalidClientTokenId = `` /* 293-byte string literal not displayed */

	MockStsAssumeRolePolicy = `{
  "Version": "2012-10-17",
  "Statement": {
    "Effect": "Allow",
    "Action": "*",
    "Resource": "*",
  }
}`
	MockStsAssumeRolePolicyArn         = `arn:aws:iam::555555555555:policy/AssumeRolePolicy1`
	MockStsAssumeRoleSecretKey         = `AssumeRoleSecretKey`
	MockStsAssumeRoleSessionName       = `AssumeRoleSessionName`
	MockStsAssumeRoleSessionToken      = `AssumeRoleSessionToken`
	MockStsAssumeRoleTagKey            = `AssumeRoleTagKey`
	MockStsAssumeRoleTagValue          = `AssumeRoleTagValue`
	MockStsAssumeRoleTransitiveTagKey  = `AssumeRoleTagKey`
	MockStsAssumeRoleValidResponseBody = `` /* 677-byte string literal not displayed */

	MockStsAssumeRoleWithWebIdentityAccessKey         = `AssumeRoleWithWebIdentityAccessKey`
	MockStsAssumeRoleWithWebIdentityArn               = `arn:aws:iam::666666666666:role/WebIdentityToken`
	MockStsAssumeRoleWithWebIdentitySecretKey         = `AssumeRoleWithWebIdentitySecretKey`
	MockStsAssumeRoleWithWebIdentitySessionName       = `AssumeRoleWithWebIdentitySessionName`
	MockStsAssumeRoleWithWebIdentitySessionToken      = `AssumeRoleWithWebIdentitySessionToken`
	MockStsAssumeRoleWithWebIdentityValidResponseBody = `` /* 1046-byte string literal not displayed */

	MockStsGetCallerIdentityAccountID                       = `222222222222`
	MockStsGetCallerIdentityInvalidResponseBodyAccessDenied = `` /* 323-byte string literal not displayed */

	MockStsGetCallerIdentityPartition         = `aws`
	MockStsGetCallerIdentityValidResponseBody = `` /* 399-byte string literal not displayed */

	MockWebIdentityToken = `WebIdentityToken`
)
View Source
const (
	// AppendUserAgentEnvVar is a conventionally used environment variable
	// containing additional HTTP User-Agent information.
	// If present and its value is non-empty, it is directly appended to the
	// User-Agent header for HTTP requests.
	AppendUserAgentEnvVar = "TF_APPEND_USER_AGENT"
	// Maximum network retries.
	// We depend on the AWS Go SDK DefaultRetryer exponential backoff.
	// Ensure that if the AWS Config MaxRetries is set high (which it is by
	// default), that we only retry for a few seconds with typically
	// unrecoverable network errors, such as DNS lookup failures.
	MaxNetworkRetryCount = 9
)
View Source
const (
	// Default amount of time for EC2/ECS metadata client operations.
	// Keep this value low to prevent long delays in non-EC2/ECS environments.
	DefaultMetadataClientTimeout = 100 * time.Millisecond
)

Variables

View Source
var (
	MockEc2MetadataCredentials = awsCredentials.Value{
		AccessKeyID:     MockEc2MetadataAccessKey,
		ProviderName:    ec2rolecreds.ProviderName,
		SecretAccessKey: MockEc2MetadataSecretKey,
		SessionToken:    MockEc2MetadataSessionToken,
	}

	MockEcsCredentialsCredentials = awsCredentials.Value{
		AccessKeyID:     MockEcsCredentialsAccessKey,
		ProviderName:    endpointcreds.ProviderName,
		SecretAccessKey: MockEcsCredentialsSecretKey,
		SessionToken:    MockEcsCredentialsSessionToken,
	}

	MockEnvCredentials = awsCredentials.Value{
		AccessKeyID:     MockEnvAccessKey,
		ProviderName:    awsCredentials.EnvProviderName,
		SecretAccessKey: MockEnvSecretKey,
	}

	MockEnvCredentialsWithSessionToken = awsCredentials.Value{
		AccessKeyID:     MockEnvAccessKey,
		ProviderName:    awsCredentials.EnvProviderName,
		SecretAccessKey: MockEnvSecretKey,
		SessionToken:    MockEnvSessionToken,
	}

	MockStaticCredentials = awsCredentials.Value{
		AccessKeyID:     MockStaticAccessKey,
		ProviderName:    awsCredentials.StaticProviderName,
		SecretAccessKey: MockStaticSecretKey,
	}

	MockStsAssumeRoleCredentials = awsCredentials.Value{
		AccessKeyID:     MockStsAssumeRoleAccessKey,
		ProviderName:    stscreds.ProviderName,
		SecretAccessKey: MockStsAssumeRoleSecretKey,
		SessionToken:    MockStsAssumeRoleSessionToken,
	}
	MockStsAssumeRoleInvalidEndpointInvalidClientTokenId = &MockEndpoint{
		Request: &MockRequest{
			Body: url.Values{
				"Action":          []string{"AssumeRole"},
				"DurationSeconds": []string{"900"},
				"RoleArn":         []string{MockStsAssumeRoleArn},
				"RoleSessionName": []string{MockStsAssumeRoleSessionName},
				"Version":         []string{"2011-06-15"},
			}.Encode(),
			Method: http.MethodPost,
			Uri:    "/",
		},
		Response: &MockResponse{
			Body:        MockStsAssumeRoleInvalidResponseBodyInvalidClientTokenId,
			ContentType: "text/xml",
			StatusCode:  http.StatusForbidden,
		},
	}
	MockStsAssumeRoleValidEndpoint = &MockEndpoint{
		Request: &MockRequest{
			Body: url.Values{
				"Action":          []string{"AssumeRole"},
				"DurationSeconds": []string{"900"},
				"RoleArn":         []string{MockStsAssumeRoleArn},
				"RoleSessionName": []string{MockStsAssumeRoleSessionName},
				"Version":         []string{"2011-06-15"},
			}.Encode(),
			Method: http.MethodPost,
			Uri:    "/",
		},
		Response: &MockResponse{
			Body:        MockStsAssumeRoleValidResponseBody,
			ContentType: "text/xml",
			StatusCode:  http.StatusOK,
		},
	}

	MockStsAssumeRoleWithWebIdentityValidEndpoint = &MockEndpoint{
		Request: &MockRequest{
			Body: url.Values{
				"Action":           []string{"AssumeRoleWithWebIdentity"},
				"RoleArn":          []string{MockStsAssumeRoleWithWebIdentityArn},
				"RoleSessionName":  []string{MockStsAssumeRoleWithWebIdentitySessionName},
				"Version":          []string{"2011-06-15"},
				"WebIdentityToken": []string{MockWebIdentityToken},
			}.Encode(),
			Method: http.MethodPost,
			Uri:    "/",
		},
		Response: &MockResponse{
			Body:        MockStsAssumeRoleWithWebIdentityValidResponseBody,
			ContentType: "text/xml",
			StatusCode:  http.StatusOK,
		},
	}

	MockStsAssumeRoleWithWebIdentityCredentials = awsCredentials.Value{
		AccessKeyID:     MockStsAssumeRoleWithWebIdentityAccessKey,
		ProviderName:    stscreds.WebIdentityProviderName,
		SecretAccessKey: MockStsAssumeRoleWithWebIdentitySecretKey,
		SessionToken:    MockStsAssumeRoleWithWebIdentitySessionToken,
	}

	MockStsGetCallerIdentityInvalidEndpointAccessDenied = &MockEndpoint{
		Request: &MockRequest{
			Body: url.Values{
				"Action":  []string{"GetCallerIdentity"},
				"Version": []string{"2011-06-15"},
			}.Encode(),
			Method: http.MethodPost,
			Uri:    "/",
		},
		Response: &MockResponse{
			Body:        MockStsGetCallerIdentityInvalidResponseBodyAccessDenied,
			ContentType: "text/xml",
			StatusCode:  http.StatusForbidden,
		},
	}
	MockStsGetCallerIdentityValidEndpoint = &MockEndpoint{
		Request: &MockRequest{
			Body: url.Values{
				"Action":  []string{"GetCallerIdentity"},
				"Version": []string{"2011-06-15"},
			}.Encode(),
			Method: http.MethodPost,
			Uri:    "/",
		},
		Response: &MockResponse{
			Body:        MockStsGetCallerIdentityValidResponseBody,
			ContentType: "text/xml",
			StatusCode:  http.StatusOK,
		},
	}
)

Functions

func GetAccountIDAndPartition

func GetAccountIDAndPartition(iamconn *iam.IAM, stsconn *sts.STS, authProviderName string) (string, string, error)

GetAccountIDAndPartition gets the account ID and associated partition.

func GetAccountIDAndPartitionFromEC2Metadata

func GetAccountIDAndPartitionFromEC2Metadata() (string, string, error)

GetAccountIDAndPartitionFromEC2Metadata gets the account ID and associated partition from EC2 metadata.

func GetAccountIDAndPartitionFromIAMGetUser

func GetAccountIDAndPartitionFromIAMGetUser(iamconn *iam.IAM) (string, string, error)

GetAccountIDAndPartitionFromIAMGetUser gets the account ID and associated partition from IAM.

func GetAccountIDAndPartitionFromIAMListRoles

func GetAccountIDAndPartitionFromIAMListRoles(iamconn *iam.IAM) (string, string, error)

GetAccountIDAndPartitionFromIAMListRoles gets the account ID and associated partition from listing IAM roles.

func GetAccountIDAndPartitionFromSTSGetCallerIdentity

func GetAccountIDAndPartitionFromSTSGetCallerIdentity(stsconn *sts.STS) (string, string, error)

GetAccountIDAndPartitionFromSTSGetCallerIdentity gets the account ID and associated partition from STS caller identity.

func GetCredentials

func GetCredentials(c *Config) (*awsCredentials.Credentials, error)

GetCredentials gets credentials from environment, shared credentials file, environment AWS_SHARED_CREDENTIALS_FILE, the session (which may include a credential process), or ECS/EC2 metadata endpoints. GetCredentials also validates the credentials and the ability to assume a role or will return an error if unsuccessful.

func GetCredentialsFromSession added in v0.4.0

func GetCredentialsFromSession(c *Config) (*awsCredentials.Credentials, error)

GetCredentialsFromSession returns credentials derived from a session. A session uses the AWS SDK Go chain of providers so may use a provider (e.g., ProcessProvider) that is not part of the Terraform provider chain.

func GetMockedAwsApiSession

func GetMockedAwsApiSession(svcName string, endpoints []*MockEndpoint) (func(), *session.Session, error)

GetMockedAwsApiSession establishes an AWS session to a simulated AWS API server for a given service and route endpoints.

func GetSession

func GetSession(c *Config) (*session.Session, error)

GetSession attempts to return valid AWS Go SDK session.

func GetSessionOptions

func GetSessionOptions(c *Config) (*session.Options, error)

GetSessionOptions attempts to return valid AWS Go SDK session authentication options based on pre-existing credential provider, configured profile, or fallback to automatically a determined session via the AWS Go SDK.

func GetSessionWithAccountIDAndPartition

func GetSessionWithAccountIDAndPartition(c *Config) (*session.Session, string, string, error)

GetSessionWithAccountIDAndPartition attempts to return valid AWS Go SDK session along with account ID and partition information if available

func IsCannotAssumeRoleError added in v0.5.0

func IsCannotAssumeRoleError(err error) bool

IsCannotAssumeRoleError returns true if the error contains the CannotAssumeRoleError type.

func IsNoValidCredentialSourcesError added in v0.5.0

func IsNoValidCredentialSourcesError(err error) bool

IsNoValidCredentialSourcesError returns true if the error contains the NoValidCredentialSourcesError type.

func MockAwsApiServer added in v0.4.0

func MockAwsApiServer(svcName string, endpoints []*MockEndpoint) *httptest.Server

MockAwsApiServer establishes a httptest server to simulate behaviour of a real AWS API server

func ValidateAccountID added in v0.2.0

func ValidateAccountID(accountID string, allowedAccountIDs, forbiddenAccountIDs []string) error

ValidateAccountID checks if the given AWS account ID is specifically allowed or forbidden. The allowedAccountIDs can be used as a whitelist and forbiddenAccountIDs can be used as a blacklist.

func ValidateRegion added in v0.2.0

func ValidateRegion(region string) error

ValidateRegion checks if the given region is a valid AWS region.

Types

type CannotAssumeRoleError added in v0.5.0

type CannotAssumeRoleError struct {
	Config *Config
	Err    error
}

CannotAssumeRoleError occurs when AssumeRole cannot complete.

func (CannotAssumeRoleError) Error added in v0.5.0

func (e CannotAssumeRoleError) Error() string

func (CannotAssumeRoleError) Unwrap added in v0.5.0

func (e CannotAssumeRoleError) Unwrap() error

type Config

type Config struct {
	AccessKey                   string
	AssumeRoleARN               string
	AssumeRoleDurationSeconds   int
	AssumeRoleExternalID        string
	AssumeRolePolicy            string
	AssumeRolePolicyARNs        []string
	AssumeRoleSessionName       string
	AssumeRoleTags              map[string]string
	AssumeRoleTransitiveTagKeys []string
	CallerDocumentationURL      string
	CallerName                  string
	CredsFilename               string
	DebugLogging                bool
	IamEndpoint                 string
	Insecure                    bool
	HTTPProxy                   string
	MaxRetries                  int
	Profile                     string
	Region                      string
	SecretKey                   string
	SkipCredsValidation         bool
	SkipMetadataApiCheck        bool
	SkipRequestingAccountId     bool
	StsEndpoint                 string
	Token                       string
	UserAgentProducts           []*UserAgentProduct
}

func (*Config) EndpointResolver added in v0.5.0

func (c *Config) EndpointResolver() endpoints.Resolver

func (*Config) NewCannotAssumeRoleError added in v0.5.0

func (c *Config) NewCannotAssumeRoleError(err error) CannotAssumeRoleError

func (*Config) NewNoValidCredentialSourcesError added in v0.5.0

func (c *Config) NewNoValidCredentialSourcesError(err error) NoValidCredentialSourcesError

type DebugLogger

type DebugLogger struct{}

func (DebugLogger) Log

func (l DebugLogger) Log(args ...interface{})

type MetadataResponse added in v0.4.0

type MetadataResponse struct {
	Uri  string `json:"uri"`
	Body string `json:"body"`
}

MetadataResponse represents a metadata server response URI and body

type MockEndpoint

type MockEndpoint struct {
	Request  *MockRequest
	Response *MockResponse
}

MockEndpoint represents a basic request and response that can be used for creating simple httptest server routes.

func MockStsAssumeRoleValidEndpointWithOptions added in v0.6.0

func MockStsAssumeRoleValidEndpointWithOptions(options map[string]string) *MockEndpoint

MockStsAssumeRoleValidEndpointWithOptions returns a valid STS AssumeRole response with configurable request options.

type MockRequest

type MockRequest struct {
	Method string
	Uri    string
	Body   string
}

MockRequest represents a basic HTTP request

type MockResponse

type MockResponse struct {
	StatusCode  int
	Body        string
	ContentType string
}

MockResponse represents a basic HTTP response.

type NoValidCredentialSourcesError added in v0.5.0

type NoValidCredentialSourcesError struct {
	Config *Config
	Err    error
}

NoValidCredentialSourcesError occurs when all credential lookup methods have been exhausted without results.

func (NoValidCredentialSourcesError) Error added in v0.5.0

func (NoValidCredentialSourcesError) Unwrap added in v0.5.0

type UserAgentProduct

type UserAgentProduct struct {
	Extra   []string
	Name    string
	Version string
}

Directories

Path Synopsis
v2
awsv1shim Module

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL