stscreds

package
v1.44.185 Latest Latest
Warning

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

Go to latest
Published: Jan 23, 2023 License: Apache-2.0 Imports: 13 Imported by: 1,412

Documentation

Overview

Package stscreds are credential Providers to retrieve STS AWS credentials.

STS provides multiple ways to retrieve credentials which can be used when making future AWS service API operation calls.

The SDK will ensure that per instance of credentials.Credentials all requests to refresh the credentials will be synchronized. But, the SDK is unable to ensure synchronous usage of the AssumeRoleProvider if the value is shared between multiple Credentials, Sessions or service clients.

Assume Role

To assume an IAM role using STS with the SDK you can create a new Credentials with the SDKs's stscreds package.

// Initial credentials loaded from SDK's default credential chain. Such as
// the environment, shared credentials (~/.aws/credentials), or EC2 Instance
// Role. These credentials will be used to to make the STS Assume Role API.
sess := session.Must(session.NewSession())

// Create the credentials from AssumeRoleProvider to assume the role
// referenced by the "myRoleARN" ARN.
creds := stscreds.NewCredentials(sess, "myRoleArn")

// Create service client value configured for credentials
// from assumed role.
svc := s3.New(sess, &aws.Config{Credentials: creds})

Assume Role with static MFA Token

To assume an IAM role with a MFA token you can either specify a MFA token code directly or provide a function to prompt the user each time the credentials need to refresh the role's credentials. Specifying the TokenCode should be used for short lived operations that will not need to be refreshed, and when you do not want to have direct control over the user provides their MFA token.

With TokenCode the AssumeRoleProvider will be not be able to refresh the role's credentials.

// Create the credentials from AssumeRoleProvider to assume the role
// referenced by the "myRoleARN" ARN using the MFA token code provided.
creds := stscreds.NewCredentials(sess, "myRoleArn", func(p *stscreds.AssumeRoleProvider) {
	p.SerialNumber = aws.String("myTokenSerialNumber")
	p.TokenCode = aws.String("00000000")
})

// Create service client value configured for credentials
// from assumed role.
svc := s3.New(sess, &aws.Config{Credentials: creds})

Assume Role with MFA Token Provider

To assume an IAM role with MFA for longer running tasks where the credentials may need to be refreshed setting the TokenProvider field of AssumeRoleProvider will allow the credential provider to prompt for new MFA token code when the role's credentials need to be refreshed.

The StdinTokenProvider function is available to prompt on stdin to retrieve the MFA token code from the user. You can also implement custom prompts by satisfing the TokenProvider function signature.

Using StdinTokenProvider with multiple AssumeRoleProviders, or Credentials will have undesirable results as the StdinTokenProvider will not be synchronized. A single Credentials with an AssumeRoleProvider can be shared safely.

// Create the credentials from AssumeRoleProvider to assume the role
// referenced by the "myRoleARN" ARN. Prompting for MFA token from stdin.
creds := stscreds.NewCredentials(sess, "myRoleArn", func(p *stscreds.AssumeRoleProvider) {
	p.SerialNumber = aws.String("myTokenSerialNumber")
	p.TokenProvider = stscreds.StdinTokenProvider
})

// Create service client value configured for credentials
// from assumed role.
svc := s3.New(sess, &aws.Config{Credentials: creds})

Index

Constants

View Source
const (
	// ErrCodeWebIdentity will be used as an error code when constructing
	// a new error to be returned during session creation or retrieval.
	ErrCodeWebIdentity = "WebIdentityErr"

	// WebIdentityProviderName is the web identity provider name
	WebIdentityProviderName = "WebIdentityCredentials"
)
View Source
const ProviderName = "AssumeRoleProvider"

ProviderName provides a name of AssumeRole provider

Variables

View Source
var DefaultDuration = time.Duration(15) * time.Minute

DefaultDuration is the default amount of time in minutes that the credentials will be valid for.

Functions

func NewCredentials

func NewCredentials(c client.ConfigProvider, roleARN string, options ...func(*AssumeRoleProvider)) *credentials.Credentials

NewCredentials returns a pointer to a new Credentials value wrapping the AssumeRoleProvider. The credentials will expire every 15 minutes and the role will be named after a nanosecond timestamp of this operation. The Credentials value will attempt to refresh the credentials using the provider when Credentials.Get is called, if the cached credentials are expiring.

Takes a Config provider to create the STS client. The ConfigProvider is satisfied by the session.Session type.

It is safe to share the returned Credentials with multiple Sessions and service clients. All access to the credentials and refreshing them will be synchronized.

func NewCredentialsWithClient added in v0.10.0

func NewCredentialsWithClient(svc AssumeRoler, roleARN string, options ...func(*AssumeRoleProvider)) *credentials.Credentials

NewCredentialsWithClient returns a pointer to a new Credentials value wrapping the AssumeRoleProvider. The credentials will expire every 15 minutes and the role will be named after a nanosecond timestamp of this operation. The Credentials value will attempt to refresh the credentials using the provider when Credentials.Get is called, if the cached credentials are expiring.

Takes an AssumeRoler which can be satisfied by the STS client.

It is safe to share the returned Credentials with multiple Sessions and service clients. All access to the credentials and refreshing them will be synchronized.

func NewWebIdentityCredentials deprecated added in v1.21.0

func NewWebIdentityCredentials(c client.ConfigProvider, roleARN, roleSessionName, path string) *credentials.Credentials

NewWebIdentityCredentials will return a new set of credentials with a given configuration, role arn, and token file path.

Deprecated: Use NewWebIdentityRoleProviderWithOptions for flexible functional options, and wrap with credentials.NewCredentials helper.

func StdinTokenProvider added in v1.7.0

func StdinTokenProvider() (string, error)

StdinTokenProvider will prompt on stderr and read from stdin for a string value. An error is returned if reading from stdin fails.

Use this function to read MFA tokens from stdin. The function makes no attempt to make atomic prompts from stdin across multiple gorouties.

Using StdinTokenProvider with multiple AssumeRoleProviders, or Credentials will have undesirable results as the StdinTokenProvider will not be synchronized. A single Credentials with an AssumeRoleProvider can be shared safely

Will wait forever until something is provided on the stdin.

Types

type AssumeRoleProvider

type AssumeRoleProvider struct {
	credentials.Expiry

	// STS client to make assume role request with.
	Client AssumeRoler

	// Role to be assumed.
	RoleARN string

	// Session name, if you wish to reuse the credentials elsewhere.
	RoleSessionName string

	// Optional, you can pass tag key-value pairs to your session. These tags are called session tags.
	Tags []*sts.Tag

	// A list of keys for session tags that you want to set as transitive.
	// If you set a tag key as transitive, the corresponding key and value passes to subsequent sessions in a role chain.
	TransitiveTagKeys []*string

	// Expiry duration of the STS credentials. Defaults to 15 minutes if not set.
	Duration time.Duration

	// Optional ExternalID to pass along, defaults to nil if not set.
	ExternalID *string

	// The policy plain text must be 2048 bytes or shorter. However, an internal
	// conversion compresses it into a packed binary format with a separate limit.
	// The PackedPolicySize response element indicates by percentage how close to
	// the upper size limit the policy is, with 100% equaling the maximum allowed
	// size.
	Policy *string

	// The ARNs of IAM managed policies you want to use as managed session policies.
	// The policies must exist in the same account as the role.
	//
	// This parameter is optional. You can provide up to 10 managed policy ARNs.
	// However, the plain text that you use for both inline and managed session
	// policies can't exceed 2,048 characters.
	//
	// An AWS conversion compresses the passed session policies and session tags
	// into a packed binary format that has a separate limit. Your request can fail
	// for this limit even if your plain text meets the other requirements. The
	// PackedPolicySize response element indicates by percentage how close the policies
	// and tags for your request are to the upper size limit.
	//
	// Passing policies to this operation returns new temporary credentials. The
	// resulting session's permissions are the intersection of the role's identity-based
	// policy and the session policies. You can use the role's temporary credentials
	// in subsequent AWS API calls to access resources in the account that owns
	// the role. You cannot use session policies to grant more permissions than
	// those allowed by the identity-based policy of the role that is being assumed.
	// For more information, see Session Policies (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session)
	// in the IAM User Guide.
	PolicyArns []*sts.PolicyDescriptorType

	// The identification number of the MFA device that is associated with the user
	// who is making the AssumeRole call. Specify this value if the trust policy
	// of the role being assumed includes a condition that requires MFA authentication.
	// The value is either the serial number for a hardware device (such as GAHT12345678)
	// or an Amazon Resource Name (ARN) for a virtual device (such as arn:aws:iam::123456789012:mfa/user).
	SerialNumber *string

	// The value provided by the MFA device, if the trust policy of the role being
	// assumed requires MFA (that is, if the policy includes a condition that tests
	// for MFA). If the role being assumed requires MFA and if the TokenCode value
	// is missing or expired, the AssumeRole call returns an "access denied" error.
	//
	// If SerialNumber is set and neither TokenCode nor TokenProvider are also
	// set an error will be returned.
	TokenCode *string

	// Async method of providing MFA token code for assuming an IAM role with MFA.
	// The value returned by the function will be used as the TokenCode in the Retrieve
	// call. See StdinTokenProvider for a provider that prompts and reads from stdin.
	//
	// This token provider will be called when ever the assumed role's
	// credentials need to be refreshed when SerialNumber is also set and
	// TokenCode is not set.
	//
	// If both TokenCode and TokenProvider is set, TokenProvider will be used and
	// TokenCode is ignored.
	TokenProvider func() (string, error)

	// ExpiryWindow will allow the credentials to trigger refreshing prior to
	// the credentials actually expiring. This is beneficial so race conditions
	// with expiring credentials do not cause request to fail unexpectedly
	// due to ExpiredTokenException exceptions.
	//
	// So a ExpiryWindow of 10s would cause calls to IsExpired() to return true
	// 10 seconds before the credentials are actually expired.
	//
	// If ExpiryWindow is 0 or less it will be ignored.
	ExpiryWindow time.Duration

	// MaxJitterFrac reduces the effective Duration of each credential requested
	// by a random percentage between 0 and MaxJitterFraction. MaxJitterFrac must
	// have a value between 0 and 1. Any other value may lead to expected behavior.
	// With a MaxJitterFrac value of 0, default) will no jitter will be used.
	//
	// For example, with a Duration of 30m and a MaxJitterFrac of 0.1, the
	// AssumeRole call will be made with an arbitrary Duration between 27m and
	// 30m.
	//
	// MaxJitterFrac should not be negative.
	MaxJitterFrac float64
}

AssumeRoleProvider retrieves temporary credentials from the STS service, and keeps track of their expiration time.

This credential provider will be used by the SDKs default credential change when shared configuration is enabled, and the shared config or shared credentials file configure assume role. See Session docs for how to do this.

AssumeRoleProvider does not provide any synchronization and it is not safe to share this value across multiple Credentials, Sessions, or service clients without also sharing the same Credentials instance.

func (*AssumeRoleProvider) Retrieve

func (p *AssumeRoleProvider) Retrieve() (credentials.Value, error)

Retrieve generates a new set of temporary credentials using STS.

func (*AssumeRoleProvider) RetrieveWithContext added in v1.30.3

func (p *AssumeRoleProvider) RetrieveWithContext(ctx credentials.Context) (credentials.Value, error)

RetrieveWithContext generates a new set of temporary credentials using STS.

type AssumeRoler

type AssumeRoler interface {
	AssumeRole(input *sts.AssumeRoleInput) (*sts.AssumeRoleOutput, error)
}

AssumeRoler represents the minimal subset of the STS client API used by this provider.

type FetchTokenPath added in v1.30.12

type FetchTokenPath string

FetchTokenPath is a path to a WebIdentity token file

func (FetchTokenPath) FetchToken added in v1.30.12

func (f FetchTokenPath) FetchToken(ctx credentials.Context) ([]byte, error)

FetchToken returns a token by reading from the filesystem

type TokenFetcher added in v1.30.12

type TokenFetcher interface {
	FetchToken(credentials.Context) ([]byte, error)
}

TokenFetcher should return WebIdentity token bytes or an error

type WebIdentityRoleProvider added in v1.21.0

type WebIdentityRoleProvider struct {
	credentials.Expiry

	// The policy ARNs to use with the web identity assumed role.
	PolicyArns []*sts.PolicyDescriptorType

	// Duration the STS credentials will be valid for. Truncated to seconds.
	// If unset, the assumed role will use AssumeRoleWithWebIdentity's default
	// expiry duration. See
	// https://docs.aws.amazon.com/sdk-for-go/api/service/sts/#STS.AssumeRoleWithWebIdentity
	// for more information.
	Duration time.Duration

	// The amount of time the credentials will be refreshed before they expire.
	// This is useful refresh credentials before they expire to reduce risk of
	// using credentials as they expire. If unset, will default to no expiry
	// window.
	ExpiryWindow time.Duration
	// contains filtered or unexported fields
}

WebIdentityRoleProvider is used to retrieve credentials using an OIDC token.

func NewWebIdentityRoleProvider deprecated added in v1.21.0

func NewWebIdentityRoleProvider(svc stsiface.STSAPI, roleARN, roleSessionName, path string) *WebIdentityRoleProvider

NewWebIdentityRoleProvider will return a new WebIdentityRoleProvider with the provided stsiface.STSAPI

Deprecated: Use NewWebIdentityRoleProviderWithOptions for flexible functional options.

func NewWebIdentityRoleProviderWithOptions added in v1.42.27

func NewWebIdentityRoleProviderWithOptions(svc stsiface.STSAPI, roleARN, roleSessionName string, tokenFetcher TokenFetcher, optFns ...func(*WebIdentityRoleProvider)) *WebIdentityRoleProvider

NewWebIdentityRoleProviderWithOptions will return an initialize WebIdentityRoleProvider with the provided stsiface.STSAPI, role ARN, and a TokenFetcher. Additional options can be provided as functional options.

TokenFetcher is the implementation that will retrieve the JWT token from to assume the role with. Use the provided FetchTokenPath implementation to retrieve the JWT token using a file system path.

func NewWebIdentityRoleProviderWithToken deprecated added in v1.30.12

func NewWebIdentityRoleProviderWithToken(svc stsiface.STSAPI, roleARN, roleSessionName string, tokenFetcher TokenFetcher) *WebIdentityRoleProvider

NewWebIdentityRoleProviderWithToken will return a new WebIdentityRoleProvider with the provided stsiface.STSAPI and a TokenFetcher

Deprecated: Use NewWebIdentityRoleProviderWithOptions for flexible functional options.

func (*WebIdentityRoleProvider) Retrieve added in v1.21.0

Retrieve will attempt to assume a role from a token which is located at 'WebIdentityTokenFilePath' specified destination and if that is empty an error will be returned.

func (*WebIdentityRoleProvider) RetrieveWithContext added in v1.30.3

func (p *WebIdentityRoleProvider) RetrieveWithContext(ctx credentials.Context) (credentials.Value, error)

RetrieveWithContext will attempt to assume a role from a token which is located at 'WebIdentityTokenFilePath' specified destination and if that is empty an error will be returned.

Jump to

Keyboard shortcuts

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