Bump AWS libraries to latest

Signed-off-by: Davanum Srinivas <davanum@gmail.com>
This commit is contained in:
Davanum Srinivas 2022-10-16 11:38:08 -04:00
parent 2e1da6590e
commit af76f3b72a
No known key found for this signature in database
GPG Key ID: 80D83A796103BF59
106 changed files with 105743 additions and 24230 deletions

4
go.mod
View File

@ -20,7 +20,7 @@ require (
github.com/Microsoft/hcsshim v0.8.22 github.com/Microsoft/hcsshim v0.8.22
github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e
github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5
github.com/aws/aws-sdk-go v1.38.49 github.com/aws/aws-sdk-go v1.44.116
github.com/blang/semver/v4 v4.0.0 github.com/blang/semver/v4 v4.0.0
github.com/container-storage-interface/spec v1.6.0 github.com/container-storage-interface/spec v1.6.0
github.com/coredns/corefile-migration v1.0.17 github.com/coredns/corefile-migration v1.0.17
@ -277,7 +277,7 @@ replace (
github.com/armon/circbuf => github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e github.com/armon/circbuf => github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e
github.com/armon/go-socks5 => github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 github.com/armon/go-socks5 => github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5
github.com/asaskevich/govalidator => github.com/asaskevich/govalidator v0.0.0-20190424111038-f61b66f89f4a github.com/asaskevich/govalidator => github.com/asaskevich/govalidator v0.0.0-20190424111038-f61b66f89f4a
github.com/aws/aws-sdk-go => github.com/aws/aws-sdk-go v1.38.49 github.com/aws/aws-sdk-go => github.com/aws/aws-sdk-go v1.44.116
github.com/benbjohnson/clock => github.com/benbjohnson/clock v1.1.0 github.com/benbjohnson/clock => github.com/benbjohnson/clock v1.1.0
github.com/beorn7/perks => github.com/beorn7/perks v1.0.1 github.com/beorn7/perks => github.com/beorn7/perks v1.0.1
github.com/blang/semver => github.com/blang/semver v3.5.1+incompatible github.com/blang/semver => github.com/blang/semver v3.5.1+incompatible

4
go.sum
View File

@ -50,8 +50,8 @@ github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPd
github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs= github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs=
github.com/asaskevich/govalidator v0.0.0-20190424111038-f61b66f89f4a h1:idn718Q4B6AGu/h5Sxe66HYVdqdGu2l9Iebqhi/AEoA= github.com/asaskevich/govalidator v0.0.0-20190424111038-f61b66f89f4a h1:idn718Q4B6AGu/h5Sxe66HYVdqdGu2l9Iebqhi/AEoA=
github.com/asaskevich/govalidator v0.0.0-20190424111038-f61b66f89f4a/go.mod h1:lB+ZfQJz7igIIfQNfa7Ml4HSf2uFQQRzpGGRXenZAgY= github.com/asaskevich/govalidator v0.0.0-20190424111038-f61b66f89f4a/go.mod h1:lB+ZfQJz7igIIfQNfa7Ml4HSf2uFQQRzpGGRXenZAgY=
github.com/aws/aws-sdk-go v1.38.49 h1:E31vxjCe6a5I+mJLmUGaZobiWmg9KdWaud9IfceYeYQ= github.com/aws/aws-sdk-go v1.44.116 h1:NpLIhcvLWXJZAEwvPj3TDHeqp7DleK6ZUVYyW01WNHY=
github.com/aws/aws-sdk-go v1.38.49/go.mod h1:hcU610XS61/+aQV88ixoOzUoG7v3b31pl2zKMmprdro= github.com/aws/aws-sdk-go v1.44.116/go.mod h1:y4AeaBuwd2Lk+GepC1E9v0qOiTws0MIWAX4oIKwKHZo=
github.com/benbjohnson/clock v1.1.0 h1:Q92kusRqC1XV2MjkWETPvjJVqKetz1OzxZB7mHJLju8= github.com/benbjohnson/clock v1.1.0 h1:Q92kusRqC1XV2MjkWETPvjJVqKetz1OzxZB7mHJLju8=
github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA=
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=

View File

@ -12,7 +12,7 @@ require (
github.com/Azure/go-autorest/autorest/mocks v0.4.2 github.com/Azure/go-autorest/autorest/mocks v0.4.2
github.com/Azure/go-autorest/autorest/to v0.4.0 github.com/Azure/go-autorest/autorest/to v0.4.0
github.com/GoogleCloudPlatform/k8s-cloud-provider v1.18.1-0.20220218231025-f11817397a1b github.com/GoogleCloudPlatform/k8s-cloud-provider v1.18.1-0.20220218231025-f11817397a1b
github.com/aws/aws-sdk-go v1.38.49 github.com/aws/aws-sdk-go v1.44.116
github.com/golang/mock v1.6.0 github.com/golang/mock v1.6.0
github.com/google/go-cmp v0.5.9 github.com/google/go-cmp v0.5.9
github.com/rubiojr/go-vhd v0.0.0-20200706105327-02e210299021 github.com/rubiojr/go-vhd v0.0.0-20200706105327-02e210299021

View File

@ -77,8 +77,8 @@ github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRF
github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho= github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho=
github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY=
github.com/aws/aws-sdk-go v1.38.49 h1:E31vxjCe6a5I+mJLmUGaZobiWmg9KdWaud9IfceYeYQ= github.com/aws/aws-sdk-go v1.44.116 h1:NpLIhcvLWXJZAEwvPj3TDHeqp7DleK6ZUVYyW01WNHY=
github.com/aws/aws-sdk-go v1.38.49/go.mod h1:hcU610XS61/+aQV88ixoOzUoG7v3b31pl2zKMmprdro= github.com/aws/aws-sdk-go v1.44.116/go.mod h1:y4AeaBuwd2Lk+GepC1E9v0qOiTws0MIWAX4oIKwKHZo=
github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q=
github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8=
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=

View File

@ -50,9 +50,19 @@ func prettify(v reflect.Value, indent int, buf *bytes.Buffer) {
for i, n := range names { for i, n := range names {
val := v.FieldByName(n) val := v.FieldByName(n)
ft, ok := v.Type().FieldByName(n)
if !ok {
panic(fmt.Sprintf("expected to find field %v on type %v, but was not found", n, v.Type()))
}
buf.WriteString(strings.Repeat(" ", indent+2)) buf.WriteString(strings.Repeat(" ", indent+2))
buf.WriteString(n + ": ") buf.WriteString(n + ": ")
prettify(val, indent+2, buf)
if tag := ft.Tag.Get("sensitive"); tag == "true" {
buf.WriteString("<sensitive>")
} else {
prettify(val, indent+2, buf)
}
if i < len(names)-1 { if i < len(names)-1 {
buf.WriteString(",\n") buf.WriteString(",\n")

View File

@ -8,6 +8,8 @@ import (
) )
// StringValue returns the string representation of a value. // StringValue returns the string representation of a value.
//
// Deprecated: Use Prettify instead.
func StringValue(i interface{}) string { func StringValue(i interface{}) string {
var buf bytes.Buffer var buf bytes.Buffer
stringValue(reflect.ValueOf(i), 0, &buf) stringValue(reflect.ValueOf(i), 0, &buf)

View File

@ -10,12 +10,13 @@ import (
// A Config provides configuration to a service client instance. // A Config provides configuration to a service client instance.
type Config struct { type Config struct {
Config *aws.Config Config *aws.Config
Handlers request.Handlers Handlers request.Handlers
PartitionID string PartitionID string
Endpoint string Endpoint string
SigningRegion string SigningRegion string
SigningName string SigningName string
ResolvedRegion string
// States that the signing name did not come from a modeled source but // States that the signing name did not come from a modeled source but
// was derived based on other data. Used by service client constructors // was derived based on other data. Used by service client constructors

View File

@ -53,7 +53,7 @@ var LogHTTPRequestHandler = request.NamedHandler{
} }
func logRequest(r *request.Request) { func logRequest(r *request.Request) {
if !r.Config.LogLevel.AtLeast(aws.LogDebug) { if !r.Config.LogLevel.AtLeast(aws.LogDebug) || r.Config.Logger == nil {
return return
} }
@ -94,6 +94,10 @@ var LogHTTPRequestHeaderHandler = request.NamedHandler{
} }
func logRequestHeader(r *request.Request) { func logRequestHeader(r *request.Request) {
if !r.Config.LogLevel.AtLeast(aws.LogDebug) || r.Config.Logger == nil {
return
}
b, err := httputil.DumpRequestOut(r.HTTPRequest, false) b, err := httputil.DumpRequestOut(r.HTTPRequest, false)
if err != nil { if err != nil {
r.Config.Logger.Log(fmt.Sprintf(logReqErrMsg, r.Config.Logger.Log(fmt.Sprintf(logReqErrMsg,
@ -124,7 +128,7 @@ var LogHTTPResponseHandler = request.NamedHandler{
} }
func logResponse(r *request.Request) { func logResponse(r *request.Request) {
if !r.Config.LogLevel.AtLeast(aws.LogDebug) { if !r.Config.LogLevel.AtLeast(aws.LogDebug) || r.Config.Logger == nil {
return return
} }
@ -186,7 +190,7 @@ var LogHTTPResponseHeaderHandler = request.NamedHandler{
} }
func logResponseHeader(r *request.Request) { func logResponseHeader(r *request.Request) {
if r.Config.Logger == nil { if !r.Config.LogLevel.AtLeast(aws.LogDebug) || r.Config.Logger == nil {
return return
} }

View File

@ -2,13 +2,14 @@ package metadata
// ClientInfo wraps immutable data from the client.Client structure. // ClientInfo wraps immutable data from the client.Client structure.
type ClientInfo struct { type ClientInfo struct {
ServiceName string ServiceName string
ServiceID string ServiceID string
APIVersion string APIVersion string
PartitionID string PartitionID string
Endpoint string Endpoint string
SigningName string SigningName string
SigningRegion string SigningRegion string
JSONVersion string JSONVersion string
TargetPrefix string TargetPrefix string
ResolvedRegion string
} }

View File

@ -170,6 +170,9 @@ type Config struct {
// //
// For example S3's X-Amz-Meta prefixed header will be unmarshaled to lower case // For example S3's X-Amz-Meta prefixed header will be unmarshaled to lower case
// Metadata member's map keys. The value of the header in the map is unaffected. // Metadata member's map keys. The value of the header in the map is unaffected.
//
// The AWS SDK for Go v2, uses lower case header maps by default. The v1
// SDK provides this opt-in for this option, for backwards compatibility.
LowerCaseHeaderMaps *bool LowerCaseHeaderMaps *bool
// Set this to `true` to disable the EC2Metadata client from overriding the // Set this to `true` to disable the EC2Metadata client from overriding the
@ -208,8 +211,19 @@ type Config struct {
// svc := s3.New(sess, &aws.Config{ // svc := s3.New(sess, &aws.Config{
// UseDualStack: aws.Bool(true), // UseDualStack: aws.Bool(true),
// }) // })
//
// Deprecated: This option will continue to function for S3 and S3 Control for backwards compatibility.
// UseDualStackEndpoint should be used to enable usage of a service's dual-stack endpoint for all service clients
// moving forward. For S3 and S3 Control, when UseDualStackEndpoint is set to a non-zero value it takes higher
// precedence then this option.
UseDualStack *bool UseDualStack *bool
// Sets the resolver to resolve a dual-stack endpoint for the service.
UseDualStackEndpoint endpoints.DualStackEndpointState
// UseFIPSEndpoint specifies the resolver must resolve a FIPS endpoint.
UseFIPSEndpoint endpoints.FIPSEndpointState
// SleepDelay is an override for the func the SDK will call when sleeping // SleepDelay is an override for the func the SDK will call when sleeping
// during the lifecycle of a request. Specifically this will be used for // during the lifecycle of a request. Specifically this will be used for
// request delays. This value should only be used for testing. To adjust // request delays. This value should only be used for testing. To adjust
@ -554,6 +568,10 @@ func mergeInConfig(dst *Config, other *Config) {
dst.UseDualStack = other.UseDualStack dst.UseDualStack = other.UseDualStack
} }
if other.UseDualStackEndpoint != endpoints.DualStackEndpointStateUnset {
dst.UseDualStackEndpoint = other.UseDualStackEndpoint
}
if other.EC2MetadataDisableTimeoutOverride != nil { if other.EC2MetadataDisableTimeoutOverride != nil {
dst.EC2MetadataDisableTimeoutOverride = other.EC2MetadataDisableTimeoutOverride dst.EC2MetadataDisableTimeoutOverride = other.EC2MetadataDisableTimeoutOverride
} }
@ -589,6 +607,14 @@ func mergeInConfig(dst *Config, other *Config) {
if other.LowerCaseHeaderMaps != nil { if other.LowerCaseHeaderMaps != nil {
dst.LowerCaseHeaderMaps = other.LowerCaseHeaderMaps dst.LowerCaseHeaderMaps = other.LowerCaseHeaderMaps
} }
if other.UseDualStackEndpoint != endpoints.DualStackEndpointStateUnset {
dst.UseDualStackEndpoint = other.UseDualStackEndpoint
}
if other.UseFIPSEndpoint != endpoints.FIPSEndpointStateUnset {
dst.UseFIPSEndpoint = other.UseFIPSEndpoint
}
} }
// Copy will return a shallow copy of the Config object. If any additional // Copy will return a shallow copy of the Config object. If any additional

View File

@ -1,3 +1,4 @@
//go:build !go1.9
// +build !go1.9 // +build !go1.9
package aws package aws

View File

@ -1,3 +1,4 @@
//go:build go1.9
// +build go1.9 // +build go1.9
package aws package aws

View File

@ -1,3 +1,4 @@
//go:build !go1.7
// +build !go1.7 // +build !go1.7
package aws package aws

View File

@ -1,3 +1,4 @@
//go:build go1.7
// +build go1.7 // +build go1.7
package aws package aws

View File

@ -1,3 +1,4 @@
//go:build !go1.7
// +build !go1.7 // +build !go1.7
package credentials package credentials

View File

@ -1,3 +1,4 @@
//go:build go1.7
// +build go1.7 // +build go1.7
package credentials package credentials

View File

@ -1,3 +1,4 @@
//go:build !go1.9
// +build !go1.9 // +build !go1.9
package credentials package credentials

View File

@ -1,3 +1,4 @@
//go:build go1.9
// +build go1.9 // +build go1.9
package credentials package credentials

View File

@ -1,3 +1,4 @@
//go:build !windows
// +build !windows // +build !windows
package ssocreds package ssocreds

View File

@ -28,7 +28,7 @@ const (
// compare test values. // compare test values.
var now = time.Now var now = time.Now
// TokenFetcher shuold return WebIdentity token bytes or an error // TokenFetcher should return WebIdentity token bytes or an error
type TokenFetcher interface { type TokenFetcher interface {
FetchToken(credentials.Context) ([]byte, error) FetchToken(credentials.Context) ([]byte, error)
} }
@ -50,6 +50,8 @@ func (f FetchTokenPath) FetchToken(ctx credentials.Context) ([]byte, error) {
// an OIDC token. // an OIDC token.
type WebIdentityRoleProvider struct { type WebIdentityRoleProvider struct {
credentials.Expiry credentials.Expiry
// The policy ARNs to use with the web identity assumed role.
PolicyArns []*sts.PolicyDescriptorType PolicyArns []*sts.PolicyDescriptorType
// Duration the STS credentials will be valid for. Truncated to seconds. // Duration the STS credentials will be valid for. Truncated to seconds.
@ -74,6 +76,9 @@ type WebIdentityRoleProvider struct {
// NewWebIdentityCredentials will return a new set of credentials with a given // NewWebIdentityCredentials will return a new set of credentials with a given
// configuration, role arn, and token file path. // configuration, role arn, and token file path.
//
// Deprecated: Use NewWebIdentityRoleProviderWithOptions for flexible
// functional options, and wrap with credentials.NewCredentials helper.
func NewWebIdentityCredentials(c client.ConfigProvider, roleARN, roleSessionName, path string) *credentials.Credentials { func NewWebIdentityCredentials(c client.ConfigProvider, roleARN, roleSessionName, path string) *credentials.Credentials {
svc := sts.New(c) svc := sts.New(c)
p := NewWebIdentityRoleProvider(svc, roleARN, roleSessionName, path) p := NewWebIdentityRoleProvider(svc, roleARN, roleSessionName, path)
@ -82,19 +87,42 @@ func NewWebIdentityCredentials(c client.ConfigProvider, roleARN, roleSessionName
// NewWebIdentityRoleProvider will return a new WebIdentityRoleProvider with the // NewWebIdentityRoleProvider will return a new WebIdentityRoleProvider with the
// provided stsiface.STSAPI // provided stsiface.STSAPI
//
// Deprecated: Use NewWebIdentityRoleProviderWithOptions for flexible
// functional options.
func NewWebIdentityRoleProvider(svc stsiface.STSAPI, roleARN, roleSessionName, path string) *WebIdentityRoleProvider { func NewWebIdentityRoleProvider(svc stsiface.STSAPI, roleARN, roleSessionName, path string) *WebIdentityRoleProvider {
return NewWebIdentityRoleProviderWithToken(svc, roleARN, roleSessionName, FetchTokenPath(path)) return NewWebIdentityRoleProviderWithOptions(svc, roleARN, roleSessionName, FetchTokenPath(path))
} }
// NewWebIdentityRoleProviderWithToken will return a new WebIdentityRoleProvider with the // NewWebIdentityRoleProviderWithToken will return a new WebIdentityRoleProvider with the
// provided stsiface.STSAPI and a TokenFetcher // provided stsiface.STSAPI and a TokenFetcher
//
// Deprecated: Use NewWebIdentityRoleProviderWithOptions for flexible
// functional options.
func NewWebIdentityRoleProviderWithToken(svc stsiface.STSAPI, roleARN, roleSessionName string, tokenFetcher TokenFetcher) *WebIdentityRoleProvider { func NewWebIdentityRoleProviderWithToken(svc stsiface.STSAPI, roleARN, roleSessionName string, tokenFetcher TokenFetcher) *WebIdentityRoleProvider {
return &WebIdentityRoleProvider{ return NewWebIdentityRoleProviderWithOptions(svc, roleARN, roleSessionName, tokenFetcher)
}
// 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 NewWebIdentityRoleProviderWithOptions(svc stsiface.STSAPI, roleARN, roleSessionName string, tokenFetcher TokenFetcher, optFns ...func(*WebIdentityRoleProvider)) *WebIdentityRoleProvider {
p := WebIdentityRoleProvider{
client: svc, client: svc,
tokenFetcher: tokenFetcher, tokenFetcher: tokenFetcher,
roleARN: roleARN, roleARN: roleARN,
roleSessionName: roleSessionName, roleSessionName: roleSessionName,
} }
for _, fn := range optFns {
fn(&p)
}
return &p
} }
// Retrieve will attempt to assume a role from a token which is located at // Retrieve will attempt to assume a role from a token which is located at
@ -104,9 +132,9 @@ func (p *WebIdentityRoleProvider) Retrieve() (credentials.Value, error) {
return p.RetrieveWithContext(aws.BackgroundContext()) return p.RetrieveWithContext(aws.BackgroundContext())
} }
// RetrieveWithContext will attempt to assume a role from a token which is located at // RetrieveWithContext will attempt to assume a role from a token which is
// 'WebIdentityTokenFilePath' specified destination and if that is empty an // located at 'WebIdentityTokenFilePath' specified destination and if that is
// error will be returned. // empty an error will be returned.
func (p *WebIdentityRoleProvider) RetrieveWithContext(ctx credentials.Context) (credentials.Value, error) { func (p *WebIdentityRoleProvider) RetrieveWithContext(ctx credentials.Context) (credentials.Value, error) {
b, err := p.tokenFetcher.FetchToken(ctx) b, err := p.tokenFetcher.FetchToken(ctx)
if err != nil { if err != nil {

View File

@ -13,7 +13,6 @@ package ec2metadata
import ( import (
"bytes" "bytes"
"errors"
"io" "io"
"net/http" "net/http"
"net/url" "net/url"
@ -234,7 +233,8 @@ func unmarshalError(r *request.Request) {
// Response body format is not consistent between metadata endpoints. // Response body format is not consistent between metadata endpoints.
// Grab the error message as a string and include that as the source error // Grab the error message as a string and include that as the source error
r.Error = awserr.NewRequestFailure(awserr.New("EC2MetadataError", "failed to make EC2Metadata request", errors.New(b.String())), r.Error = awserr.NewRequestFailure(
awserr.New("EC2MetadataError", "failed to make EC2Metadata request\n"+b.String(), nil),
r.HTTPResponse.StatusCode, r.RequestID) r.HTTPResponse.StatusCode, r.RequestID)
} }

View File

@ -31,12 +31,12 @@ func (d *DecodeModelOptions) Set(optFns ...func(*DecodeModelOptions)) {
// allow you to get a list of the partitions in the order the endpoints // allow you to get a list of the partitions in the order the endpoints
// will be resolved in. // will be resolved in.
// //
// resolver, err := endpoints.DecodeModel(reader) // resolver, err := endpoints.DecodeModel(reader)
// //
// partitions := resolver.(endpoints.EnumPartitions).Partitions() // partitions := resolver.(endpoints.EnumPartitions).Partitions()
// for _, p := range partitions { // for _, p := range partitions {
// // ... inspect partitions // // ... inspect partitions
// } // }
func DecodeModel(r io.Reader, optFns ...func(*DecodeModelOptions)) (Resolver, error) { func DecodeModel(r io.Reader, optFns ...func(*DecodeModelOptions)) (Resolver, error) {
var opts DecodeModelOptions var opts DecodeModelOptions
opts.Set(optFns...) opts.Set(optFns...)
@ -81,8 +81,6 @@ func decodeV3Endpoints(modelDef modelDefinition, opts DecodeModelOptions) (Resol
// Customization // Customization
for i := 0; i < len(ps); i++ { for i := 0; i < len(ps); i++ {
p := &ps[i] p := &ps[i]
custAddEC2Metadata(p)
custAddS3DualStack(p)
custRegionalS3(p) custRegionalS3(p)
custRmIotDataService(p) custRmIotDataService(p)
custFixAppAutoscalingChina(p) custFixAppAutoscalingChina(p)
@ -92,15 +90,6 @@ func decodeV3Endpoints(modelDef modelDefinition, opts DecodeModelOptions) (Resol
return ps, nil return ps, nil
} }
func custAddS3DualStack(p *partition) {
if !(p.ID == "aws" || p.ID == "aws-cn" || p.ID == "aws-us-gov") {
return
}
custAddDualstack(p, "s3")
custAddDualstack(p, "s3-control")
}
func custRegionalS3(p *partition) { func custRegionalS3(p *partition) {
if p.ID != "aws" { if p.ID != "aws" {
return return
@ -111,48 +100,28 @@ func custRegionalS3(p *partition) {
return return
} }
const awsGlobal = "aws-global"
const usEast1 = "us-east-1"
// If global endpoint already exists no customization needed. // If global endpoint already exists no customization needed.
if _, ok := service.Endpoints["aws-global"]; ok { if _, ok := service.Endpoints[endpointKey{Region: awsGlobal}]; ok {
return return
} }
service.PartitionEndpoint = "aws-global" service.PartitionEndpoint = awsGlobal
service.Endpoints["us-east-1"] = endpoint{} if _, ok := service.Endpoints[endpointKey{Region: usEast1}]; !ok {
service.Endpoints["aws-global"] = endpoint{ service.Endpoints[endpointKey{Region: usEast1}] = endpoint{}
}
service.Endpoints[endpointKey{Region: awsGlobal}] = endpoint{
Hostname: "s3.amazonaws.com", Hostname: "s3.amazonaws.com",
CredentialScope: credentialScope{ CredentialScope: credentialScope{
Region: "us-east-1", Region: usEast1,
}, },
} }
p.Services["s3"] = service p.Services["s3"] = service
} }
func custAddDualstack(p *partition, svcName string) {
s, ok := p.Services[svcName]
if !ok {
return
}
s.Defaults.HasDualStack = boxedTrue
s.Defaults.DualStackHostname = "{service}.dualstack.{region}.{dnsSuffix}"
p.Services[svcName] = s
}
func custAddEC2Metadata(p *partition) {
p.Services["ec2metadata"] = service{
IsRegionalized: boxedFalse,
PartitionEndpoint: "aws-global",
Endpoints: endpoints{
"aws-global": endpoint{
Hostname: "169.254.169.254/latest",
Protocols: []string{"http"},
},
},
}
}
func custRmIotDataService(p *partition) { func custRmIotDataService(p *partition) {
delete(p.Services, "data.iot") delete(p.Services, "data.iot")
} }
@ -169,12 +138,13 @@ func custFixAppAutoscalingChina(p *partition) {
} }
const expectHostname = `autoscaling.{region}.amazonaws.com` const expectHostname = `autoscaling.{region}.amazonaws.com`
if e, a := s.Defaults.Hostname, expectHostname; e != a { serviceDefault := s.Defaults[defaultKey{}]
if e, a := expectHostname, serviceDefault.Hostname; e != a {
fmt.Printf("custFixAppAutoscalingChina: ignoring customization, expected %s, got %s\n", e, a) fmt.Printf("custFixAppAutoscalingChina: ignoring customization, expected %s, got %s\n", e, a)
return return
} }
serviceDefault.Hostname = expectHostname + ".cn"
s.Defaults.Hostname = expectHostname + ".cn" s.Defaults[defaultKey{}] = serviceDefault
p.Services[serviceName] = s p.Services[serviceName] = s
} }
@ -189,18 +159,25 @@ func custFixAppAutoscalingUsGov(p *partition) {
return return
} }
if a := s.Defaults.CredentialScope.Service; a != "" { serviceDefault := s.Defaults[defaultKey{}]
if a := serviceDefault.CredentialScope.Service; a != "" {
fmt.Printf("custFixAppAutoscalingUsGov: ignoring customization, expected empty credential scope service, got %s\n", a) fmt.Printf("custFixAppAutoscalingUsGov: ignoring customization, expected empty credential scope service, got %s\n", a)
return return
} }
if a := s.Defaults.Hostname; a != "" { if a := serviceDefault.Hostname; a != "" {
fmt.Printf("custFixAppAutoscalingUsGov: ignoring customization, expected empty hostname, got %s\n", a) fmt.Printf("custFixAppAutoscalingUsGov: ignoring customization, expected empty hostname, got %s\n", a)
return return
} }
s.Defaults.CredentialScope.Service = "application-autoscaling" serviceDefault.CredentialScope.Service = "application-autoscaling"
s.Defaults.Hostname = "autoscaling.{region}.amazonaws.com" serviceDefault.Hostname = "autoscaling.{region}.amazonaws.com"
if s.Defaults == nil {
s.Defaults = make(endpointDefaults)
}
s.Defaults[defaultKey{}] = serviceDefault
p.Services[serviceName] = s p.Services[serviceName] = s
} }

File diff suppressed because it is too large Load Diff

View File

@ -9,7 +9,7 @@
// AWS GovCloud (US) (aws-us-gov). // AWS GovCloud (US) (aws-us-gov).
// . // .
// //
// Enumerating Regions and Endpoint Metadata // # Enumerating Regions and Endpoint Metadata
// //
// Casting the Resolver returned by DefaultResolver to a EnumPartitions interface // Casting the Resolver returned by DefaultResolver to a EnumPartitions interface
// will allow you to get access to the list of underlying Partitions with the // will allow you to get access to the list of underlying Partitions with the
@ -17,22 +17,22 @@
// resolving to a single partition, or enumerate regions, services, and endpoints // resolving to a single partition, or enumerate regions, services, and endpoints
// in the partition. // in the partition.
// //
// resolver := endpoints.DefaultResolver() // resolver := endpoints.DefaultResolver()
// partitions := resolver.(endpoints.EnumPartitions).Partitions() // partitions := resolver.(endpoints.EnumPartitions).Partitions()
// //
// for _, p := range partitions { // for _, p := range partitions {
// fmt.Println("Regions for", p.ID()) // fmt.Println("Regions for", p.ID())
// for id, _ := range p.Regions() { // for id, _ := range p.Regions() {
// fmt.Println("*", id) // fmt.Println("*", id)
// } // }
// //
// fmt.Println("Services for", p.ID()) // fmt.Println("Services for", p.ID())
// for id, _ := range p.Services() { // for id, _ := range p.Services() {
// fmt.Println("*", id) // fmt.Println("*", id)
// } // }
// } // }
// //
// Using Custom Endpoints // # Using Custom Endpoints
// //
// The endpoints package also gives you the ability to use your own logic how // The endpoints package also gives you the ability to use your own logic how
// endpoints are resolved. This is a great way to define a custom endpoint // endpoints are resolved. This is a great way to define a custom endpoint
@ -47,20 +47,19 @@
// of Resolver.EndpointFor, converting it to a type that satisfies the // of Resolver.EndpointFor, converting it to a type that satisfies the
// Resolver interface. // Resolver interface.
// //
// myCustomResolver := func(service, region string, optFns ...func(*endpoints.Options)) (endpoints.ResolvedEndpoint, error) {
// if service == endpoints.S3ServiceID {
// return endpoints.ResolvedEndpoint{
// URL: "s3.custom.endpoint.com",
// SigningRegion: "custom-signing-region",
// }, nil
// }
// //
// myCustomResolver := func(service, region string, optFns ...func(*endpoints.Options)) (endpoints.ResolvedEndpoint, error) { // return endpoints.DefaultResolver().EndpointFor(service, region, optFns...)
// if service == endpoints.S3ServiceID { // }
// return endpoints.ResolvedEndpoint{
// URL: "s3.custom.endpoint.com",
// SigningRegion: "custom-signing-region",
// }, nil
// }
// //
// return endpoints.DefaultResolver().EndpointFor(service, region, optFns...) // sess := session.Must(session.NewSession(&aws.Config{
// } // Region: aws.String("us-west-2"),
// // EndpointResolver: endpoints.ResolverFunc(myCustomResolver),
// sess := session.Must(session.NewSession(&aws.Config{ // }))
// Region: aws.String("us-west-2"),
// EndpointResolver: endpoints.ResolverFunc(myCustomResolver),
// }))
package endpoints package endpoints

View File

@ -8,6 +8,41 @@ import (
"github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/awserr"
) )
// A Logger is a minimalistic interface for the SDK to log messages to.
type Logger interface {
Log(...interface{})
}
// DualStackEndpointState is a constant to describe the dual-stack endpoint resolution
// behavior.
type DualStackEndpointState uint
const (
// DualStackEndpointStateUnset is the default value behavior for dual-stack endpoint
// resolution.
DualStackEndpointStateUnset DualStackEndpointState = iota
// DualStackEndpointStateEnabled enable dual-stack endpoint resolution for endpoints.
DualStackEndpointStateEnabled
// DualStackEndpointStateDisabled disables dual-stack endpoint resolution for endpoints.
DualStackEndpointStateDisabled
)
// FIPSEndpointState is a constant to describe the FIPS endpoint resolution behavior.
type FIPSEndpointState uint
const (
// FIPSEndpointStateUnset is the default value behavior for FIPS endpoint resolution.
FIPSEndpointStateUnset FIPSEndpointState = iota
// FIPSEndpointStateEnabled enables FIPS endpoint resolution for service endpoints.
FIPSEndpointStateEnabled
// FIPSEndpointStateDisabled disables FIPS endpoint resolution for endpoints.
FIPSEndpointStateDisabled
)
// Options provide the configuration needed to direct how the // Options provide the configuration needed to direct how the
// endpoints will be resolved. // endpoints will be resolved.
type Options struct { type Options struct {
@ -21,8 +56,19 @@ type Options struct {
// be returned. This endpoint may not be valid. If StrictMatching is // be returned. This endpoint may not be valid. If StrictMatching is
// enabled only services that are known to support dualstack will return // enabled only services that are known to support dualstack will return
// dualstack endpoints. // dualstack endpoints.
//
// Deprecated: This option will continue to function for S3 and S3 Control for backwards compatibility.
// UseDualStackEndpoint should be used to enable usage of a service's dual-stack endpoint for all service clients
// moving forward. For S3 and S3 Control, when UseDualStackEndpoint is set to a non-zero value it takes higher
// precedence then this option.
UseDualStack bool UseDualStack bool
// Sets the resolver to resolve a dual-stack endpoint for the service.
UseDualStackEndpoint DualStackEndpointState
// UseFIPSEndpoint specifies the resolver must resolve a FIPS endpoint.
UseFIPSEndpoint FIPSEndpointState
// Enables strict matching of services and regions resolved endpoints. // Enables strict matching of services and regions resolved endpoints.
// If the partition doesn't enumerate the exact service and region an // If the partition doesn't enumerate the exact service and region an
// error will be returned. This option will prevent returning endpoints // error will be returned. This option will prevent returning endpoints
@ -48,11 +94,65 @@ type Options struct {
// This option is ignored if StrictMatching is enabled. // This option is ignored if StrictMatching is enabled.
ResolveUnknownService bool ResolveUnknownService bool
// Specifies the EC2 Instance Metadata Service default endpoint selection mode (IPv4 or IPv6)
EC2MetadataEndpointMode EC2IMDSEndpointModeState
// STS Regional Endpoint flag helps with resolving the STS endpoint // STS Regional Endpoint flag helps with resolving the STS endpoint
STSRegionalEndpoint STSRegionalEndpoint STSRegionalEndpoint STSRegionalEndpoint
// S3 Regional Endpoint flag helps with resolving the S3 endpoint // S3 Regional Endpoint flag helps with resolving the S3 endpoint
S3UsEast1RegionalEndpoint S3UsEast1RegionalEndpoint S3UsEast1RegionalEndpoint S3UsEast1RegionalEndpoint
// ResolvedRegion is the resolved region string. If provided (non-zero length) it takes priority
// over the region name passed to the ResolveEndpoint call.
ResolvedRegion string
// Logger is the logger that will be used to log messages.
Logger Logger
// Determines whether logging of deprecated endpoints usage is enabled.
LogDeprecated bool
}
func (o Options) getEndpointVariant(service string) (v endpointVariant) {
const s3 = "s3"
const s3Control = "s3-control"
if (o.UseDualStackEndpoint == DualStackEndpointStateEnabled) ||
((service == s3 || service == s3Control) && (o.UseDualStackEndpoint == DualStackEndpointStateUnset && o.UseDualStack)) {
v |= dualStackVariant
}
if o.UseFIPSEndpoint == FIPSEndpointStateEnabled {
v |= fipsVariant
}
return v
}
// EC2IMDSEndpointModeState is an enum configuration variable describing the client endpoint mode.
type EC2IMDSEndpointModeState uint
// Enumeration values for EC2IMDSEndpointModeState
const (
EC2IMDSEndpointModeStateUnset EC2IMDSEndpointModeState = iota
EC2IMDSEndpointModeStateIPv4
EC2IMDSEndpointModeStateIPv6
)
// SetFromString sets the EC2IMDSEndpointModeState based on the provided string value. Unknown values will default to EC2IMDSEndpointModeStateUnset
func (e *EC2IMDSEndpointModeState) SetFromString(v string) error {
v = strings.TrimSpace(v)
switch {
case len(v) == 0:
*e = EC2IMDSEndpointModeStateUnset
case strings.EqualFold(v, "IPv6"):
*e = EC2IMDSEndpointModeStateIPv6
case strings.EqualFold(v, "IPv4"):
*e = EC2IMDSEndpointModeStateIPv4
default:
return fmt.Errorf("unknown EC2 IMDS endpoint mode, must be either IPv6 or IPv4")
}
return nil
} }
// STSRegionalEndpoint is an enum for the states of the STS Regional Endpoint // STSRegionalEndpoint is an enum for the states of the STS Regional Endpoint
@ -166,10 +266,25 @@ func DisableSSLOption(o *Options) {
// UseDualStackOption sets the UseDualStack option. Can be used as a functional // UseDualStackOption sets the UseDualStack option. Can be used as a functional
// option when resolving endpoints. // option when resolving endpoints.
//
// Deprecated: UseDualStackEndpointOption should be used to enable usage of a service's dual-stack endpoint.
// When DualStackEndpointState is set to a non-zero value it takes higher precedence then this option.
func UseDualStackOption(o *Options) { func UseDualStackOption(o *Options) {
o.UseDualStack = true o.UseDualStack = true
} }
// UseDualStackEndpointOption sets the UseDualStackEndpoint option to enabled. Can be used as a functional
// option when resolving endpoints.
func UseDualStackEndpointOption(o *Options) {
o.UseDualStackEndpoint = DualStackEndpointStateEnabled
}
// UseFIPSEndpointOption sets the UseFIPSEndpoint option to enabled. Can be used as a functional
// option when resolving endpoints.
func UseFIPSEndpointOption(o *Options) {
o.UseFIPSEndpoint = FIPSEndpointStateEnabled
}
// StrictMatchingOption sets the StrictMatching option. Can be used as a functional // StrictMatchingOption sets the StrictMatching option. Can be used as a functional
// option when resolving endpoints. // option when resolving endpoints.
func StrictMatchingOption(o *Options) { func StrictMatchingOption(o *Options) {
@ -238,16 +353,18 @@ type EnumPartitions interface {
// as the second parameter. // as the second parameter.
// //
// This example shows how to get the regions for DynamoDB in the AWS partition. // This example shows how to get the regions for DynamoDB in the AWS partition.
// rs, exists := endpoints.RegionsForService(endpoints.DefaultPartitions(), endpoints.AwsPartitionID, endpoints.DynamodbServiceID) //
// rs, exists := endpoints.RegionsForService(endpoints.DefaultPartitions(), endpoints.AwsPartitionID, endpoints.DynamodbServiceID)
// //
// This is equivalent to using the partition directly. // This is equivalent to using the partition directly.
// rs := endpoints.AwsPartition().Services()[endpoints.DynamodbServiceID].Regions() //
// rs := endpoints.AwsPartition().Services()[endpoints.DynamodbServiceID].Regions()
func RegionsForService(ps []Partition, partitionID, serviceID string) (map[string]Region, bool) { func RegionsForService(ps []Partition, partitionID, serviceID string) (map[string]Region, bool) {
for _, p := range ps { for _, p := range ps {
if p.ID() != partitionID { if p.ID() != partitionID {
continue continue
} }
if _, ok := p.p.Services[serviceID]; !ok { if _, ok := p.p.Services[serviceID]; !(ok || serviceID == Ec2metadataServiceID) {
break break
} }
@ -308,8 +425,8 @@ func (p Partition) ID() string { return p.id }
// of new regions and services expansions. // of new regions and services expansions.
// //
// Errors that can be returned. // Errors that can be returned.
// * UnknownServiceError // - UnknownServiceError
// * UnknownEndpointError // - UnknownEndpointError
func (p Partition) EndpointFor(service, region string, opts ...func(*Options)) (ResolvedEndpoint, error) { func (p Partition) EndpointFor(service, region string, opts ...func(*Options)) (ResolvedEndpoint, error) {
return p.p.EndpointFor(service, region, opts...) return p.p.EndpointFor(service, region, opts...)
} }
@ -333,6 +450,7 @@ func (p Partition) Regions() map[string]Region {
// enumerating over the services in a partition. // enumerating over the services in a partition.
func (p Partition) Services() map[string]Service { func (p Partition) Services() map[string]Service {
ss := make(map[string]Service, len(p.p.Services)) ss := make(map[string]Service, len(p.p.Services))
for id := range p.p.Services { for id := range p.p.Services {
ss[id] = Service{ ss[id] = Service{
id: id, id: id,
@ -340,6 +458,15 @@ func (p Partition) Services() map[string]Service {
} }
} }
// Since we have removed the customization that injected this into the model
// we still need to pretend that this is a modeled service.
if _, ok := ss[Ec2metadataServiceID]; !ok {
ss[Ec2metadataServiceID] = Service{
id: Ec2metadataServiceID,
p: p.p,
}
}
return ss return ss
} }
@ -367,7 +494,7 @@ func (r Region) ResolveEndpoint(service string, opts ...func(*Options)) (Resolve
func (r Region) Services() map[string]Service { func (r Region) Services() map[string]Service {
ss := map[string]Service{} ss := map[string]Service{}
for id, s := range r.p.Services { for id, s := range r.p.Services {
if _, ok := s.Endpoints[r.id]; ok { if _, ok := s.Endpoints[endpointKey{Region: r.id}]; ok {
ss[id] = Service{ ss[id] = Service{
id: id, id: id,
p: r.p, p: r.p,
@ -400,10 +527,24 @@ func (s Service) ResolveEndpoint(region string, opts ...func(*Options)) (Resolve
// an URL that can be resolved to a instance of a service. // an URL that can be resolved to a instance of a service.
func (s Service) Regions() map[string]Region { func (s Service) Regions() map[string]Region {
rs := map[string]Region{} rs := map[string]Region{}
for id := range s.p.Services[s.id].Endpoints {
if r, ok := s.p.Regions[id]; ok { service, ok := s.p.Services[s.id]
rs[id] = Region{
id: id, // Since ec2metadata customization has been removed we need to check
// if it was defined in non-standard endpoints.json file. If it's not
// then we can return the empty map as there is no regional-endpoints for IMDS.
// Otherwise, we iterate need to iterate the non-standard model.
if s.id == Ec2metadataServiceID && !ok {
return rs
}
for id := range service.Endpoints {
if id.Variant != 0 {
continue
}
if r, ok := s.p.Regions[id.Region]; ok {
rs[id.Region] = Region{
id: id.Region,
desc: r.Description, desc: r.Description,
p: s.p, p: s.p,
} }
@ -421,8 +562,11 @@ func (s Service) Regions() map[string]Region {
func (s Service) Endpoints() map[string]Endpoint { func (s Service) Endpoints() map[string]Endpoint {
es := make(map[string]Endpoint, len(s.p.Services[s.id].Endpoints)) es := make(map[string]Endpoint, len(s.p.Services[s.id].Endpoints))
for id := range s.p.Services[s.id].Endpoints { for id := range s.p.Services[s.id].Endpoints {
es[id] = Endpoint{ if id.Variant != 0 {
id: id, continue
}
es[id.Region] = Endpoint{
id: id.Region,
serviceID: s.id, serviceID: s.id,
p: s.p, p: s.p,
} }

View File

@ -1,12 +1,46 @@
package endpoints package endpoints
import ( import (
"encoding/json"
"fmt" "fmt"
"regexp" "regexp"
"strconv" "strconv"
"strings" "strings"
) )
const (
ec2MetadataEndpointIPv6 = "http://[fd00:ec2::254]/latest"
ec2MetadataEndpointIPv4 = "http://169.254.169.254/latest"
)
const dnsSuffixTemplateKey = "{dnsSuffix}"
// defaultKey is a compound map key of a variant and other values.
type defaultKey struct {
Variant endpointVariant
ServiceVariant serviceVariant
}
// endpointKey is a compound map key of a region and associated variant value.
type endpointKey struct {
Region string
Variant endpointVariant
}
// endpointVariant is a bit field to describe the endpoints attributes.
type endpointVariant uint64
// serviceVariant is a bit field to describe the service endpoint attributes.
type serviceVariant uint64
const (
// fipsVariant indicates that the endpoint is FIPS capable.
fipsVariant endpointVariant = 1 << (64 - 1 - iota)
// dualStackVariant indicates that the endpoint is DualStack capable.
dualStackVariant
)
var regionValidationRegex = regexp.MustCompile(`^[[:alnum:]]([[:alnum:]\-]*[[:alnum:]])?$`) var regionValidationRegex = regexp.MustCompile(`^[[:alnum:]]([[:alnum:]\-]*[[:alnum:]])?$`)
type partitions []partition type partitions []partition
@ -15,8 +49,12 @@ func (ps partitions) EndpointFor(service, region string, opts ...func(*Options))
var opt Options var opt Options
opt.Set(opts...) opt.Set(opts...)
if len(opt.ResolvedRegion) > 0 {
region = opt.ResolvedRegion
}
for i := 0; i < len(ps); i++ { for i := 0; i < len(ps); i++ {
if !ps[i].canResolveEndpoint(service, region, opt.StrictMatching) { if !ps[i].canResolveEndpoint(service, region, opt) {
continue continue
} }
@ -44,14 +82,76 @@ func (ps partitions) Partitions() []Partition {
return parts return parts
} }
type endpointWithVariants struct {
endpoint
Variants []endpointWithTags `json:"variants"`
}
type endpointWithTags struct {
endpoint
Tags []string `json:"tags"`
}
type endpointDefaults map[defaultKey]endpoint
func (p *endpointDefaults) UnmarshalJSON(data []byte) error {
if *p == nil {
*p = make(endpointDefaults)
}
var e endpointWithVariants
if err := json.Unmarshal(data, &e); err != nil {
return err
}
(*p)[defaultKey{Variant: 0}] = e.endpoint
e.Hostname = ""
e.DNSSuffix = ""
for _, variant := range e.Variants {
endpointVariant, unknown := parseVariantTags(variant.Tags)
if unknown {
continue
}
var ve endpoint
ve.mergeIn(e.endpoint)
ve.mergeIn(variant.endpoint)
(*p)[defaultKey{Variant: endpointVariant}] = ve
}
return nil
}
func parseVariantTags(tags []string) (ev endpointVariant, unknown bool) {
if len(tags) == 0 {
unknown = true
return
}
for _, tag := range tags {
switch {
case strings.EqualFold("fips", tag):
ev |= fipsVariant
case strings.EqualFold("dualstack", tag):
ev |= dualStackVariant
default:
unknown = true
}
}
return ev, unknown
}
type partition struct { type partition struct {
ID string `json:"partition"` ID string `json:"partition"`
Name string `json:"partitionName"` Name string `json:"partitionName"`
DNSSuffix string `json:"dnsSuffix"` DNSSuffix string `json:"dnsSuffix"`
RegionRegex regionRegex `json:"regionRegex"` RegionRegex regionRegex `json:"regionRegex"`
Defaults endpoint `json:"defaults"` Defaults endpointDefaults `json:"defaults"`
Regions regions `json:"regions"` Regions regions `json:"regions"`
Services services `json:"services"` Services services `json:"services"`
} }
func (p partition) Partition() Partition { func (p partition) Partition() Partition {
@ -62,15 +162,18 @@ func (p partition) Partition() Partition {
} }
} }
func (p partition) canResolveEndpoint(service, region string, strictMatch bool) bool { func (p partition) canResolveEndpoint(service, region string, options Options) bool {
s, hasService := p.Services[service] s, hasService := p.Services[service]
_, hasEndpoint := s.Endpoints[region] _, hasEndpoint := s.Endpoints[endpointKey{
Region: region,
Variant: options.getEndpointVariant(service),
}]
if hasEndpoint && hasService { if hasEndpoint && hasService {
return true return true
} }
if strictMatch { if options.StrictMatching {
return false return false
} }
@ -101,7 +204,17 @@ func (p partition) EndpointFor(service, region string, opts ...func(*Options)) (
var opt Options var opt Options
opt.Set(opts...) opt.Set(opts...)
if len(opt.ResolvedRegion) > 0 {
region = opt.ResolvedRegion
}
s, hasService := p.Services[service] s, hasService := p.Services[service]
if service == Ec2metadataServiceID && !hasService {
endpoint := getEC2MetadataEndpoint(p.ID, service, opt.EC2MetadataEndpointMode)
return endpoint, nil
}
if len(service) == 0 || !(hasService || opt.ResolveUnknownService) { if len(service) == 0 || !(hasService || opt.ResolveUnknownService) {
// Only return error if the resolver will not fallback to creating // Only return error if the resolver will not fallback to creating
// endpoint based on service endpoint ID passed in. // endpoint based on service endpoint ID passed in.
@ -112,21 +225,94 @@ func (p partition) EndpointFor(service, region string, opts ...func(*Options)) (
region = s.PartitionEndpoint region = s.PartitionEndpoint
} }
if (service == "sts" && opt.STSRegionalEndpoint != RegionalSTSEndpoint) || if r, ok := isLegacyGlobalRegion(service, region, opt); ok {
(service == "s3" && opt.S3UsEast1RegionalEndpoint != RegionalS3UsEast1Endpoint) { region = r
}
variant := opt.getEndpointVariant(service)
endpoints := s.Endpoints
serviceDefaults, hasServiceDefault := s.Defaults[defaultKey{Variant: variant}]
// If we searched for a variant which may have no explicit service defaults,
// then we need to inherit the standard service defaults except the hostname and dnsSuffix
if variant != 0 && !hasServiceDefault {
serviceDefaults = s.Defaults[defaultKey{}]
serviceDefaults.Hostname = ""
serviceDefaults.DNSSuffix = ""
}
partitionDefaults, hasPartitionDefault := p.Defaults[defaultKey{Variant: variant}]
var dnsSuffix string
if len(serviceDefaults.DNSSuffix) > 0 {
dnsSuffix = serviceDefaults.DNSSuffix
} else if variant == 0 {
// For legacy reasons the partition dnsSuffix is not in the defaults, so if we looked for
// a non-variant endpoint then we need to set the dnsSuffix.
dnsSuffix = p.DNSSuffix
}
noDefaults := !hasServiceDefault && !hasPartitionDefault
e, hasEndpoint := s.endpointForRegion(region, endpoints, variant)
if len(region) == 0 || (!hasEndpoint && (opt.StrictMatching || noDefaults)) {
return resolved, NewUnknownEndpointError(p.ID, service, region, endpointList(endpoints, variant))
}
defs := []endpoint{partitionDefaults, serviceDefaults}
return e.resolve(service, p.ID, region, dnsSuffixTemplateKey, dnsSuffix, defs, opt)
}
func getEC2MetadataEndpoint(partitionID, service string, mode EC2IMDSEndpointModeState) ResolvedEndpoint {
switch mode {
case EC2IMDSEndpointModeStateIPv6:
return ResolvedEndpoint{
URL: ec2MetadataEndpointIPv6,
PartitionID: partitionID,
SigningRegion: "aws-global",
SigningName: service,
SigningNameDerived: true,
SigningMethod: "v4",
}
case EC2IMDSEndpointModeStateIPv4:
fallthrough
default:
return ResolvedEndpoint{
URL: ec2MetadataEndpointIPv4,
PartitionID: partitionID,
SigningRegion: "aws-global",
SigningName: service,
SigningNameDerived: true,
SigningMethod: "v4",
}
}
}
func isLegacyGlobalRegion(service string, region string, opt Options) (string, bool) {
if opt.getEndpointVariant(service) != 0 {
return "", false
}
const (
sts = "sts"
s3 = "s3"
awsGlobal = "aws-global"
)
switch {
case service == sts && opt.STSRegionalEndpoint == RegionalSTSEndpoint:
return region, false
case service == s3 && opt.S3UsEast1RegionalEndpoint == RegionalS3UsEast1Endpoint:
return region, false
default:
if _, ok := legacyGlobalRegions[service][region]; ok { if _, ok := legacyGlobalRegions[service][region]; ok {
region = "aws-global" return awsGlobal, true
} }
} }
e, hasEndpoint := s.endpointForRegion(region) return region, false
if len(region) == 0 || (!hasEndpoint && opt.StrictMatching) {
return resolved, NewUnknownEndpointError(p.ID, service, region, endpointList(s.Endpoints))
}
defs := []endpoint{p.Defaults, s.Defaults}
return e.resolve(service, p.ID, region, p.DNSSuffix, defs, opt)
} }
func serviceList(ss services) []string { func serviceList(ss services) []string {
@ -136,10 +322,13 @@ func serviceList(ss services) []string {
} }
return list return list
} }
func endpointList(es endpoints) []string { func endpointList(es serviceEndpoints, variant endpointVariant) []string {
list := make([]string, 0, len(es)) list := make([]string, 0, len(es))
for k := range es { for k := range es {
list = append(list, k) if k.Variant != variant {
continue
}
list = append(list, k.Region)
} }
return list return list
} }
@ -171,19 +360,19 @@ type region struct {
type services map[string]service type services map[string]service
type service struct { type service struct {
PartitionEndpoint string `json:"partitionEndpoint"` PartitionEndpoint string `json:"partitionEndpoint"`
IsRegionalized boxedBool `json:"isRegionalized,omitempty"` IsRegionalized boxedBool `json:"isRegionalized,omitempty"`
Defaults endpoint `json:"defaults"` Defaults endpointDefaults `json:"defaults"`
Endpoints endpoints `json:"endpoints"` Endpoints serviceEndpoints `json:"endpoints"`
} }
func (s *service) endpointForRegion(region string) (endpoint, bool) { func (s *service) endpointForRegion(region string, endpoints serviceEndpoints, variant endpointVariant) (endpoint, bool) {
if e, ok := s.Endpoints[region]; ok { if e, ok := endpoints[endpointKey{Region: region, Variant: variant}]; ok {
return e, true return e, true
} }
if s.IsRegionalized == boxedFalse { if s.IsRegionalized == boxedFalse {
return s.Endpoints[s.PartitionEndpoint], region == s.PartitionEndpoint return endpoints[endpointKey{Region: s.PartitionEndpoint, Variant: variant}], region == s.PartitionEndpoint
} }
// Unable to find any matching endpoint, return // Unable to find any matching endpoint, return
@ -191,22 +380,73 @@ func (s *service) endpointForRegion(region string) (endpoint, bool) {
return endpoint{}, false return endpoint{}, false
} }
type endpoints map[string]endpoint type serviceEndpoints map[endpointKey]endpoint
func (s *serviceEndpoints) UnmarshalJSON(data []byte) error {
if *s == nil {
*s = make(serviceEndpoints)
}
var regionToEndpoint map[string]endpointWithVariants
if err := json.Unmarshal(data, &regionToEndpoint); err != nil {
return err
}
for region, e := range regionToEndpoint {
(*s)[endpointKey{Region: region}] = e.endpoint
e.Hostname = ""
e.DNSSuffix = ""
for _, variant := range e.Variants {
endpointVariant, unknown := parseVariantTags(variant.Tags)
if unknown {
continue
}
var ve endpoint
ve.mergeIn(e.endpoint)
ve.mergeIn(variant.endpoint)
(*s)[endpointKey{Region: region, Variant: endpointVariant}] = ve
}
}
return nil
}
type endpoint struct { type endpoint struct {
Hostname string `json:"hostname"` Hostname string `json:"hostname"`
Protocols []string `json:"protocols"` Protocols []string `json:"protocols"`
CredentialScope credentialScope `json:"credentialScope"` CredentialScope credentialScope `json:"credentialScope"`
// Custom fields not modeled DNSSuffix string `json:"dnsSuffix"`
HasDualStack boxedBool `json:"-"`
DualStackHostname string `json:"-"`
// Signature Version not used // Signature Version not used
SignatureVersions []string `json:"signatureVersions"` SignatureVersions []string `json:"signatureVersions"`
// SSLCommonName not used. // SSLCommonName not used.
SSLCommonName string `json:"sslCommonName"` SSLCommonName string `json:"sslCommonName"`
Deprecated boxedBool `json:"deprecated"`
}
// isZero returns whether the endpoint structure is an empty (zero) value.
func (e endpoint) isZero() bool {
switch {
case len(e.Hostname) != 0:
return false
case len(e.Protocols) != 0:
return false
case e.CredentialScope != (credentialScope{}):
return false
case len(e.SignatureVersions) != 0:
return false
case len(e.SSLCommonName) != 0:
return false
}
return true
} }
const ( const (
@ -235,7 +475,7 @@ func getByPriority(s []string, p []string, def string) string {
return s[0] return s[0]
} }
func (e endpoint) resolve(service, partitionID, region, dnsSuffix string, defs []endpoint, opts Options) (ResolvedEndpoint, error) { func (e endpoint) resolve(service, partitionID, region, dnsSuffixTemplateVariable, dnsSuffix string, defs []endpoint, opts Options) (ResolvedEndpoint, error) {
var merged endpoint var merged endpoint
for _, def := range defs { for _, def := range defs {
merged.mergeIn(def) merged.mergeIn(def)
@ -256,23 +496,26 @@ func (e endpoint) resolve(service, partitionID, region, dnsSuffix string, defs [
} }
hostname := e.Hostname hostname := e.Hostname
// Offset the hostname for dualstack if enabled
if opts.UseDualStack && e.HasDualStack == boxedTrue {
hostname = e.DualStackHostname
region = signingRegion
}
if !validateInputRegion(region) { if !validateInputRegion(region) {
return ResolvedEndpoint{}, fmt.Errorf("invalid region identifier format provided") return ResolvedEndpoint{}, fmt.Errorf("invalid region identifier format provided")
} }
if len(merged.DNSSuffix) > 0 {
dnsSuffix = merged.DNSSuffix
}
u := strings.Replace(hostname, "{service}", service, 1) u := strings.Replace(hostname, "{service}", service, 1)
u = strings.Replace(u, "{region}", region, 1) u = strings.Replace(u, "{region}", region, 1)
u = strings.Replace(u, "{dnsSuffix}", dnsSuffix, 1) u = strings.Replace(u, dnsSuffixTemplateVariable, dnsSuffix, 1)
scheme := getEndpointScheme(e.Protocols, opts.DisableSSL) scheme := getEndpointScheme(e.Protocols, opts.DisableSSL)
u = fmt.Sprintf("%s://%s", scheme, u) u = fmt.Sprintf("%s://%s", scheme, u)
if e.Deprecated == boxedTrue && opts.LogDeprecated && opts.Logger != nil {
opts.Logger.Log(fmt.Sprintf("endpoint identifier %q, url %q marked as deprecated", region, u))
}
return ResolvedEndpoint{ return ResolvedEndpoint{
URL: u, URL: u,
PartitionID: partitionID, PartitionID: partitionID,
@ -310,11 +553,11 @@ func (e *endpoint) mergeIn(other endpoint) {
if len(other.SSLCommonName) > 0 { if len(other.SSLCommonName) > 0 {
e.SSLCommonName = other.SSLCommonName e.SSLCommonName = other.SSLCommonName
} }
if other.HasDualStack != boxedBoolUnset { if len(other.DNSSuffix) > 0 {
e.HasDualStack = other.HasDualStack e.DNSSuffix = other.DNSSuffix
} }
if len(other.DualStackHostname) > 0 { if other.Deprecated != boxedBoolUnset {
e.DualStackHostname = other.DualStackHostname e.Deprecated = other.Deprecated
} }
} }

View File

@ -1,3 +1,4 @@
//go:build codegen
// +build codegen // +build codegen
package endpoints package endpoints
@ -154,18 +155,71 @@ func serviceSet(ps partitions) map[string]struct{} {
return set return set
} }
func endpointVariantSetter(variant endpointVariant) (string, error) {
if variant == 0 {
return "0", nil
}
if variant > (fipsVariant | dualStackVariant) {
return "", fmt.Errorf("unknown endpoint variant")
}
var symbols []string
if variant&fipsVariant != 0 {
symbols = append(symbols, "fipsVariant")
}
if variant&dualStackVariant != 0 {
symbols = append(symbols, "dualStackVariant")
}
v := strings.Join(symbols, "|")
return v, nil
}
func endpointKeySetter(e endpointKey) (string, error) {
var sb strings.Builder
sb.WriteString("endpointKey{\n")
sb.WriteString(fmt.Sprintf("Region: %q,\n", e.Region))
if e.Variant != 0 {
variantSetter, err := endpointVariantSetter(e.Variant)
if err != nil {
return "", err
}
sb.WriteString(fmt.Sprintf("Variant: %s,\n", variantSetter))
}
sb.WriteString("}")
return sb.String(), nil
}
func defaultKeySetter(e defaultKey) (string, error) {
var sb strings.Builder
sb.WriteString("defaultKey{\n")
if e.Variant != 0 {
variantSetter, err := endpointVariantSetter(e.Variant)
if err != nil {
return "", err
}
sb.WriteString(fmt.Sprintf("Variant: %s,\n", variantSetter))
}
sb.WriteString("}")
return sb.String(), nil
}
var funcMap = template.FuncMap{ var funcMap = template.FuncMap{
"ToSymbol": toSymbol, "ToSymbol": toSymbol,
"QuoteString": quoteString, "QuoteString": quoteString,
"RegionConst": regionConstName, "RegionConst": regionConstName,
"PartitionGetter": partitionGetter, "PartitionGetter": partitionGetter,
"PartitionVarName": partitionVarName, "PartitionVarName": partitionVarName,
"ListPartitionNames": listPartitionNames, "ListPartitionNames": listPartitionNames,
"BoxedBoolIfSet": boxedBoolIfSet, "BoxedBoolIfSet": boxedBoolIfSet,
"StringIfSet": stringIfSet, "StringIfSet": stringIfSet,
"StringSliceIfSet": stringSliceIfSet, "StringSliceIfSet": stringSliceIfSet,
"EndpointIsSet": endpointIsSet, "EndpointIsSet": endpointIsSet,
"ServicesSet": serviceSet, "ServicesSet": serviceSet,
"EndpointVariantSetter": endpointVariantSetter,
"EndpointKeySetter": endpointKeySetter,
"DefaultKeySetter": defaultKeySetter,
} }
const v3Tmpl = ` const v3Tmpl = `
@ -271,9 +325,9 @@ partition{
{{ StringIfSet "Name: %q,\n" .Name -}} {{ StringIfSet "Name: %q,\n" .Name -}}
{{ StringIfSet "DNSSuffix: %q,\n" .DNSSuffix -}} {{ StringIfSet "DNSSuffix: %q,\n" .DNSSuffix -}}
RegionRegex: {{ template "gocode RegionRegex" .RegionRegex }}, RegionRegex: {{ template "gocode RegionRegex" .RegionRegex }},
{{ if EndpointIsSet .Defaults -}} {{ if (gt (len .Defaults) 0) -}}
Defaults: {{ template "gocode Endpoint" .Defaults }}, Defaults: {{ template "gocode Defaults" .Defaults -}},
{{- end }} {{ end -}}
Regions: {{ template "gocode Regions" .Regions }}, Regions: {{ template "gocode Regions" .Regions }},
Services: {{ template "gocode Services" .Services }}, Services: {{ template "gocode Services" .Services }},
} }
@ -314,19 +368,27 @@ services{
service{ service{
{{ StringIfSet "PartitionEndpoint: %q,\n" .PartitionEndpoint -}} {{ StringIfSet "PartitionEndpoint: %q,\n" .PartitionEndpoint -}}
{{ BoxedBoolIfSet "IsRegionalized: %s,\n" .IsRegionalized -}} {{ BoxedBoolIfSet "IsRegionalized: %s,\n" .IsRegionalized -}}
{{ if EndpointIsSet .Defaults -}} {{ if (gt (len .Defaults) 0) -}}
Defaults: {{ template "gocode Endpoint" .Defaults -}}, Defaults: {{ template "gocode Defaults" .Defaults -}},
{{- end }} {{ end -}}
{{ if .Endpoints -}} {{ if .Endpoints -}}
Endpoints: {{ template "gocode Endpoints" .Endpoints }}, Endpoints: {{ template "gocode Endpoints" .Endpoints }},
{{- end }} {{- end }}
} }
{{- end }} {{- end }}
{{ define "gocode Endpoints" -}} {{ define "gocode Defaults" -}}
endpoints{ endpointDefaults{
{{ range $id, $endpoint := . -}} {{ range $id, $endpoint := . -}}
"{{ $id }}": {{ template "gocode Endpoint" $endpoint }}, {{ DefaultKeySetter $id }}: {{ template "gocode Endpoint" $endpoint }},
{{ end }}
}
{{- end }}
{{ define "gocode Endpoints" -}}
serviceEndpoints{
{{ range $id, $endpoint := . -}}
{{ EndpointKeySetter $id }}: {{ template "gocode Endpoint" $endpoint }},
{{ end }} {{ end }}
} }
{{- end }} {{- end }}
@ -334,6 +396,7 @@ endpoints{
{{ define "gocode Endpoint" -}} {{ define "gocode Endpoint" -}}
endpoint{ endpoint{
{{ StringIfSet "Hostname: %q,\n" .Hostname -}} {{ StringIfSet "Hostname: %q,\n" .Hostname -}}
{{ StringIfSet "DNSSuffix: %q,\n" .DNSSuffix -}}
{{ StringIfSet "SSLCommonName: %q,\n" .SSLCommonName -}} {{ StringIfSet "SSLCommonName: %q,\n" .SSLCommonName -}}
{{ StringSliceIfSet "Protocols: []string{%s},\n" .Protocols -}} {{ StringSliceIfSet "Protocols: []string{%s},\n" .Protocols -}}
{{ StringSliceIfSet "SignatureVersions: []string{%s},\n" .SignatureVersions -}} {{ StringSliceIfSet "SignatureVersions: []string{%s},\n" .SignatureVersions -}}
@ -343,9 +406,7 @@ endpoint{
{{ StringIfSet "Service: %q,\n" .CredentialScope.Service -}} {{ StringIfSet "Service: %q,\n" .CredentialScope.Service -}}
}, },
{{- end }} {{- end }}
{{ BoxedBoolIfSet "HasDualStack: %s,\n" .HasDualStack -}} {{ BoxedBoolIfSet "Deprecated: %s,\n" .Deprecated -}}
{{ StringIfSet "DualStackHostname: %q,\n" .DualStackHostname -}}
} }
{{- end }} {{- end }}
` `

View File

@ -77,6 +77,9 @@ const (
// wire unmarshaled message content of requests and responses made while // wire unmarshaled message content of requests and responses made while
// using the SDK Will also enable LogDebug. // using the SDK Will also enable LogDebug.
LogDebugWithEventStreamBody LogDebugWithEventStreamBody
// LogDebugWithDeprecated states the SDK should log details about deprecated functionality.
LogDebugWithDeprecated
) )
// A Logger is a minimalistic interface for the SDK to log messages to. Should // A Logger is a minimalistic interface for the SDK to log messages to. Should

View File

@ -330,6 +330,9 @@ func MakeAddToUserAgentFreeFormHandler(s string) func(*Request) {
// WithSetRequestHeaders updates the operation request's HTTP header to contain // WithSetRequestHeaders updates the operation request's HTTP header to contain
// the header key value pairs provided. If the header key already exists in the // the header key value pairs provided. If the header key already exists in the
// request's HTTP header set, the existing value(s) will be replaced. // request's HTTP header set, the existing value(s) will be replaced.
//
// Header keys added will be added as canonical format with title casing
// applied via http.Header.Set method.
func WithSetRequestHeaders(h map[string]string) Option { func WithSetRequestHeaders(h map[string]string) Option {
return withRequestHeader(h).SetRequestHeaders return withRequestHeader(h).SetRequestHeaders
} }
@ -338,6 +341,6 @@ type withRequestHeader map[string]string
func (h withRequestHeader) SetRequestHeaders(r *Request) { func (h withRequestHeader) SetRequestHeaders(r *Request) {
for k, v := range h { for k, v := range h {
r.HTTPRequest.Header[k] = []string{v} r.HTTPRequest.Header.Set(k, v)
} }
} }

View File

@ -4,6 +4,7 @@ import (
"bytes" "bytes"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"net/http" "net/http"
"net/url" "net/url"
"reflect" "reflect"
@ -129,12 +130,27 @@ func New(cfg aws.Config, clientInfo metadata.ClientInfo, handlers Handlers,
httpReq, _ := http.NewRequest(method, "", nil) httpReq, _ := http.NewRequest(method, "", nil)
var err error var err error
httpReq.URL, err = url.Parse(clientInfo.Endpoint + operation.HTTPPath) httpReq.URL, err = url.Parse(clientInfo.Endpoint)
if err != nil { if err != nil {
httpReq.URL = &url.URL{} httpReq.URL = &url.URL{}
err = awserr.New("InvalidEndpointURL", "invalid endpoint uri", err) err = awserr.New("InvalidEndpointURL", "invalid endpoint uri", err)
} }
if len(operation.HTTPPath) != 0 {
opHTTPPath := operation.HTTPPath
var opQueryString string
if idx := strings.Index(opHTTPPath, "?"); idx >= 0 {
opQueryString = opHTTPPath[idx+1:]
opHTTPPath = opHTTPPath[:idx]
}
if strings.HasSuffix(httpReq.URL.Path, "/") && strings.HasPrefix(opHTTPPath, "/") {
opHTTPPath = opHTTPPath[1:]
}
httpReq.URL.Path += opHTTPPath
httpReq.URL.RawQuery = opQueryString
}
r := &Request{ r := &Request{
Config: cfg, Config: cfg,
ClientInfo: clientInfo, ClientInfo: clientInfo,
@ -510,6 +526,14 @@ func (r *Request) GetBody() io.ReadSeeker {
// Send will not close the request.Request's body. // Send will not close the request.Request's body.
func (r *Request) Send() error { func (r *Request) Send() error {
defer func() { defer func() {
// Ensure a non-nil HTTPResponse parameter is set to ensure handlers
// checking for HTTPResponse values, don't fail.
if r.HTTPResponse == nil {
r.HTTPResponse = &http.Response{
Header: http.Header{},
Body: ioutil.NopCloser(&bytes.Buffer{}),
}
}
// Regardless of success or failure of the request trigger the Complete // Regardless of success or failure of the request trigger the Complete
// request handlers. // request handlers.
r.Handlers.Complete.Run(r) r.Handlers.Complete.Run(r)

View File

@ -1,3 +1,4 @@
//go:build !go1.8
// +build !go1.8 // +build !go1.8
package request package request

View File

@ -1,3 +1,4 @@
//go:build go1.8
// +build go1.8 // +build go1.8
package request package request

View File

@ -1,3 +1,4 @@
//go:build go1.7
// +build go1.7 // +build go1.7
package request package request

View File

@ -1,3 +1,4 @@
//go:build !go1.7
// +build !go1.7 // +build !go1.7
package request package request

View File

@ -15,8 +15,8 @@ import (
// and determine if a request API error should be retried. // and determine if a request API error should be retried.
// //
// client.DefaultRetryer is the SDK's default implementation of the Retryer. It // client.DefaultRetryer is the SDK's default implementation of the Retryer. It
// uses the which uses the Request.IsErrorRetryable and Request.IsErrorThrottle // uses the Request.IsErrorRetryable and Request.IsErrorThrottle methods to
// methods to determine if the request is retried. // determine if the request is retried.
type Retryer interface { type Retryer interface {
// RetryRules return the retry delay that should be used by the SDK before // RetryRules return the retry delay that should be used by the SDK before
// making another request attempt for the failed request. // making another request attempt for the failed request.

View File

@ -14,8 +14,17 @@ import (
"github.com/aws/aws-sdk-go/aws/defaults" "github.com/aws/aws-sdk-go/aws/defaults"
"github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/internal/shareddefaults" "github.com/aws/aws-sdk-go/internal/shareddefaults"
"github.com/aws/aws-sdk-go/service/sts"
) )
// CredentialsProviderOptions specifies additional options for configuring
// credentials providers.
type CredentialsProviderOptions struct {
// WebIdentityRoleProviderOptions configures a WebIdentityRoleProvider,
// such as setting its ExpiryWindow.
WebIdentityRoleProviderOptions func(*stscreds.WebIdentityRoleProvider)
}
func resolveCredentials(cfg *aws.Config, func resolveCredentials(cfg *aws.Config,
envCfg envConfig, sharedCfg sharedConfig, envCfg envConfig, sharedCfg sharedConfig,
handlers request.Handlers, handlers request.Handlers,
@ -40,6 +49,7 @@ func resolveCredentials(cfg *aws.Config,
envCfg.WebIdentityTokenFilePath, envCfg.WebIdentityTokenFilePath,
envCfg.RoleARN, envCfg.RoleARN,
envCfg.RoleSessionName, envCfg.RoleSessionName,
sessOpts.CredentialsProviderOptions,
) )
default: default:
@ -59,6 +69,7 @@ var WebIdentityEmptyTokenFilePathErr = awserr.New(stscreds.ErrCodeWebIdentity, "
func assumeWebIdentity(cfg *aws.Config, handlers request.Handlers, func assumeWebIdentity(cfg *aws.Config, handlers request.Handlers,
filepath string, filepath string,
roleARN, sessionName string, roleARN, sessionName string,
credOptions *CredentialsProviderOptions,
) (*credentials.Credentials, error) { ) (*credentials.Credentials, error) {
if len(filepath) == 0 { if len(filepath) == 0 {
@ -69,17 +80,18 @@ func assumeWebIdentity(cfg *aws.Config, handlers request.Handlers,
return nil, WebIdentityEmptyRoleARNErr return nil, WebIdentityEmptyRoleARNErr
} }
creds := stscreds.NewWebIdentityCredentials( svc := sts.New(&Session{
&Session{ Config: cfg,
Config: cfg, Handlers: handlers.Copy(),
Handlers: handlers.Copy(), })
},
roleARN,
sessionName,
filepath,
)
return creds, nil var optFns []func(*stscreds.WebIdentityRoleProvider)
if credOptions != nil && credOptions.WebIdentityRoleProviderOptions != nil {
optFns = append(optFns, credOptions.WebIdentityRoleProviderOptions)
}
p := stscreds.NewWebIdentityRoleProviderWithOptions(svc, roleARN, sessionName, stscreds.FetchTokenPath(filepath), optFns...)
return credentials.NewCredentials(p), nil
} }
func resolveCredsFromProfile(cfg *aws.Config, func resolveCredsFromProfile(cfg *aws.Config,
@ -114,6 +126,7 @@ func resolveCredsFromProfile(cfg *aws.Config,
sharedCfg.WebIdentityTokenFile, sharedCfg.WebIdentityTokenFile,
sharedCfg.RoleARN, sharedCfg.RoleARN,
sharedCfg.RoleSessionName, sharedCfg.RoleSessionName,
sessOpts.CredentialsProviderOptions,
) )
case sharedCfg.hasSSOConfiguration(): case sharedCfg.hasSSOConfiguration():

View File

@ -1,3 +1,4 @@
//go:build go1.13
// +build go1.13 // +build go1.13
package session package session

View File

@ -1,3 +1,4 @@
//go:build !go1.13 && go1.7
// +build !go1.13,go1.7 // +build !go1.13,go1.7
package session package session

View File

@ -1,3 +1,4 @@
//go:build !go1.6 && go1.5
// +build !go1.6,go1.5 // +build !go1.6,go1.5
package session package session

View File

@ -1,3 +1,4 @@
//go:build !go1.7 && go1.6
// +build !go1.7,go1.6 // +build !go1.7,go1.6
package session package session

View File

@ -283,7 +283,85 @@ component must be enclosed in square brackets.
The custom EC2 IMDS endpoint can also be specified via the Session options. The custom EC2 IMDS endpoint can also be specified via the Session options.
sess, err := session.NewSessionWithOptions(session.Options{ sess, err := session.NewSessionWithOptions(session.Options{
EC2IMDSEndpoint: "http://[::1]", EC2MetadataEndpoint: "http://[::1]",
})
FIPS and DualStack Endpoints
The SDK can be configured to resolve an endpoint with certain capabilities such as FIPS and DualStack.
You can configure a FIPS endpoint using an environment variable, shared config ($HOME/.aws/config),
or programmatically.
To configure a FIPS endpoint set the environment variable set the AWS_USE_FIPS_ENDPOINT to true or false to enable
or disable FIPS endpoint resolution.
AWS_USE_FIPS_ENDPOINT=true
To configure a FIPS endpoint using shared config, set use_fips_endpoint to true or false to enable
or disable FIPS endpoint resolution.
[profile myprofile]
region=us-west-2
use_fips_endpoint=true
To configure a FIPS endpoint programmatically
// Option 1: Configure it on a session for all clients
sess, err := session.NewSessionWithOptions(session.Options{
UseFIPSEndpoint: endpoints.FIPSEndpointStateEnabled,
})
if err != nil {
// handle error
}
client := s3.New(sess)
// Option 2: Configure it per client
sess, err := session.NewSession()
if err != nil {
// handle error
}
client := s3.New(sess, &aws.Config{
UseFIPSEndpoint: endpoints.FIPSEndpointStateEnabled,
})
You can configure a DualStack endpoint using an environment variable, shared config ($HOME/.aws/config),
or programmatically.
To configure a DualStack endpoint set the environment variable set the AWS_USE_DUALSTACK_ENDPOINT to true or false to
enable or disable DualStack endpoint resolution.
AWS_USE_DUALSTACK_ENDPOINT=true
To configure a DualStack endpoint using shared config, set use_dualstack_endpoint to true or false to enable
or disable DualStack endpoint resolution.
[profile myprofile]
region=us-west-2
use_dualstack_endpoint=true
To configure a DualStack endpoint programmatically
// Option 1: Configure it on a session for all clients
sess, err := session.NewSessionWithOptions(session.Options{
UseDualStackEndpoint: endpoints.DualStackEndpointStateEnabled,
})
if err != nil {
// handle error
}
client := s3.New(sess)
// Option 2: Configure it per client
sess, err := session.NewSession()
if err != nil {
// handle error
}
client := s3.New(sess, &aws.Config{
UseDualStackEndpoint: endpoints.DualStackEndpointStateEnabled,
}) })
*/ */
package session package session

View File

@ -161,10 +161,27 @@ type envConfig struct {
// AWS_S3_USE_ARN_REGION=true // AWS_S3_USE_ARN_REGION=true
S3UseARNRegion bool S3UseARNRegion bool
// Specifies the alternative endpoint to use for EC2 IMDS. // Specifies the EC2 Instance Metadata Service endpoint to use. If specified it overrides EC2IMDSEndpointMode.
// //
// AWS_EC2_METADATA_SERVICE_ENDPOINT=http://[::1] // AWS_EC2_METADATA_SERVICE_ENDPOINT=http://[::1]
EC2IMDSEndpoint string EC2IMDSEndpoint string
// Specifies the EC2 Instance Metadata Service default endpoint selection mode (IPv4 or IPv6)
//
// AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE=IPv6
EC2IMDSEndpointMode endpoints.EC2IMDSEndpointModeState
// Specifies that SDK clients must resolve a dual-stack endpoint for
// services.
//
// AWS_USE_DUALSTACK_ENDPOINT=true
UseDualStackEndpoint endpoints.DualStackEndpointState
// Specifies that SDK clients must resolve a FIPS endpoint for
// services.
//
// AWS_USE_FIPS_ENDPOINT=true
UseFIPSEndpoint endpoints.FIPSEndpointState
} }
var ( var (
@ -231,6 +248,9 @@ var (
ec2IMDSEndpointEnvKey = []string{ ec2IMDSEndpointEnvKey = []string{
"AWS_EC2_METADATA_SERVICE_ENDPOINT", "AWS_EC2_METADATA_SERVICE_ENDPOINT",
} }
ec2IMDSEndpointModeEnvKey = []string{
"AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE",
}
useCABundleKey = []string{ useCABundleKey = []string{
"AWS_CA_BUNDLE", "AWS_CA_BUNDLE",
} }
@ -240,6 +260,12 @@ var (
useClientTLSKey = []string{ useClientTLSKey = []string{
"AWS_SDK_GO_CLIENT_TLS_KEY", "AWS_SDK_GO_CLIENT_TLS_KEY",
} }
awsUseDualStackEndpoint = []string{
"AWS_USE_DUALSTACK_ENDPOINT",
}
awsUseFIPSEndpoint = []string{
"AWS_USE_FIPS_ENDPOINT",
}
) )
// loadEnvConfig retrieves the SDK's environment configuration. // loadEnvConfig retrieves the SDK's environment configuration.
@ -364,6 +390,17 @@ func envConfigLoad(enableSharedConfig bool) (envConfig, error) {
} }
setFromEnvVal(&cfg.EC2IMDSEndpoint, ec2IMDSEndpointEnvKey) setFromEnvVal(&cfg.EC2IMDSEndpoint, ec2IMDSEndpointEnvKey)
if err := setEC2IMDSEndpointMode(&cfg.EC2IMDSEndpointMode, ec2IMDSEndpointModeEnvKey); err != nil {
return envConfig{}, err
}
if err := setUseDualStackEndpointFromEnvVal(&cfg.UseDualStackEndpoint, awsUseDualStackEndpoint); err != nil {
return cfg, err
}
if err := setUseFIPSEndpointFromEnvVal(&cfg.UseFIPSEndpoint, awsUseFIPSEndpoint); err != nil {
return cfg, err
}
return cfg, nil return cfg, nil
} }
@ -376,3 +413,59 @@ func setFromEnvVal(dst *string, keys []string) {
} }
} }
} }
func setEC2IMDSEndpointMode(mode *endpoints.EC2IMDSEndpointModeState, keys []string) error {
for _, k := range keys {
value := os.Getenv(k)
if len(value) == 0 {
continue
}
if err := mode.SetFromString(value); err != nil {
return fmt.Errorf("invalid value for environment variable, %s=%s, %v", k, value, err)
}
return nil
}
return nil
}
func setUseDualStackEndpointFromEnvVal(dst *endpoints.DualStackEndpointState, keys []string) error {
for _, k := range keys {
value := os.Getenv(k)
if len(value) == 0 {
continue // skip if empty
}
switch {
case strings.EqualFold(value, "true"):
*dst = endpoints.DualStackEndpointStateEnabled
case strings.EqualFold(value, "false"):
*dst = endpoints.DualStackEndpointStateDisabled
default:
return fmt.Errorf(
"invalid value for environment variable, %s=%s, need true, false",
k, value)
}
}
return nil
}
func setUseFIPSEndpointFromEnvVal(dst *endpoints.FIPSEndpointState, keys []string) error {
for _, k := range keys {
value := os.Getenv(k)
if len(value) == 0 {
continue // skip if empty
}
switch {
case strings.EqualFold(value, "true"):
*dst = endpoints.FIPSEndpointStateEnabled
case strings.EqualFold(value, "false"):
*dst = endpoints.FIPSEndpointStateDisabled
default:
return fmt.Errorf(
"invalid value for environment variable, %s=%s, need true, false",
k, value)
}
}
return nil
}

View File

@ -8,6 +8,7 @@ import (
"io/ioutil" "io/ioutil"
"net/http" "net/http"
"os" "os"
"strings"
"time" "time"
"github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws"
@ -283,8 +284,8 @@ type Options struct {
Handlers request.Handlers Handlers request.Handlers
// Allows specifying a custom endpoint to be used by the EC2 IMDS client // Allows specifying a custom endpoint to be used by the EC2 IMDS client
// when making requests to the EC2 IMDS API. The must endpoint value must // when making requests to the EC2 IMDS API. The endpoint value should
// include protocol prefix. // include the URI scheme. If the scheme is not present it will be defaulted to http.
// //
// If unset, will the EC2 IMDS client will use its default endpoint. // If unset, will the EC2 IMDS client will use its default endpoint.
// //
@ -298,6 +299,16 @@ type Options struct {
// //
// AWS_EC2_METADATA_SERVICE_ENDPOINT=http://[::1] // AWS_EC2_METADATA_SERVICE_ENDPOINT=http://[::1]
EC2IMDSEndpoint string EC2IMDSEndpoint string
// Specifies the EC2 Instance Metadata Service default endpoint selection mode (IPv4 or IPv6)
//
// AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE=IPv6
EC2IMDSEndpointMode endpoints.EC2IMDSEndpointModeState
// Specifies options for creating credential providers.
// These are only used if the aws.Config does not already
// include credentials.
CredentialsProviderOptions *CredentialsProviderOptions
} }
// NewSessionWithOptions returns a new Session created from SDK defaults, config files, // NewSessionWithOptions returns a new Session created from SDK defaults, config files,
@ -375,19 +386,23 @@ func Must(sess *Session, err error) *Session {
// Wraps the endpoint resolver with a resolver that will return a custom // Wraps the endpoint resolver with a resolver that will return a custom
// endpoint for EC2 IMDS. // endpoint for EC2 IMDS.
func wrapEC2IMDSEndpoint(resolver endpoints.Resolver, endpoint string) endpoints.Resolver { func wrapEC2IMDSEndpoint(resolver endpoints.Resolver, endpoint string, mode endpoints.EC2IMDSEndpointModeState) endpoints.Resolver {
return endpoints.ResolverFunc( return endpoints.ResolverFunc(
func(service, region string, opts ...func(*endpoints.Options)) ( func(service, region string, opts ...func(*endpoints.Options)) (
endpoints.ResolvedEndpoint, error, endpoints.ResolvedEndpoint, error,
) { ) {
if service == ec2MetadataServiceID { if service == ec2MetadataServiceID && len(endpoint) > 0 {
return endpoints.ResolvedEndpoint{ return endpoints.ResolvedEndpoint{
URL: endpoint, URL: endpoint,
SigningName: ec2MetadataServiceID, SigningName: ec2MetadataServiceID,
SigningRegion: region, SigningRegion: region,
}, nil }, nil
} else if service == ec2MetadataServiceID {
opts = append(opts, func(o *endpoints.Options) {
o.EC2MetadataEndpointMode = mode
})
} }
return resolver.EndpointFor(service, region) return resolver.EndpointFor(service, region, opts...)
}) })
} }
@ -404,8 +419,8 @@ func deprecatedNewSession(envCfg envConfig, cfgs ...*aws.Config) *Session {
cfg.EndpointResolver = endpoints.DefaultResolver() cfg.EndpointResolver = endpoints.DefaultResolver()
} }
if len(envCfg.EC2IMDSEndpoint) != 0 { if !(len(envCfg.EC2IMDSEndpoint) == 0 && envCfg.EC2IMDSEndpointMode == endpoints.EC2IMDSEndpointModeStateUnset) {
cfg.EndpointResolver = wrapEC2IMDSEndpoint(cfg.EndpointResolver, envCfg.EC2IMDSEndpoint) cfg.EndpointResolver = wrapEC2IMDSEndpoint(cfg.EndpointResolver, envCfg.EC2IMDSEndpoint, envCfg.EC2IMDSEndpointMode)
} }
cfg.Credentials = defaults.CredChain(cfg, handlers) cfg.Credentials = defaults.CredChain(cfg, handlers)
@ -737,12 +752,32 @@ func mergeConfigSrcs(cfg, userCfg *aws.Config,
endpoints.LegacyS3UsEast1Endpoint, endpoints.LegacyS3UsEast1Endpoint,
}) })
ec2IMDSEndpoint := sessOpts.EC2IMDSEndpoint var ec2IMDSEndpoint string
if len(ec2IMDSEndpoint) == 0 { for _, v := range []string{
ec2IMDSEndpoint = envCfg.EC2IMDSEndpoint sessOpts.EC2IMDSEndpoint,
envCfg.EC2IMDSEndpoint,
sharedCfg.EC2IMDSEndpoint,
} {
if len(v) != 0 {
ec2IMDSEndpoint = v
break
}
} }
if len(ec2IMDSEndpoint) != 0 {
cfg.EndpointResolver = wrapEC2IMDSEndpoint(cfg.EndpointResolver, ec2IMDSEndpoint) var endpointMode endpoints.EC2IMDSEndpointModeState
for _, v := range []endpoints.EC2IMDSEndpointModeState{
sessOpts.EC2IMDSEndpointMode,
envCfg.EC2IMDSEndpointMode,
sharedCfg.EC2IMDSEndpointMode,
} {
if v != endpoints.EC2IMDSEndpointModeStateUnset {
endpointMode = v
break
}
}
if len(ec2IMDSEndpoint) != 0 || endpointMode != endpoints.EC2IMDSEndpointModeStateUnset {
cfg.EndpointResolver = wrapEC2IMDSEndpoint(cfg.EndpointResolver, ec2IMDSEndpoint, endpointMode)
} }
// Configure credentials if not already set by the user when creating the // Configure credentials if not already set by the user when creating the
@ -763,6 +798,20 @@ func mergeConfigSrcs(cfg, userCfg *aws.Config,
cfg.S3UseARNRegion = &sharedCfg.S3UseARNRegion cfg.S3UseARNRegion = &sharedCfg.S3UseARNRegion
} }
for _, v := range []endpoints.DualStackEndpointState{userCfg.UseDualStackEndpoint, envCfg.UseDualStackEndpoint, sharedCfg.UseDualStackEndpoint} {
if v != endpoints.DualStackEndpointStateUnset {
cfg.UseDualStackEndpoint = v
break
}
}
for _, v := range []endpoints.FIPSEndpointState{userCfg.UseFIPSEndpoint, envCfg.UseFIPSEndpoint, sharedCfg.UseFIPSEndpoint} {
if v != endpoints.FIPSEndpointStateUnset {
cfg.UseFIPSEndpoint = v
break
}
}
return nil return nil
} }
@ -816,8 +865,10 @@ func (s *Session) Copy(cfgs ...*aws.Config) *Session {
func (s *Session) ClientConfig(service string, cfgs ...*aws.Config) client.Config { func (s *Session) ClientConfig(service string, cfgs ...*aws.Config) client.Config {
s = s.Copy(cfgs...) s = s.Copy(cfgs...)
resolvedRegion := normalizeRegion(s.Config)
region := aws.StringValue(s.Config.Region) region := aws.StringValue(s.Config.Region)
resolved, err := s.resolveEndpoint(service, region, s.Config) resolved, err := s.resolveEndpoint(service, region, resolvedRegion, s.Config)
if err != nil { if err != nil {
s.Handlers.Validate.PushBack(func(r *request.Request) { s.Handlers.Validate.PushBack(func(r *request.Request) {
if len(r.ClientInfo.Endpoint) != 0 { if len(r.ClientInfo.Endpoint) != 0 {
@ -838,12 +889,13 @@ func (s *Session) ClientConfig(service string, cfgs ...*aws.Config) client.Confi
SigningRegion: resolved.SigningRegion, SigningRegion: resolved.SigningRegion,
SigningNameDerived: resolved.SigningNameDerived, SigningNameDerived: resolved.SigningNameDerived,
SigningName: resolved.SigningName, SigningName: resolved.SigningName,
ResolvedRegion: resolvedRegion,
} }
} }
const ec2MetadataServiceID = "ec2metadata" const ec2MetadataServiceID = "ec2metadata"
func (s *Session) resolveEndpoint(service, region string, cfg *aws.Config) (endpoints.ResolvedEndpoint, error) { func (s *Session) resolveEndpoint(service, region, resolvedRegion string, cfg *aws.Config) (endpoints.ResolvedEndpoint, error) {
if ep := aws.StringValue(cfg.Endpoint); len(ep) != 0 { if ep := aws.StringValue(cfg.Endpoint); len(ep) != 0 {
return endpoints.ResolvedEndpoint{ return endpoints.ResolvedEndpoint{
@ -855,7 +907,12 @@ func (s *Session) resolveEndpoint(service, region string, cfg *aws.Config) (endp
resolved, err := cfg.EndpointResolver.EndpointFor(service, region, resolved, err := cfg.EndpointResolver.EndpointFor(service, region,
func(opt *endpoints.Options) { func(opt *endpoints.Options) {
opt.DisableSSL = aws.BoolValue(cfg.DisableSSL) opt.DisableSSL = aws.BoolValue(cfg.DisableSSL)
opt.UseDualStack = aws.BoolValue(cfg.UseDualStack) opt.UseDualStack = aws.BoolValue(cfg.UseDualStack)
opt.UseDualStackEndpoint = cfg.UseDualStackEndpoint
opt.UseFIPSEndpoint = cfg.UseFIPSEndpoint
// Support for STSRegionalEndpoint where the STSRegionalEndpoint is // Support for STSRegionalEndpoint where the STSRegionalEndpoint is
// provided in envConfig or sharedConfig with envConfig getting // provided in envConfig or sharedConfig with envConfig getting
// precedence. // precedence.
@ -869,6 +926,11 @@ func (s *Session) resolveEndpoint(service, region string, cfg *aws.Config) (endp
// Support the condition where the service is modeled but its // Support the condition where the service is modeled but its
// endpoint metadata is not available. // endpoint metadata is not available.
opt.ResolveUnknownService = true opt.ResolveUnknownService = true
opt.ResolvedRegion = resolvedRegion
opt.Logger = cfg.Logger
opt.LogDeprecated = cfg.LogLevel.Matches(aws.LogDebugWithDeprecated)
}, },
) )
if err != nil { if err != nil {
@ -884,6 +946,8 @@ func (s *Session) resolveEndpoint(service, region string, cfg *aws.Config) (endp
func (s *Session) ClientConfigNoResolveEndpoint(cfgs ...*aws.Config) client.Config { func (s *Session) ClientConfigNoResolveEndpoint(cfgs ...*aws.Config) client.Config {
s = s.Copy(cfgs...) s = s.Copy(cfgs...)
resolvedRegion := normalizeRegion(s.Config)
var resolved endpoints.ResolvedEndpoint var resolved endpoints.ResolvedEndpoint
if ep := aws.StringValue(s.Config.Endpoint); len(ep) > 0 { if ep := aws.StringValue(s.Config.Endpoint); len(ep) > 0 {
resolved.URL = endpoints.AddScheme(ep, aws.BoolValue(s.Config.DisableSSL)) resolved.URL = endpoints.AddScheme(ep, aws.BoolValue(s.Config.DisableSSL))
@ -897,6 +961,7 @@ func (s *Session) ClientConfigNoResolveEndpoint(cfgs ...*aws.Config) client.Conf
SigningRegion: resolved.SigningRegion, SigningRegion: resolved.SigningRegion,
SigningNameDerived: resolved.SigningNameDerived, SigningNameDerived: resolved.SigningNameDerived,
SigningName: resolved.SigningName, SigningName: resolved.SigningName,
ResolvedRegion: resolvedRegion,
} }
} }
@ -910,3 +975,23 @@ func (s *Session) logDeprecatedNewSessionError(msg string, err error, cfgs []*aw
r.Error = err r.Error = err
}) })
} }
// normalizeRegion resolves / normalizes the configured region (converts pseudo fips regions), and modifies the provided
// config to have the equivalent options for resolution and returns the resolved region name.
func normalizeRegion(cfg *aws.Config) (resolved string) {
const fipsInfix = "-fips-"
const fipsPrefix = "-fips"
const fipsSuffix = "fips-"
region := aws.StringValue(cfg.Region)
if strings.Contains(region, fipsInfix) ||
strings.Contains(region, fipsPrefix) ||
strings.Contains(region, fipsSuffix) {
resolved = strings.Replace(strings.Replace(strings.Replace(
region, fipsInfix, "-", -1), fipsPrefix, "", -1), fipsSuffix, "", -1)
cfg.UseFIPSEndpoint = endpoints.FIPSEndpointStateEnabled
}
return resolved
}

View File

@ -66,6 +66,18 @@ const (
// S3 ARN Region Usage // S3 ARN Region Usage
s3UseARNRegionKey = "s3_use_arn_region" s3UseARNRegionKey = "s3_use_arn_region"
// EC2 IMDS Endpoint Mode
ec2MetadataServiceEndpointModeKey = "ec2_metadata_service_endpoint_mode"
// EC2 IMDS Endpoint
ec2MetadataServiceEndpointKey = "ec2_metadata_service_endpoint"
// Use DualStack Endpoint Resolution
useDualStackEndpoint = "use_dualstack_endpoint"
// Use FIPS Endpoint Resolution
useFIPSEndpointKey = "use_fips_endpoint"
) )
// sharedConfig represents the configuration fields of the SDK config files. // sharedConfig represents the configuration fields of the SDK config files.
@ -145,6 +157,28 @@ type sharedConfig struct {
// //
// s3_use_arn_region=true // s3_use_arn_region=true
S3UseARNRegion bool S3UseARNRegion bool
// Specifies the EC2 Instance Metadata Service default endpoint selection mode (IPv4 or IPv6)
//
// ec2_metadata_service_endpoint_mode=IPv6
EC2IMDSEndpointMode endpoints.EC2IMDSEndpointModeState
// Specifies the EC2 Instance Metadata Service endpoint to use. If specified it overrides EC2IMDSEndpointMode.
//
// ec2_metadata_service_endpoint=http://fd00:ec2::254
EC2IMDSEndpoint string
// Specifies that SDK clients must resolve a dual-stack endpoint for
// services.
//
// use_dualstack_endpoint=true
UseDualStackEndpoint endpoints.DualStackEndpointState
// Specifies that SDK clients must resolve a FIPS endpoint for
// services.
//
// use_fips_endpoint=true
UseFIPSEndpoint endpoints.FIPSEndpointState
} }
type sharedConfigFile struct { type sharedConfigFile struct {
@ -334,6 +368,16 @@ func (cfg *sharedConfig) setFromIniFile(profile string, file sharedConfigFile, e
updateString(&cfg.SSORegion, section, ssoRegionKey) updateString(&cfg.SSORegion, section, ssoRegionKey)
updateString(&cfg.SSORoleName, section, ssoRoleNameKey) updateString(&cfg.SSORoleName, section, ssoRoleNameKey)
updateString(&cfg.SSOStartURL, section, ssoStartURL) updateString(&cfg.SSOStartURL, section, ssoStartURL)
if err := updateEC2MetadataServiceEndpointMode(&cfg.EC2IMDSEndpointMode, section, ec2MetadataServiceEndpointModeKey); err != nil {
return fmt.Errorf("failed to load %s from shared config, %s, %v",
ec2MetadataServiceEndpointModeKey, file.Filename, err)
}
updateString(&cfg.EC2IMDSEndpoint, section, ec2MetadataServiceEndpointKey)
updateUseDualStackEndpoint(&cfg.UseDualStackEndpoint, section, useDualStackEndpoint)
updateUseFIPSEndpoint(&cfg.UseFIPSEndpoint, section, useFIPSEndpointKey)
} }
updateString(&cfg.CredentialProcess, section, credentialProcessKey) updateString(&cfg.CredentialProcess, section, credentialProcessKey)
@ -364,6 +408,14 @@ func (cfg *sharedConfig) setFromIniFile(profile string, file sharedConfigFile, e
return nil return nil
} }
func updateEC2MetadataServiceEndpointMode(endpointMode *endpoints.EC2IMDSEndpointModeState, section ini.Section, key string) error {
if !section.Has(key) {
return nil
}
value := section.String(key)
return endpointMode.SetFromString(value)
}
func (cfg *sharedConfig) validateCredentialsConfig(profile string) error { func (cfg *sharedConfig) validateCredentialsConfig(profile string) error {
if err := cfg.validateCredentialsRequireARN(profile); err != nil { if err := cfg.validateCredentialsRequireARN(profile); err != nil {
return err return err
@ -643,3 +695,35 @@ func (e CredentialRequiresARNError) OrigErr() error {
func (e CredentialRequiresARNError) Error() string { func (e CredentialRequiresARNError) Error() string {
return awserr.SprintError(e.Code(), e.Message(), "", nil) return awserr.SprintError(e.Code(), e.Message(), "", nil)
} }
// updateEndpointDiscoveryType will only update the dst with the value in the section, if
// a valid key and corresponding EndpointDiscoveryType is found.
func updateUseDualStackEndpoint(dst *endpoints.DualStackEndpointState, section ini.Section, key string) {
if !section.Has(key) {
return
}
if section.Bool(key) {
*dst = endpoints.DualStackEndpointStateEnabled
} else {
*dst = endpoints.DualStackEndpointStateDisabled
}
return
}
// updateEndpointDiscoveryType will only update the dst with the value in the section, if
// a valid key and corresponding EndpointDiscoveryType is found.
func updateUseFIPSEndpoint(dst *endpoints.FIPSEndpointState, section ini.Section, key string) {
if !section.Has(key) {
return
}
if section.Bool(key) {
*dst = endpoints.FIPSEndpointStateEnabled
} else {
*dst = endpoints.FIPSEndpointStateDisabled
}
return
}

View File

@ -34,23 +34,23 @@ func (m mapRule) IsValid(value string) bool {
return ok return ok
} }
// whitelist is a generic rule for whitelisting // allowList is a generic rule for allow listing
type whitelist struct { type allowList struct {
rule rule
} }
// IsValid for whitelist checks if the value is within the whitelist // IsValid for allow list checks if the value is within the allow list
func (w whitelist) IsValid(value string) bool { func (w allowList) IsValid(value string) bool {
return w.rule.IsValid(value) return w.rule.IsValid(value)
} }
// blacklist is a generic rule for blacklisting // excludeList is a generic rule for exclude listing
type blacklist struct { type excludeList struct {
rule rule
} }
// IsValid for whitelist checks if the value is within the whitelist // IsValid for exclude list checks if the value is within the exclude list
func (b blacklist) IsValid(value string) bool { func (b excludeList) IsValid(value string) bool {
return !b.rule.IsValid(value) return !b.rule.IsValid(value)
} }

View File

@ -1,3 +1,4 @@
//go:build !go1.7
// +build !go1.7 // +build !go1.7
package v4 package v4

View File

@ -1,3 +1,4 @@
//go:build go1.7
// +build go1.7 // +build go1.7
package v4 package v4

View File

@ -1,3 +1,4 @@
//go:build go1.5
// +build go1.5 // +build go1.5
package v4 package v4

View File

@ -90,7 +90,7 @@ const (
) )
var ignoredHeaders = rules{ var ignoredHeaders = rules{
blacklist{ excludeList{
mapRule{ mapRule{
authorizationHeader: struct{}{}, authorizationHeader: struct{}{},
"User-Agent": struct{}{}, "User-Agent": struct{}{},
@ -99,9 +99,9 @@ var ignoredHeaders = rules{
}, },
} }
// requiredSignedHeaders is a whitelist for build canonical headers. // requiredSignedHeaders is a allow list for build canonical headers.
var requiredSignedHeaders = rules{ var requiredSignedHeaders = rules{
whitelist{ allowList{
mapRule{ mapRule{
"Cache-Control": struct{}{}, "Cache-Control": struct{}{},
"Content-Disposition": struct{}{}, "Content-Disposition": struct{}{},
@ -145,12 +145,13 @@ var requiredSignedHeaders = rules{
}, },
}, },
patterns{"X-Amz-Meta-"}, patterns{"X-Amz-Meta-"},
patterns{"X-Amz-Object-Lock-"},
} }
// allowedHoisting is a whitelist for build query headers. The boolean value // allowedHoisting is a allow list for build query headers. The boolean value
// represents whether or not it is a pattern. // represents whether or not it is a pattern.
var allowedQueryHoisting = inclusiveRules{ var allowedQueryHoisting = inclusiveRules{
blacklist{requiredSignedHeaders}, excludeList{requiredSignedHeaders},
patterns{"X-Amz-"}, patterns{"X-Amz-"},
} }
@ -417,7 +418,7 @@ var SignRequestHandler = request.NamedHandler{
// request handler should only be used with the SDK's built in service client's // request handler should only be used with the SDK's built in service client's
// API operation requests. // API operation requests.
// //
// This function should not be used on its on its own, but in conjunction with // This function should not be used on its own, but in conjunction with
// an AWS service client's API operation call. To sign a standalone request // an AWS service client's API operation call. To sign a standalone request
// not created by a service client's API operation method use the "Sign" or // not created by a service client's API operation method use the "Sign" or
// "Presign" functions of the "Signer" type. // "Presign" functions of the "Signer" type.
@ -633,21 +634,25 @@ func (ctx *signingCtx) buildCanonicalHeaders(r rule, header http.Header) {
ctx.Query.Set("X-Amz-SignedHeaders", ctx.signedHeaders) ctx.Query.Set("X-Amz-SignedHeaders", ctx.signedHeaders)
} }
headerValues := make([]string, len(headers)) headerItems := make([]string, len(headers))
for i, k := range headers { for i, k := range headers {
if k == "host" { if k == "host" {
if ctx.Request.Host != "" { if ctx.Request.Host != "" {
headerValues[i] = "host:" + ctx.Request.Host headerItems[i] = "host:" + ctx.Request.Host
} else { } else {
headerValues[i] = "host:" + ctx.Request.URL.Host headerItems[i] = "host:" + ctx.Request.URL.Host
} }
} else { } else {
headerValues[i] = k + ":" + headerValues := make([]string, len(ctx.SignedHeaderVals[k]))
strings.Join(ctx.SignedHeaderVals[k], ",") for i, v := range ctx.SignedHeaderVals[k] {
headerValues[i] = strings.TrimSpace(v)
}
headerItems[i] = k + ":" +
strings.Join(headerValues, ",")
} }
} }
stripExcessSpaces(headerValues) stripExcessSpaces(headerItems)
ctx.canonicalHeaders = strings.Join(headerValues, "\n") ctx.canonicalHeaders = strings.Join(headerItems, "\n")
} }
func (ctx *signingCtx) buildCanonicalString() { func (ctx *signingCtx) buildCanonicalString() {

View File

@ -1,3 +1,4 @@
//go:build go1.8
// +build go1.8 // +build go1.8
package aws package aws

View File

@ -1,3 +1,4 @@
//go:build !go1.8
// +build !go1.8 // +build !go1.8
package aws package aws

View File

@ -5,4 +5,4 @@ package aws
const SDKName = "aws-sdk-go" const SDKName = "aws-sdk-go"
// SDKVersion is the version of this SDK // SDKVersion is the version of this SDK
const SDKVersion = "1.38.49" const SDKVersion = "1.44.116"

View File

@ -1,3 +1,4 @@
//go:build !go1.7
// +build !go1.7 // +build !go1.7
package context package context

View File

@ -13,17 +13,30 @@
// } // }
// //
// Below is the BNF that describes this parser // Below is the BNF that describes this parser
// Grammar: // Grammar:
// stmt -> value stmt' // stmt -> section | stmt'
// stmt' -> epsilon | op stmt // stmt' -> epsilon | expr
// value -> number | string | boolean | quoted_string // expr -> value (stmt)* | equal_expr (stmt)*
// equal_expr -> value ( ':' | '=' ) equal_expr'
// equal_expr' -> number | string | quoted_string
// quoted_string -> " quoted_string'
// quoted_string' -> string quoted_string_end
// quoted_string_end -> "
// //
// section -> [ section' // section -> [ section'
// section' -> value section_close // section' -> section_value section_close
// section_close -> ] // section_value -> number | string_subset | boolean | quoted_string_subset
// quoted_string_subset -> " quoted_string_subset'
// quoted_string_subset' -> string_subset quoted_string_end
// quoted_string_subset -> "
// section_close -> ]
// //
// SkipState will skip (NL WS)+ // value -> number | string_subset | boolean
// string -> ? UTF-8 Code-Points except '\n' (U+000A) and '\r\n' (U+000D U+000A) ?
// string_subset -> ? Code-points excepted by <string> grammar except ':' (U+003A), '=' (U+003D), '[' (U+005B), and ']' (U+005D) ?
// //
// comment -> # comment' | ; comment' // SkipState will skip (NL WS)+
// comment' -> epsilon | value //
// comment -> # comment' | ; comment'
// comment' -> epsilon | value
package ini package ini

View File

@ -1,3 +1,4 @@
//go:build gofuzz
// +build gofuzz // +build gofuzz
package ini package ini

View File

@ -5,9 +5,12 @@ import (
"io" "io"
) )
// ParseState represents the current state of the parser.
type ParseState uint
// State enums for the parse table // State enums for the parse table
const ( const (
InvalidState = iota InvalidState ParseState = iota
// stmt -> value stmt' // stmt -> value stmt'
StatementState StatementState
// stmt' -> MarkComplete | op stmt // stmt' -> MarkComplete | op stmt
@ -36,8 +39,8 @@ const (
) )
// parseTable is a state machine to dictate the grammar above. // parseTable is a state machine to dictate the grammar above.
var parseTable = map[ASTKind]map[TokenType]int{ var parseTable = map[ASTKind]map[TokenType]ParseState{
ASTKindStart: map[TokenType]int{ ASTKindStart: {
TokenLit: StatementState, TokenLit: StatementState,
TokenSep: OpenScopeState, TokenSep: OpenScopeState,
TokenWS: SkipTokenState, TokenWS: SkipTokenState,
@ -45,7 +48,7 @@ var parseTable = map[ASTKind]map[TokenType]int{
TokenComment: CommentState, TokenComment: CommentState,
TokenNone: TerminalState, TokenNone: TerminalState,
}, },
ASTKindCommentStatement: map[TokenType]int{ ASTKindCommentStatement: {
TokenLit: StatementState, TokenLit: StatementState,
TokenSep: OpenScopeState, TokenSep: OpenScopeState,
TokenWS: SkipTokenState, TokenWS: SkipTokenState,
@ -53,7 +56,7 @@ var parseTable = map[ASTKind]map[TokenType]int{
TokenComment: CommentState, TokenComment: CommentState,
TokenNone: MarkCompleteState, TokenNone: MarkCompleteState,
}, },
ASTKindExpr: map[TokenType]int{ ASTKindExpr: {
TokenOp: StatementPrimeState, TokenOp: StatementPrimeState,
TokenLit: ValueState, TokenLit: ValueState,
TokenSep: OpenScopeState, TokenSep: OpenScopeState,
@ -62,13 +65,15 @@ var parseTable = map[ASTKind]map[TokenType]int{
TokenComment: CommentState, TokenComment: CommentState,
TokenNone: MarkCompleteState, TokenNone: MarkCompleteState,
}, },
ASTKindEqualExpr: map[TokenType]int{ ASTKindEqualExpr: {
TokenLit: ValueState, TokenLit: ValueState,
TokenWS: SkipTokenState, TokenSep: ValueState,
TokenNL: SkipState, TokenOp: ValueState,
TokenNone: SkipState, TokenWS: SkipTokenState,
TokenNL: SkipState,
TokenNone: SkipState,
}, },
ASTKindStatement: map[TokenType]int{ ASTKindStatement: {
TokenLit: SectionState, TokenLit: SectionState,
TokenSep: CloseScopeState, TokenSep: CloseScopeState,
TokenWS: SkipTokenState, TokenWS: SkipTokenState,
@ -76,9 +81,9 @@ var parseTable = map[ASTKind]map[TokenType]int{
TokenComment: CommentState, TokenComment: CommentState,
TokenNone: MarkCompleteState, TokenNone: MarkCompleteState,
}, },
ASTKindExprStatement: map[TokenType]int{ ASTKindExprStatement: {
TokenLit: ValueState, TokenLit: ValueState,
TokenSep: OpenScopeState, TokenSep: ValueState,
TokenOp: ValueState, TokenOp: ValueState,
TokenWS: ValueState, TokenWS: ValueState,
TokenNL: MarkCompleteState, TokenNL: MarkCompleteState,
@ -86,14 +91,14 @@ var parseTable = map[ASTKind]map[TokenType]int{
TokenNone: TerminalState, TokenNone: TerminalState,
TokenComma: SkipState, TokenComma: SkipState,
}, },
ASTKindSectionStatement: map[TokenType]int{ ASTKindSectionStatement: {
TokenLit: SectionState, TokenLit: SectionState,
TokenOp: SectionState, TokenOp: SectionState,
TokenSep: CloseScopeState, TokenSep: CloseScopeState,
TokenWS: SectionState, TokenWS: SectionState,
TokenNL: SkipTokenState, TokenNL: SkipTokenState,
}, },
ASTKindCompletedSectionStatement: map[TokenType]int{ ASTKindCompletedSectionStatement: {
TokenWS: SkipTokenState, TokenWS: SkipTokenState,
TokenNL: SkipTokenState, TokenNL: SkipTokenState,
TokenLit: StatementState, TokenLit: StatementState,
@ -101,7 +106,7 @@ var parseTable = map[ASTKind]map[TokenType]int{
TokenComment: CommentState, TokenComment: CommentState,
TokenNone: MarkCompleteState, TokenNone: MarkCompleteState,
}, },
ASTKindSkipStatement: map[TokenType]int{ ASTKindSkipStatement: {
TokenLit: StatementState, TokenLit: StatementState,
TokenSep: OpenScopeState, TokenSep: OpenScopeState,
TokenWS: SkipTokenState, TokenWS: SkipTokenState,
@ -205,18 +210,6 @@ loop:
case ValueState: case ValueState:
// ValueState requires the previous state to either be an equal expression // ValueState requires the previous state to either be an equal expression
// or an expression statement. // or an expression statement.
//
// This grammar occurs when the RHS is a number, word, or quoted string.
// equal_expr -> lit op equal_expr'
// equal_expr' -> number | string | quoted_string
// quoted_string -> " quoted_string'
// quoted_string' -> string quoted_string_end
// quoted_string_end -> "
//
// otherwise
// expr_stmt -> equal_expr (expr_stmt')*
// expr_stmt' -> ws S | op S | MarkComplete
// S -> equal_expr' expr_stmt'
switch k.Kind { switch k.Kind {
case ASTKindEqualExpr: case ASTKindEqualExpr:
// assigning a value to some key // assigning a value to some key
@ -243,7 +236,7 @@ loop:
} }
children[len(children)-1] = rhs children[len(children)-1] = rhs
k.SetChildren(children) root.SetChildren(children)
stack.Push(k) stack.Push(k)
} }

View File

@ -4,6 +4,7 @@ import (
"fmt" "fmt"
"strconv" "strconv"
"strings" "strings"
"unicode"
) )
var ( var (
@ -18,7 +19,7 @@ var literalValues = [][]rune{
func isBoolValue(b []rune) bool { func isBoolValue(b []rune) bool {
for _, lv := range literalValues { for _, lv := range literalValues {
if isLitValue(lv, b) { if isCaselessLitValue(lv, b) {
return true return true
} }
} }
@ -39,6 +40,21 @@ func isLitValue(want, have []rune) bool {
return true return true
} }
// isCaselessLitValue is a caseless value comparison, assumes want is already lower-cased for efficiency.
func isCaselessLitValue(want, have []rune) bool {
if len(have) < len(want) {
return false
}
for i := 0; i < len(want); i++ {
if want[i] != unicode.ToLower(have[i]) {
return false
}
}
return true
}
// isNumberValue will return whether not the leading characters in // isNumberValue will return whether not the leading characters in
// a byte slice is a number. A number is delimited by whitespace or // a byte slice is a number. A number is delimited by whitespace or
// the newline token. // the newline token.
@ -177,7 +193,7 @@ func newValue(t ValueType, base int, raw []rune) (Value, error) {
case QuotedStringType: case QuotedStringType:
v.str = string(raw[1 : len(raw)-1]) v.str = string(raw[1 : len(raw)-1])
case BoolType: case BoolType:
v.boolean = runeCompare(v.raw, runesTrue) v.boolean = isCaselessLitValue(runesTrue, v.raw)
} }
// issue 2253 // issue 2253

View File

@ -57,7 +57,7 @@ func getBoolValue(b []rune) (int, error) {
continue continue
} }
if isLitValue(lv, b) { if isCaselessLitValue(lv, b) {
n = len(lv) n = len(lv)
} }
} }

View File

@ -50,7 +50,10 @@ func (v *DefaultVisitor) VisitExpr(expr AST) error {
rhs := children[1] rhs := children[1]
if rhs.Root.Type() != TokenLit { // The right-hand value side the equality expression is allowed to contain '[', ']', ':', '=' in the values.
// If the token is not either a literal or one of the token types that identifies those four additional
// tokens then error.
if !(rhs.Root.Type() == TokenLit || rhs.Root.Type() == TokenOp || rhs.Root.Type() == TokenSep) {
return NewParseError("unexpected token type") return NewParseError("unexpected token type")
} }

View File

@ -1,3 +1,4 @@
//go:build !go1.7
// +build !go1.7 // +build !go1.7
package sdkio package sdkio

View File

@ -1,3 +1,4 @@
//go:build go1.7
// +build go1.7 // +build go1.7
package sdkio package sdkio

View File

@ -1,3 +1,4 @@
//go:build go1.10
// +build go1.10 // +build go1.10
package sdkmath package sdkmath

View File

@ -1,3 +1,4 @@
//go:build !go1.10
// +build !go1.10 // +build !go1.10
package sdkmath package sdkmath

View File

@ -1,3 +1,4 @@
//go:build go1.6
// +build go1.6 // +build go1.6
package sdkrand package sdkrand

View File

@ -1,3 +1,4 @@
//go:build !go1.6
// +build !go1.6 // +build !go1.6
package sdkrand package sdkrand

View File

@ -4,6 +4,7 @@ package ec2query
import ( import (
"encoding/xml" "encoding/xml"
"strings"
"github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/aws/request"
@ -70,7 +71,7 @@ func UnmarshalError(r *request.Request) {
} }
r.Error = awserr.NewRequestFailure( r.Error = awserr.NewRequestFailure(
awserr.New(respErr.Code, respErr.Message, nil), awserr.New(strings.TrimSpace(respErr.Code), strings.TrimSpace(respErr.Message), nil),
r.HTTPResponse.StatusCode, r.HTTPResponse.StatusCode,
respErr.RequestID, respErr.RequestID,
) )

View File

@ -82,13 +82,17 @@ func buildStruct(value reflect.Value, buf *bytes.Buffer, tag reflect.StructTag)
field, _ := value.Type().FieldByName(payload) field, _ := value.Type().FieldByName(payload)
tag = field.Tag tag = field.Tag
value = elemOf(value.FieldByName(payload)) value = elemOf(value.FieldByName(payload))
if !value.IsValid() && tag.Get("type") != "structure" {
if !value.IsValid() {
return nil return nil
} }
} }
buf.WriteByte('{') buf.WriteByte('{')
defer buf.WriteString("}")
if !value.IsValid() {
return nil
}
t := value.Type() t := value.Type()
first := true first := true
@ -144,8 +148,6 @@ func buildStruct(value reflect.Value, buf *bytes.Buffer, tag reflect.StructTag)
} }
buf.WriteString("}")
return nil return nil
} }

View File

@ -49,9 +49,8 @@ func Build(req *request.Request) {
buf = emptyJSON buf = emptyJSON
} }
if req.ClientInfo.TargetPrefix != "" || string(buf) != "{}" { // Always serialize the body, don't suppress it.
req.SetBufferBody(buf) req.SetBufferBody(buf)
}
if req.ClientInfo.TargetPrefix != "" { if req.ClientInfo.TargetPrefix != "" {
target := req.ClientInfo.TargetPrefix + "." + req.Operation.Name target := req.ClientInfo.TargetPrefix + "." + req.Operation.Name

View File

@ -3,6 +3,7 @@ package query
import ( import (
"encoding/xml" "encoding/xml"
"fmt" "fmt"
"strings"
"github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/aws/request"
@ -62,7 +63,7 @@ func UnmarshalError(r *request.Request) {
} }
r.Error = awserr.NewRequestFailure( r.Error = awserr.NewRequestFailure(
awserr.New(respErr.Code, respErr.Message, nil), awserr.New(strings.TrimSpace(respErr.Code), strings.TrimSpace(respErr.Message), nil),
r.HTTPResponse.StatusCode, r.HTTPResponse.StatusCode,
reqID, reqID,
) )

View File

@ -98,7 +98,7 @@ func buildLocationElements(r *request.Request, v reflect.Value, buildGETQuery bo
// Support the ability to customize values to be marshaled as a // Support the ability to customize values to be marshaled as a
// blob even though they were modeled as a string. Required for S3 // blob even though they were modeled as a string. Required for S3
// API operations like SSECustomerKey is modeled as stirng but // API operations like SSECustomerKey is modeled as string but
// required to be base64 encoded in request. // required to be base64 encoded in request.
if field.Tag.Get("marshal-as") == "blob" { if field.Tag.Get("marshal-as") == "blob" {
m = m.Convert(byteSliceType) m = m.Convert(byteSliceType)
@ -272,7 +272,29 @@ func convertType(v reflect.Value, tag reflect.StructTag) (str string, err error)
switch value := v.Interface().(type) { switch value := v.Interface().(type) {
case string: case string:
if tag.Get("suppressedJSONValue") == "true" && tag.Get("location") == "header" {
value = base64.StdEncoding.EncodeToString([]byte(value))
}
str = value str = value
case []*string:
if tag.Get("location") != "header" || tag.Get("enum") == "" {
return "", fmt.Errorf("%T is only supported with location header and enum shapes", value)
}
buff := &bytes.Buffer{}
for i, sv := range value {
if sv == nil || len(*sv) == 0 {
continue
}
if i != 0 {
buff.WriteRune(',')
}
item := *sv
if strings.Index(item, `,`) != -1 || strings.Index(item, `"`) != -1 {
item = strconv.Quote(item)
}
buff.WriteString(item)
}
str = string(buff.Bytes())
case []byte: case []byte:
str = base64.StdEncoding.EncodeToString(value) str = base64.StdEncoding.EncodeToString(value)
case bool: case bool:
@ -306,5 +328,6 @@ func convertType(v reflect.Value, tag reflect.StructTag) (str string, err error)
err := fmt.Errorf("unsupported value for param %v (%s)", v.Interface(), v.Type()) err := fmt.Errorf("unsupported value for param %v (%s)", v.Interface(), v.Type())
return "", err return "", err
} }
return str, nil return str, nil
} }

View File

@ -28,18 +28,27 @@ func PayloadMember(i interface{}) interface{} {
return nil return nil
} }
// PayloadType returns the type of a payload field member of i if there is one, or "". const nopayloadPayloadType = "nopayload"
// PayloadType returns the type of a payload field member of i if there is one,
// or "".
func PayloadType(i interface{}) string { func PayloadType(i interface{}) string {
v := reflect.Indirect(reflect.ValueOf(i)) v := reflect.Indirect(reflect.ValueOf(i))
if !v.IsValid() { if !v.IsValid() {
return "" return ""
} }
if field, ok := v.Type().FieldByName("_"); ok { if field, ok := v.Type().FieldByName("_"); ok {
if noPayload := field.Tag.Get(nopayloadPayloadType); noPayload != "" {
return nopayloadPayloadType
}
if payloadName := field.Tag.Get("payload"); payloadName != "" { if payloadName := field.Tag.Get("payload"); payloadName != "" {
if member, ok := v.Type().FieldByName(payloadName); ok { if member, ok := v.Type().FieldByName(payloadName); ok {
return member.Tag.Get("type") return member.Tag.Get("type")
} }
} }
} }
return "" return ""
} }

View File

@ -140,7 +140,7 @@ func unmarshalLocationElements(resp *http.Response, v reflect.Value, lowerCaseHe
prefix := field.Tag.Get("locationName") prefix := field.Tag.Get("locationName")
err := unmarshalHeaderMap(m, resp.Header, prefix, lowerCaseHeaderMaps) err := unmarshalHeaderMap(m, resp.Header, prefix, lowerCaseHeaderMaps)
if err != nil { if err != nil {
awserr.New(request.ErrCodeSerialization, "failed to decode REST response", err) return awserr.New(request.ErrCodeSerialization, "failed to decode REST response", err)
} }
} }
} }
@ -204,6 +204,13 @@ func unmarshalHeader(v reflect.Value, header string, tag reflect.StructTag) erro
switch v.Interface().(type) { switch v.Interface().(type) {
case *string: case *string:
if tag.Get("suppressedJSONValue") == "true" && tag.Get("location") == "header" {
b, err := base64.StdEncoding.DecodeString(header)
if err != nil {
return fmt.Errorf("failed to decode JSONValue, %v", err)
}
header = string(b)
}
v.Set(reflect.ValueOf(&header)) v.Set(reflect.ValueOf(&header))
case []byte: case []byte:
b, err := base64.StdEncoding.DecodeString(header) b, err := base64.StdEncoding.DecodeString(header)

View File

@ -1,6 +1,8 @@
package protocol package protocol
import ( import (
"bytes"
"fmt"
"math" "math"
"strconv" "strconv"
"time" "time"
@ -19,13 +21,16 @@ const (
// Output time is intended to not contain decimals // Output time is intended to not contain decimals
const ( const (
// RFC 7231#section-7.1.1.1 timetamp format. e.g Tue, 29 Apr 2014 18:30:38 GMT // RFC 7231#section-7.1.1.1 timetamp format. e.g Tue, 29 Apr 2014 18:30:38 GMT
RFC822TimeFormat = "Mon, 2 Jan 2006 15:04:05 GMT" RFC822TimeFormat = "Mon, 2 Jan 2006 15:04:05 GMT"
rfc822TimeFormatSingleDigitDay = "Mon, _2 Jan 2006 15:04:05 GMT"
rfc822TimeFormatSingleDigitDayTwoDigitYear = "Mon, _2 Jan 06 15:04:05 GMT"
// This format is used for output time without seconds precision // This format is used for output time without seconds precision
RFC822OutputTimeFormat = "Mon, 02 Jan 2006 15:04:05 GMT" RFC822OutputTimeFormat = "Mon, 02 Jan 2006 15:04:05 GMT"
// RFC3339 a subset of the ISO8601 timestamp format. e.g 2014-04-29T18:30:38Z // RFC3339 a subset of the ISO8601 timestamp format. e.g 2014-04-29T18:30:38Z
ISO8601TimeFormat = "2006-01-02T15:04:05.999999999Z" ISO8601TimeFormat = "2006-01-02T15:04:05.999999999Z"
iso8601TimeFormatNoZ = "2006-01-02T15:04:05.999999999"
// This format is used for output time with fractional second precision up to milliseconds // This format is used for output time with fractional second precision up to milliseconds
ISO8601OutputTimeFormat = "2006-01-02T15:04:05.999999999Z" ISO8601OutputTimeFormat = "2006-01-02T15:04:05.999999999Z"
@ -67,10 +72,21 @@ func FormatTime(name string, t time.Time) string {
// the time if it was able to be parsed, and fails otherwise. // the time if it was able to be parsed, and fails otherwise.
func ParseTime(formatName, value string) (time.Time, error) { func ParseTime(formatName, value string) (time.Time, error) {
switch formatName { switch formatName {
case RFC822TimeFormatName: case RFC822TimeFormatName: // Smithy HTTPDate format
return time.Parse(RFC822TimeFormat, value) return tryParse(value,
case ISO8601TimeFormatName: RFC822TimeFormat,
return time.Parse(ISO8601TimeFormat, value) rfc822TimeFormatSingleDigitDay,
rfc822TimeFormatSingleDigitDayTwoDigitYear,
time.RFC850,
time.ANSIC,
)
case ISO8601TimeFormatName: // Smithy DateTime format
return tryParse(value,
ISO8601TimeFormat,
iso8601TimeFormatNoZ,
time.RFC3339Nano,
time.RFC3339,
)
case UnixTimeFormatName: case UnixTimeFormatName:
v, err := strconv.ParseFloat(value, 64) v, err := strconv.ParseFloat(value, 64)
_, dec := math.Modf(v) _, dec := math.Modf(v)
@ -83,3 +99,36 @@ func ParseTime(formatName, value string) (time.Time, error) {
panic("unknown timestamp format name, " + formatName) panic("unknown timestamp format name, " + formatName)
} }
} }
func tryParse(v string, formats ...string) (time.Time, error) {
var errs parseErrors
for _, f := range formats {
t, err := time.Parse(f, v)
if err != nil {
errs = append(errs, parseError{
Format: f,
Err: err,
})
continue
}
return t, nil
}
return time.Time{}, fmt.Errorf("unable to parse time string, %v", errs)
}
type parseErrors []parseError
func (es parseErrors) Error() string {
var s bytes.Buffer
for _, e := range es {
fmt.Fprintf(&s, "\n * %q: %v", e.Format, e.Err)
}
return "parse errors:" + s.String()
}
type parseError struct {
Format string
Err error
}

File diff suppressed because it is too large Load Diff

View File

@ -3,23 +3,19 @@
// Package autoscaling provides the client and types for making API // Package autoscaling provides the client and types for making API
// requests to Auto Scaling. // requests to Auto Scaling.
// //
// Amazon EC2 Auto Scaling is designed to automatically launch or terminate // Amazon EC2 Auto Scaling is designed to automatically launch and terminate
// EC2 instances based on user-defined scaling policies, scheduled actions, // EC2 instances based on user-defined scaling policies, scheduled actions,
// and health checks. // and health checks.
// //
// For more information about Amazon EC2 Auto Scaling, see the Amazon EC2 Auto // For more information, see the Amazon EC2 Auto Scaling User Guide (https://docs.aws.amazon.com/autoscaling/ec2/userguide/)
// Scaling User Guide (https://docs.aws.amazon.com/autoscaling/ec2/userguide/what-is-amazon-ec2-auto-scaling.html). // and the Amazon EC2 Auto Scaling API Reference (https://docs.aws.amazon.com/autoscaling/ec2/APIReference/Welcome.html).
// For information about granting IAM users required permissions for calls to
// Amazon EC2 Auto Scaling, see Granting IAM users required permissions for
// Amazon EC2 Auto Scaling resources (https://docs.aws.amazon.com/autoscaling/ec2/APIReference/ec2-auto-scaling-api-permissions.html)
// in the Amazon EC2 Auto Scaling API Reference.
// //
// See https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01 for more information on this service. // See https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01 for more information on this service.
// //
// See autoscaling package documentation for more information. // See autoscaling package documentation for more information.
// https://docs.aws.amazon.com/sdk-for-go/api/service/autoscaling/ // https://docs.aws.amazon.com/sdk-for-go/api/service/autoscaling/
// //
// Using the Client // # Using the Client
// //
// To contact Auto Scaling with the SDK use the New function to create // To contact Auto Scaling with the SDK use the New function to create
// a new service client. With that client you can make API requests to the service. // a new service client. With that client you can make API requests to the service.

View File

@ -39,31 +39,37 @@ const (
// aws.Config parameter to add your extra config. // aws.Config parameter to add your extra config.
// //
// Example: // Example:
// mySession := session.Must(session.NewSession())
// //
// // Create a AutoScaling client from just a session. // mySession := session.Must(session.NewSession())
// svc := autoscaling.New(mySession)
// //
// // Create a AutoScaling client with additional configuration // // Create a AutoScaling client from just a session.
// svc := autoscaling.New(mySession, aws.NewConfig().WithRegion("us-west-2")) // svc := autoscaling.New(mySession)
//
// // Create a AutoScaling client with additional configuration
// svc := autoscaling.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func New(p client.ConfigProvider, cfgs ...*aws.Config) *AutoScaling { func New(p client.ConfigProvider, cfgs ...*aws.Config) *AutoScaling {
c := p.ClientConfig(EndpointsID, cfgs...) c := p.ClientConfig(EndpointsID, cfgs...)
return newClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName) if c.SigningNameDerived || len(c.SigningName) == 0 {
c.SigningName = EndpointsID
// No Fallback
}
return newClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName, c.ResolvedRegion)
} }
// newClient creates, initializes and returns a new service client instance. // newClient creates, initializes and returns a new service client instance.
func newClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *AutoScaling { func newClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName, resolvedRegion string) *AutoScaling {
svc := &AutoScaling{ svc := &AutoScaling{
Client: client.New( Client: client.New(
cfg, cfg,
metadata.ClientInfo{ metadata.ClientInfo{
ServiceName: ServiceName, ServiceName: ServiceName,
ServiceID: ServiceID, ServiceID: ServiceID,
SigningName: signingName, SigningName: signingName,
SigningRegion: signingRegion, SigningRegion: signingRegion,
PartitionID: partitionID, PartitionID: partitionID,
Endpoint: endpoint, Endpoint: endpoint,
APIVersion: "2011-01-01", APIVersion: "2011-01-01",
ResolvedRegion: resolvedRegion,
}, },
handlers, handlers,
), ),

File diff suppressed because it is too large Load Diff

View File

@ -68,6 +68,10 @@ func fillPresignedURL(r *request.Request) {
func(opt *endpoints.Options) { func(opt *endpoints.Options) {
opt.DisableSSL = aws.BoolValue(cfg.DisableSSL) opt.DisableSSL = aws.BoolValue(cfg.DisableSSL)
opt.UseDualStack = aws.BoolValue(cfg.UseDualStack) opt.UseDualStack = aws.BoolValue(cfg.UseDualStack)
opt.UseDualStackEndpoint = cfg.UseDualStackEndpoint
opt.UseFIPSEndpoint = cfg.UseFIPSEndpoint
opt.Logger = r.Config.Logger
opt.LogDeprecated = r.Config.LogLevel.Matches(aws.LogDebugWithDeprecated)
}, },
) )
if err != nil { if err != nil {

View File

@ -4,35 +4,36 @@
// requests to Amazon Elastic Compute Cloud. // requests to Amazon Elastic Compute Cloud.
// //
// Amazon Elastic Compute Cloud (Amazon EC2) provides secure and resizable computing // Amazon Elastic Compute Cloud (Amazon EC2) provides secure and resizable computing
// capacity in the AWS Cloud. Using Amazon EC2 eliminates the need to invest // capacity in the Amazon Web Services Cloud. Using Amazon EC2 eliminates the
// in hardware up front, so you can develop and deploy applications faster. // need to invest in hardware up front, so you can develop and deploy applications
// Amazon Virtual Private Cloud (Amazon VPC) enables you to provision a logically // faster. Amazon Virtual Private Cloud (Amazon VPC) enables you to provision
// isolated section of the AWS Cloud where you can launch AWS resources in a // a logically isolated section of the Amazon Web Services Cloud where you can
// virtual network that you've defined. Amazon Elastic Block Store (Amazon EBS) // launch Amazon Web Services resources in a virtual network that you've defined.
// provides block level storage volumes for use with EC2 instances. EBS volumes // Amazon Elastic Block Store (Amazon EBS) provides block level storage volumes
// are highly available and reliable storage volumes that can be attached to // for use with EC2 instances. EBS volumes are highly available and reliable
// any running instance and used like a hard drive. // storage volumes that can be attached to any running instance and used like
// a hard drive.
// //
// To learn more, see the following resources: // To learn more, see the following resources:
// //
// * Amazon EC2: AmazonEC2 product page (http://aws.amazon.com/ec2), Amazon // - Amazon EC2: AmazonEC2 product page (http://aws.amazon.com/ec2), Amazon
// EC2 documentation (http://aws.amazon.com/documentation/ec2) // EC2 documentation (http://aws.amazon.com/documentation/ec2)
// //
// * Amazon EBS: Amazon EBS product page (http://aws.amazon.com/ebs), Amazon // - Amazon EBS: Amazon EBS product page (http://aws.amazon.com/ebs), Amazon
// EBS documentation (http://aws.amazon.com/documentation/ebs) // EBS documentation (http://aws.amazon.com/documentation/ebs)
// //
// * Amazon VPC: Amazon VPC product page (http://aws.amazon.com/vpc), Amazon // - Amazon VPC: Amazon VPC product page (http://aws.amazon.com/vpc), Amazon
// VPC documentation (http://aws.amazon.com/documentation/vpc) // VPC documentation (http://aws.amazon.com/documentation/vpc)
// //
// * AWS VPN: AWS VPN product page (http://aws.amazon.com/vpn), AWS VPN documentation // - Amazon Web Services VPN: Amazon Web Services VPN product page (http://aws.amazon.com/vpn),
// (http://aws.amazon.com/documentation/vpn) // Amazon Web Services VPN documentation (http://aws.amazon.com/documentation/vpn)
// //
// See https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15 for more information on this service. // See https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15 for more information on this service.
// //
// See ec2 package documentation for more information. // See ec2 package documentation for more information.
// https://docs.aws.amazon.com/sdk-for-go/api/service/ec2/ // https://docs.aws.amazon.com/sdk-for-go/api/service/ec2/
// //
// Using the Client // # Using the Client
// //
// To contact Amazon Elastic Compute Cloud with the SDK use the New function to create // To contact Amazon Elastic Compute Cloud with the SDK use the New function to create
// a new service client. With that client you can make API requests to the service. // a new service client. With that client you can make API requests to the service.

View File

@ -39,31 +39,37 @@ const (
// aws.Config parameter to add your extra config. // aws.Config parameter to add your extra config.
// //
// Example: // Example:
// mySession := session.Must(session.NewSession())
// //
// // Create a EC2 client from just a session. // mySession := session.Must(session.NewSession())
// svc := ec2.New(mySession)
// //
// // Create a EC2 client with additional configuration // // Create a EC2 client from just a session.
// svc := ec2.New(mySession, aws.NewConfig().WithRegion("us-west-2")) // svc := ec2.New(mySession)
//
// // Create a EC2 client with additional configuration
// svc := ec2.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func New(p client.ConfigProvider, cfgs ...*aws.Config) *EC2 { func New(p client.ConfigProvider, cfgs ...*aws.Config) *EC2 {
c := p.ClientConfig(EndpointsID, cfgs...) c := p.ClientConfig(EndpointsID, cfgs...)
return newClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName) if c.SigningNameDerived || len(c.SigningName) == 0 {
c.SigningName = EndpointsID
// No Fallback
}
return newClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName, c.ResolvedRegion)
} }
// newClient creates, initializes and returns a new service client instance. // newClient creates, initializes and returns a new service client instance.
func newClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *EC2 { func newClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName, resolvedRegion string) *EC2 {
svc := &EC2{ svc := &EC2{
Client: client.New( Client: client.New(
cfg, cfg,
metadata.ClientInfo{ metadata.ClientInfo{
ServiceName: ServiceName, ServiceName: ServiceName,
ServiceID: ServiceID, ServiceID: ServiceID,
SigningName: signingName, SigningName: signingName,
SigningRegion: signingRegion, SigningRegion: signingRegion,
PartitionID: partitionID, PartitionID: partitionID,
Endpoint: endpoint, Endpoint: endpoint,
APIVersion: "2016-11-15", APIVersion: "2016-11-15",
ResolvedRegion: resolvedRegion,
}, },
handlers, handlers,
), ),

View File

@ -738,6 +738,57 @@ func (c *EC2) WaitUntilInstanceTerminatedWithContext(ctx aws.Context, input *Des
return w.WaitWithContext(ctx) return w.WaitWithContext(ctx)
} }
// WaitUntilInternetGatewayExists uses the Amazon EC2 API operation
// DescribeInternetGateways to wait for a condition to be met before returning.
// If the condition is not met within the max attempt window, an error will
// be returned.
func (c *EC2) WaitUntilInternetGatewayExists(input *DescribeInternetGatewaysInput) error {
return c.WaitUntilInternetGatewayExistsWithContext(aws.BackgroundContext(), input)
}
// WaitUntilInternetGatewayExistsWithContext is an extended version of WaitUntilInternetGatewayExists.
// With the support for passing in a context and options to configure the
// Waiter and the underlying request options.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *EC2) WaitUntilInternetGatewayExistsWithContext(ctx aws.Context, input *DescribeInternetGatewaysInput, opts ...request.WaiterOption) error {
w := request.Waiter{
Name: "WaitUntilInternetGatewayExists",
MaxAttempts: 6,
Delay: request.ConstantWaiterDelay(5 * time.Second),
Acceptors: []request.WaiterAcceptor{
{
State: request.SuccessWaiterState,
Matcher: request.PathWaiterMatch, Argument: "length(InternetGateways[].InternetGatewayId) > `0`",
Expected: true,
},
{
State: request.RetryWaiterState,
Matcher: request.ErrorWaiterMatch,
Expected: "InvalidInternetGateway.NotFound",
},
},
Logger: c.Config.Logger,
NewRequest: func(opts []request.Option) (*request.Request, error) {
var inCpy *DescribeInternetGatewaysInput
if input != nil {
tmp := *input
inCpy = &tmp
}
req, _ := c.DescribeInternetGatewaysRequest(inCpy)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return req, nil
},
}
w.ApplyOptions(opts...)
return w.WaitWithContext(ctx)
}
// WaitUntilKeyPairExists uses the Amazon EC2 API operation // WaitUntilKeyPairExists uses the Amazon EC2 API operation
// DescribeKeyPairs to wait for a condition to be met before returning. // DescribeKeyPairs to wait for a condition to be met before returning.
// If the condition is not met within the max attempt window, an error will // If the condition is not met within the max attempt window, an error will
@ -855,6 +906,57 @@ func (c *EC2) WaitUntilNatGatewayAvailableWithContext(ctx aws.Context, input *De
return w.WaitWithContext(ctx) return w.WaitWithContext(ctx)
} }
// WaitUntilNatGatewayDeleted uses the Amazon EC2 API operation
// DescribeNatGateways to wait for a condition to be met before returning.
// If the condition is not met within the max attempt window, an error will
// be returned.
func (c *EC2) WaitUntilNatGatewayDeleted(input *DescribeNatGatewaysInput) error {
return c.WaitUntilNatGatewayDeletedWithContext(aws.BackgroundContext(), input)
}
// WaitUntilNatGatewayDeletedWithContext is an extended version of WaitUntilNatGatewayDeleted.
// With the support for passing in a context and options to configure the
// Waiter and the underlying request options.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *EC2) WaitUntilNatGatewayDeletedWithContext(ctx aws.Context, input *DescribeNatGatewaysInput, opts ...request.WaiterOption) error {
w := request.Waiter{
Name: "WaitUntilNatGatewayDeleted",
MaxAttempts: 40,
Delay: request.ConstantWaiterDelay(15 * time.Second),
Acceptors: []request.WaiterAcceptor{
{
State: request.SuccessWaiterState,
Matcher: request.PathAllWaiterMatch, Argument: "NatGateways[].State",
Expected: "deleted",
},
{
State: request.SuccessWaiterState,
Matcher: request.ErrorWaiterMatch,
Expected: "NatGatewayNotFound",
},
},
Logger: c.Config.Logger,
NewRequest: func(opts []request.Option) (*request.Request, error) {
var inCpy *DescribeNatGatewaysInput
if input != nil {
tmp := *input
inCpy = &tmp
}
req, _ := c.DescribeNatGatewaysRequest(inCpy)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return req, nil
},
}
w.ApplyOptions(opts...)
return w.WaitWithContext(ctx)
}
// WaitUntilNetworkInterfaceAvailable uses the Amazon EC2 API operation // WaitUntilNetworkInterfaceAvailable uses the Amazon EC2 API operation
// DescribeNetworkInterfaces to wait for a condition to be met before returning. // DescribeNetworkInterfaces to wait for a condition to be met before returning.
// If the condition is not met within the max attempt window, an error will // If the condition is not met within the max attempt window, an error will
@ -1030,6 +1132,11 @@ func (c *EC2) WaitUntilSnapshotCompletedWithContext(ctx aws.Context, input *Desc
Matcher: request.PathAllWaiterMatch, Argument: "Snapshots[].State", Matcher: request.PathAllWaiterMatch, Argument: "Snapshots[].State",
Expected: "completed", Expected: "completed",
}, },
{
State: request.FailureWaiterState,
Matcher: request.PathAnyWaiterMatch, Argument: "Snapshots[].State",
Expected: "error",
},
}, },
Logger: c.Config.Logger, Logger: c.Config.Logger,
NewRequest: func(opts []request.Option) (*request.Request, error) { NewRequest: func(opts []request.Option) (*request.Request, error) {

File diff suppressed because it is too large Load Diff

View File

@ -11,12 +11,16 @@
// using IAM so that specific users or Amazon EC2 instances can access repositories // using IAM so that specific users or Amazon EC2 instances can access repositories
// and images. // and images.
// //
// Amazon ECR has service endpoints in each supported Region. For more information,
// see Amazon ECR endpoints (https://docs.aws.amazon.com/general/latest/gr/ecr.html)
// in the Amazon Web Services General Reference.
//
// See https://docs.aws.amazon.com/goto/WebAPI/ecr-2015-09-21 for more information on this service. // See https://docs.aws.amazon.com/goto/WebAPI/ecr-2015-09-21 for more information on this service.
// //
// See ecr package documentation for more information. // See ecr package documentation for more information.
// https://docs.aws.amazon.com/sdk-for-go/api/service/ecr/ // https://docs.aws.amazon.com/sdk-for-go/api/service/ecr/
// //
// Using the Client // # Using the Client
// //
// To contact Amazon EC2 Container Registry with the SDK use the New function to create // To contact Amazon EC2 Container Registry with the SDK use the New function to create
// a new service client. With that client you can make API requests to the service. // a new service client. With that client you can make API requests to the service.

View File

@ -125,10 +125,24 @@ const (
// "LimitExceededException". // "LimitExceededException".
// //
// The operation did not succeed because it would have exceeded a service limit // The operation did not succeed because it would have exceeded a service limit
// for your account. For more information, see Amazon ECR Service Quotas (https://docs.aws.amazon.com/AmazonECR/latest/userguide/service-quotas.html) // for your account. For more information, see Amazon ECR service quotas (https://docs.aws.amazon.com/AmazonECR/latest/userguide/service-quotas.html)
// in the Amazon Elastic Container Registry User Guide. // in the Amazon Elastic Container Registry User Guide.
ErrCodeLimitExceededException = "LimitExceededException" ErrCodeLimitExceededException = "LimitExceededException"
// ErrCodePullThroughCacheRuleAlreadyExistsException for service response error code
// "PullThroughCacheRuleAlreadyExistsException".
//
// A pull through cache rule with these settings already exists for the private
// registry.
ErrCodePullThroughCacheRuleAlreadyExistsException = "PullThroughCacheRuleAlreadyExistsException"
// ErrCodePullThroughCacheRuleNotFoundException for service response error code
// "PullThroughCacheRuleNotFoundException".
//
// The pull through cache rule was not found. Specify a valid pull through cache
// rule and try again.
ErrCodePullThroughCacheRuleNotFoundException = "PullThroughCacheRuleNotFoundException"
// ErrCodeReferencedImagesNotFoundException for service response error code // ErrCodeReferencedImagesNotFoundException for service response error code
// "ReferencedImagesNotFoundException". // "ReferencedImagesNotFoundException".
// //
@ -194,6 +208,12 @@ const (
// The image is of a type that cannot be scanned. // The image is of a type that cannot be scanned.
ErrCodeUnsupportedImageTypeException = "UnsupportedImageTypeException" ErrCodeUnsupportedImageTypeException = "UnsupportedImageTypeException"
// ErrCodeUnsupportedUpstreamRegistryException for service response error code
// "UnsupportedUpstreamRegistryException".
//
// The specified upstream registry isn't supported.
ErrCodeUnsupportedUpstreamRegistryException = "UnsupportedUpstreamRegistryException"
// ErrCodeUploadNotFoundException for service response error code // ErrCodeUploadNotFoundException for service response error code
// "UploadNotFoundException". // "UploadNotFoundException".
// //
@ -209,34 +229,37 @@ const (
) )
var exceptionFromCode = map[string]func(protocol.ResponseMetadata) error{ var exceptionFromCode = map[string]func(protocol.ResponseMetadata) error{
"EmptyUploadException": newErrorEmptyUploadException, "EmptyUploadException": newErrorEmptyUploadException,
"ImageAlreadyExistsException": newErrorImageAlreadyExistsException, "ImageAlreadyExistsException": newErrorImageAlreadyExistsException,
"ImageDigestDoesNotMatchException": newErrorImageDigestDoesNotMatchException, "ImageDigestDoesNotMatchException": newErrorImageDigestDoesNotMatchException,
"ImageNotFoundException": newErrorImageNotFoundException, "ImageNotFoundException": newErrorImageNotFoundException,
"ImageTagAlreadyExistsException": newErrorImageTagAlreadyExistsException, "ImageTagAlreadyExistsException": newErrorImageTagAlreadyExistsException,
"InvalidLayerException": newErrorInvalidLayerException, "InvalidLayerException": newErrorInvalidLayerException,
"InvalidLayerPartException": newErrorInvalidLayerPartException, "InvalidLayerPartException": newErrorInvalidLayerPartException,
"InvalidParameterException": newErrorInvalidParameterException, "InvalidParameterException": newErrorInvalidParameterException,
"InvalidTagParameterException": newErrorInvalidTagParameterException, "InvalidTagParameterException": newErrorInvalidTagParameterException,
"KmsException": newErrorKmsException, "KmsException": newErrorKmsException,
"LayerAlreadyExistsException": newErrorLayerAlreadyExistsException, "LayerAlreadyExistsException": newErrorLayerAlreadyExistsException,
"LayerInaccessibleException": newErrorLayerInaccessibleException, "LayerInaccessibleException": newErrorLayerInaccessibleException,
"LayerPartTooSmallException": newErrorLayerPartTooSmallException, "LayerPartTooSmallException": newErrorLayerPartTooSmallException,
"LayersNotFoundException": newErrorLayersNotFoundException, "LayersNotFoundException": newErrorLayersNotFoundException,
"LifecyclePolicyNotFoundException": newErrorLifecyclePolicyNotFoundException, "LifecyclePolicyNotFoundException": newErrorLifecyclePolicyNotFoundException,
"LifecyclePolicyPreviewInProgressException": newErrorLifecyclePolicyPreviewInProgressException, "LifecyclePolicyPreviewInProgressException": newErrorLifecyclePolicyPreviewInProgressException,
"LifecyclePolicyPreviewNotFoundException": newErrorLifecyclePolicyPreviewNotFoundException, "LifecyclePolicyPreviewNotFoundException": newErrorLifecyclePolicyPreviewNotFoundException,
"LimitExceededException": newErrorLimitExceededException, "LimitExceededException": newErrorLimitExceededException,
"ReferencedImagesNotFoundException": newErrorReferencedImagesNotFoundException, "PullThroughCacheRuleAlreadyExistsException": newErrorPullThroughCacheRuleAlreadyExistsException,
"RegistryPolicyNotFoundException": newErrorRegistryPolicyNotFoundException, "PullThroughCacheRuleNotFoundException": newErrorPullThroughCacheRuleNotFoundException,
"RepositoryAlreadyExistsException": newErrorRepositoryAlreadyExistsException, "ReferencedImagesNotFoundException": newErrorReferencedImagesNotFoundException,
"RepositoryNotEmptyException": newErrorRepositoryNotEmptyException, "RegistryPolicyNotFoundException": newErrorRegistryPolicyNotFoundException,
"RepositoryNotFoundException": newErrorRepositoryNotFoundException, "RepositoryAlreadyExistsException": newErrorRepositoryAlreadyExistsException,
"RepositoryPolicyNotFoundException": newErrorRepositoryPolicyNotFoundException, "RepositoryNotEmptyException": newErrorRepositoryNotEmptyException,
"ScanNotFoundException": newErrorScanNotFoundException, "RepositoryNotFoundException": newErrorRepositoryNotFoundException,
"ServerException": newErrorServerException, "RepositoryPolicyNotFoundException": newErrorRepositoryPolicyNotFoundException,
"TooManyTagsException": newErrorTooManyTagsException, "ScanNotFoundException": newErrorScanNotFoundException,
"UnsupportedImageTypeException": newErrorUnsupportedImageTypeException, "ServerException": newErrorServerException,
"UploadNotFoundException": newErrorUploadNotFoundException, "TooManyTagsException": newErrorTooManyTagsException,
"ValidationException": newErrorValidationException, "UnsupportedImageTypeException": newErrorUnsupportedImageTypeException,
"UnsupportedUpstreamRegistryException": newErrorUnsupportedUpstreamRegistryException,
"UploadNotFoundException": newErrorUploadNotFoundException,
"ValidationException": newErrorValidationException,
} }

View File

@ -40,36 +40,38 @@ const (
// aws.Config parameter to add your extra config. // aws.Config parameter to add your extra config.
// //
// Example: // Example:
// mySession := session.Must(session.NewSession())
// //
// // Create a ECR client from just a session. // mySession := session.Must(session.NewSession())
// svc := ecr.New(mySession)
// //
// // Create a ECR client with additional configuration // // Create a ECR client from just a session.
// svc := ecr.New(mySession, aws.NewConfig().WithRegion("us-west-2")) // svc := ecr.New(mySession)
//
// // Create a ECR client with additional configuration
// svc := ecr.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func New(p client.ConfigProvider, cfgs ...*aws.Config) *ECR { func New(p client.ConfigProvider, cfgs ...*aws.Config) *ECR {
c := p.ClientConfig(EndpointsID, cfgs...) c := p.ClientConfig(EndpointsID, cfgs...)
if c.SigningNameDerived || len(c.SigningName) == 0 { if c.SigningNameDerived || len(c.SigningName) == 0 {
c.SigningName = "ecr" c.SigningName = "ecr"
} }
return newClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName) return newClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName, c.ResolvedRegion)
} }
// newClient creates, initializes and returns a new service client instance. // newClient creates, initializes and returns a new service client instance.
func newClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *ECR { func newClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName, resolvedRegion string) *ECR {
svc := &ECR{ svc := &ECR{
Client: client.New( Client: client.New(
cfg, cfg,
metadata.ClientInfo{ metadata.ClientInfo{
ServiceName: ServiceName, ServiceName: ServiceName,
ServiceID: ServiceID, ServiceID: ServiceID,
SigningName: signingName, SigningName: signingName,
SigningRegion: signingRegion, SigningRegion: signingRegion,
PartitionID: partitionID, PartitionID: partitionID,
Endpoint: endpoint, Endpoint: endpoint,
APIVersion: "2015-09-21", APIVersion: "2015-09-21",
JSONVersion: "1.1", ResolvedRegion: resolvedRegion,
TargetPrefix: "AmazonEC2ContainerRegistry_V20150921", JSONVersion: "1.1",
TargetPrefix: "AmazonEC2ContainerRegistry_V20150921",
}, },
handlers, handlers,
), ),

File diff suppressed because it is too large Load Diff

View File

@ -32,7 +32,7 @@
// See elb package documentation for more information. // See elb package documentation for more information.
// https://docs.aws.amazon.com/sdk-for-go/api/service/elb/ // https://docs.aws.amazon.com/sdk-for-go/api/service/elb/
// //
// Using the Client // # Using the Client
// //
// To contact Elastic Load Balancing with the SDK use the New function to create // To contact Elastic Load Balancing with the SDK use the New function to create
// a new service client. With that client you can make API requests to the service. // a new service client. With that client you can make API requests to the service.

View File

@ -39,31 +39,37 @@ const (
// aws.Config parameter to add your extra config. // aws.Config parameter to add your extra config.
// //
// Example: // Example:
// mySession := session.Must(session.NewSession())
// //
// // Create a ELB client from just a session. // mySession := session.Must(session.NewSession())
// svc := elb.New(mySession)
// //
// // Create a ELB client with additional configuration // // Create a ELB client from just a session.
// svc := elb.New(mySession, aws.NewConfig().WithRegion("us-west-2")) // svc := elb.New(mySession)
//
// // Create a ELB client with additional configuration
// svc := elb.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func New(p client.ConfigProvider, cfgs ...*aws.Config) *ELB { func New(p client.ConfigProvider, cfgs ...*aws.Config) *ELB {
c := p.ClientConfig(EndpointsID, cfgs...) c := p.ClientConfig(EndpointsID, cfgs...)
return newClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName) if c.SigningNameDerived || len(c.SigningName) == 0 {
c.SigningName = EndpointsID
// No Fallback
}
return newClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName, c.ResolvedRegion)
} }
// newClient creates, initializes and returns a new service client instance. // newClient creates, initializes and returns a new service client instance.
func newClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *ELB { func newClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName, resolvedRegion string) *ELB {
svc := &ELB{ svc := &ELB{
Client: client.New( Client: client.New(
cfg, cfg,
metadata.ClientInfo{ metadata.ClientInfo{
ServiceName: ServiceName, ServiceName: ServiceName,
ServiceID: ServiceID, ServiceID: ServiceID,
SigningName: signingName, SigningName: signingName,
SigningRegion: signingRegion, SigningRegion: signingRegion,
PartitionID: partitionID, PartitionID: partitionID,
Endpoint: endpoint, Endpoint: endpoint,
APIVersion: "2012-06-01", APIVersion: "2012-06-01",
ResolvedRegion: resolvedRegion,
}, },
handlers, handlers,
), ),

File diff suppressed because it is too large Load Diff

View File

@ -18,13 +18,13 @@
// Load Balancers, Network Load Balancers, Gateway Load Balancers, and Classic // Load Balancers, Network Load Balancers, Gateway Load Balancers, and Classic
// Load Balancers. This reference covers the following load balancer types: // Load Balancers. This reference covers the following load balancer types:
// //
// * Application Load Balancer - Operates at the application layer (layer // - Application Load Balancer - Operates at the application layer (layer
// 7) and supports HTTP and HTTPS. // 7) and supports HTTP and HTTPS.
// //
// * Network Load Balancer - Operates at the transport layer (layer 4) and // - Network Load Balancer - Operates at the transport layer (layer 4) and
// supports TCP, TLS, and UDP. // supports TCP, TLS, and UDP.
// //
// * Gateway Load Balancer - Operates at the network layer (layer 3). // - Gateway Load Balancer - Operates at the network layer (layer 3).
// //
// For more information, see the Elastic Load Balancing User Guide (https://docs.aws.amazon.com/elasticloadbalancing/latest/userguide/). // For more information, see the Elastic Load Balancing User Guide (https://docs.aws.amazon.com/elasticloadbalancing/latest/userguide/).
// //
@ -36,7 +36,7 @@
// See elbv2 package documentation for more information. // See elbv2 package documentation for more information.
// https://docs.aws.amazon.com/sdk-for-go/api/service/elbv2/ // https://docs.aws.amazon.com/sdk-for-go/api/service/elbv2/
// //
// Using the Client // # Using the Client
// //
// To contact Elastic Load Balancing with the SDK use the New function to create // To contact Elastic Load Balancing with the SDK use the New function to create
// a new service client. With that client you can make API requests to the service. // a new service client. With that client you can make API requests to the service.

View File

@ -183,7 +183,8 @@ const (
// ErrCodeTooManyLoadBalancersException for service response error code // ErrCodeTooManyLoadBalancersException for service response error code
// "TooManyLoadBalancers". // "TooManyLoadBalancers".
// //
// You've reached the limit on the number of load balancers for your AWS account. // You've reached the limit on the number of load balancers for your Amazon
// Web Services account.
ErrCodeTooManyLoadBalancersException = "TooManyLoadBalancers" ErrCodeTooManyLoadBalancersException = "TooManyLoadBalancers"
// ErrCodeTooManyRegistrationsForTargetIdException for service response error code // ErrCodeTooManyRegistrationsForTargetIdException for service response error code
@ -208,7 +209,8 @@ const (
// ErrCodeTooManyTargetGroupsException for service response error code // ErrCodeTooManyTargetGroupsException for service response error code
// "TooManyTargetGroups". // "TooManyTargetGroups".
// //
// You've reached the limit on the number of target groups for your AWS account. // You've reached the limit on the number of target groups for your Amazon Web
// Services account.
ErrCodeTooManyTargetGroupsException = "TooManyTargetGroups" ErrCodeTooManyTargetGroupsException = "TooManyTargetGroups"
// ErrCodeTooManyTargetsException for service response error code // ErrCodeTooManyTargetsException for service response error code

View File

@ -39,31 +39,37 @@ const (
// aws.Config parameter to add your extra config. // aws.Config parameter to add your extra config.
// //
// Example: // Example:
// mySession := session.Must(session.NewSession())
// //
// // Create a ELBV2 client from just a session. // mySession := session.Must(session.NewSession())
// svc := elbv2.New(mySession)
// //
// // Create a ELBV2 client with additional configuration // // Create a ELBV2 client from just a session.
// svc := elbv2.New(mySession, aws.NewConfig().WithRegion("us-west-2")) // svc := elbv2.New(mySession)
//
// // Create a ELBV2 client with additional configuration
// svc := elbv2.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func New(p client.ConfigProvider, cfgs ...*aws.Config) *ELBV2 { func New(p client.ConfigProvider, cfgs ...*aws.Config) *ELBV2 {
c := p.ClientConfig(EndpointsID, cfgs...) c := p.ClientConfig(EndpointsID, cfgs...)
return newClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName) if c.SigningNameDerived || len(c.SigningName) == 0 {
c.SigningName = EndpointsID
// No Fallback
}
return newClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName, c.ResolvedRegion)
} }
// newClient creates, initializes and returns a new service client instance. // newClient creates, initializes and returns a new service client instance.
func newClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *ELBV2 { func newClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName, resolvedRegion string) *ELBV2 {
svc := &ELBV2{ svc := &ELBV2{
Client: client.New( Client: client.New(
cfg, cfg,
metadata.ClientInfo{ metadata.ClientInfo{
ServiceName: ServiceName, ServiceName: ServiceName,
ServiceID: ServiceID, ServiceID: ServiceID,
SigningName: signingName, SigningName: signingName,
SigningRegion: signingRegion, SigningRegion: signingRegion,
PartitionID: partitionID, PartitionID: partitionID,
Endpoint: endpoint, Endpoint: endpoint,
APIVersion: "2015-12-01", APIVersion: "2015-12-01",
ResolvedRegion: resolvedRegion,
}, },
handlers, handlers,
), ),

File diff suppressed because it is too large Load Diff

View File

@ -3,84 +3,99 @@
// Package kms provides the client and types for making API // Package kms provides the client and types for making API
// requests to AWS Key Management Service. // requests to AWS Key Management Service.
// //
// AWS Key Management Service (AWS KMS) is an encryption and key management // Key Management Service (KMS) is an encryption and key management web service.
// web service. This guide describes the AWS KMS operations that you can call // This guide describes the KMS operations that you can call programmatically.
// programmatically. For general information about AWS KMS, see the AWS Key // For general information about KMS, see the Key Management Service Developer
// Management Service Developer Guide (https://docs.aws.amazon.com/kms/latest/developerguide/). // Guide (https://docs.aws.amazon.com/kms/latest/developerguide/).
// //
// AWS provides SDKs that consist of libraries and sample code for various programming // KMS is replacing the term customer master key (CMK) with KMS key and KMS
// languages and platforms (Java, Ruby, .Net, macOS, Android, etc.). The SDKs // key. The concept has not changed. To prevent breaking changes, KMS is keeping
// provide a convenient way to create programmatic access to AWS KMS and other // some variations of this term.
// AWS services. For example, the SDKs take care of tasks such as signing requests
// (see below), managing errors, and retrying requests automatically. For more
// information about the AWS SDKs, including how to download and install them,
// see Tools for Amazon Web Services (http://aws.amazon.com/tools/).
// //
// We recommend that you use the AWS SDKs to make programmatic API calls to // Amazon Web Services provides SDKs that consist of libraries and sample code
// AWS KMS. // for various programming languages and platforms (Java, Ruby, .Net, macOS,
// Android, etc.). The SDKs provide a convenient way to create programmatic
// access to KMS and other Amazon Web Services services. For example, the SDKs
// take care of tasks such as signing requests (see below), managing errors,
// and retrying requests automatically. For more information about the Amazon
// Web Services SDKs, including how to download and install them, see Tools
// for Amazon Web Services (http://aws.amazon.com/tools/).
// //
// Clients must support TLS (Transport Layer Security) 1.0. We recommend TLS // We recommend that you use the Amazon Web Services SDKs to make programmatic
// 1.2. Clients must also support cipher suites with Perfect Forward Secrecy // API calls to KMS.
// (PFS) such as Ephemeral Diffie-Hellman (DHE) or Elliptic Curve Ephemeral
// Diffie-Hellman (ECDHE). Most modern systems such as Java 7 and later support
// these modes.
// //
// Signing Requests // If you need to use FIPS 140-2 validated cryptographic modules when communicating
// with Amazon Web Services, use the FIPS endpoint in your preferred Amazon
// Web Services Region. For more information about the available FIPS endpoints,
// see Service endpoints (https://docs.aws.amazon.com/general/latest/gr/kms.html#kms_region)
// in the Key Management Service topic of the Amazon Web Services General Reference.
//
// All KMS API calls must be signed and be transmitted using Transport Layer
// Security (TLS). KMS recommends you always use the latest supported TLS version.
// Clients must also support cipher suites with Perfect Forward Secrecy (PFS)
// such as Ephemeral Diffie-Hellman (DHE) or Elliptic Curve Ephemeral Diffie-Hellman
// (ECDHE). Most modern systems such as Java 7 and later support these modes.
//
// # Signing Requests
// //
// Requests must be signed by using an access key ID and a secret access key. // Requests must be signed by using an access key ID and a secret access key.
// We strongly recommend that you do not use your AWS account (root) access // We strongly recommend that you do not use your Amazon Web Services account
// key ID and secret key for everyday work with AWS KMS. Instead, use the access // (root) access key ID and secret key for everyday work with KMS. Instead,
// key ID and secret access key for an IAM user. You can also use the AWS Security // use the access key ID and secret access key for an IAM user. You can also
// Token Service to generate temporary security credentials that you can use // use the Amazon Web Services Security Token Service to generate temporary
// to sign requests. // security credentials that you can use to sign requests.
// //
// All AWS KMS operations require Signature Version 4 (https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html). // All KMS operations require Signature Version 4 (https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html).
// //
// Logging API Requests // # Logging API Requests
// //
// AWS KMS supports AWS CloudTrail, a service that logs AWS API calls and related // KMS supports CloudTrail, a service that logs Amazon Web Services API calls
// events for your AWS account and delivers them to an Amazon S3 bucket that // and related events for your Amazon Web Services account and delivers them
// you specify. By using the information collected by CloudTrail, you can determine // to an Amazon S3 bucket that you specify. By using the information collected
// what requests were made to AWS KMS, who made the request, when it was made, // by CloudTrail, you can determine what requests were made to KMS, who made
// and so on. To learn more about CloudTrail, including how to turn it on and // the request, when it was made, and so on. To learn more about CloudTrail,
// find your log files, see the AWS CloudTrail User Guide (https://docs.aws.amazon.com/awscloudtrail/latest/userguide/). // including how to turn it on and find your log files, see the CloudTrail User
// Guide (https://docs.aws.amazon.com/awscloudtrail/latest/userguide/).
// //
// Additional Resources // # Additional Resources
// //
// For more information about credentials and request signing, see the following: // For more information about credentials and request signing, see the following:
// //
// * AWS Security Credentials (https://docs.aws.amazon.com/general/latest/gr/aws-security-credentials.html) // - Amazon Web Services Security Credentials (https://docs.aws.amazon.com/general/latest/gr/aws-security-credentials.html)
// - This topic provides general information about the types of credentials
// used for accessing AWS.
// //
// * Temporary Security Credentials (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html) // - This topic provides general information about the types of credentials
// - This section of the IAM User Guide describes how to create and use temporary // used to access Amazon Web Services.
// security credentials.
// //
// * Signature Version 4 Signing Process (https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html) // - Temporary Security Credentials (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html)
// - This set of topics walks you through the process of signing a request
// using an access key ID and a secret access key.
// //
// Commonly Used API Operations // - This section of the IAM User Guide describes how to create and use temporary
// security credentials.
//
// - Signature Version 4 Signing Process (https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html)
//
// - This set of topics walks you through the process of signing a request
// using an access key ID and a secret access key.
//
// # Commonly Used API Operations
// //
// Of the API operations discussed in this guide, the following will prove the // Of the API operations discussed in this guide, the following will prove the
// most useful for most applications. You will likely perform operations other // most useful for most applications. You will likely perform operations other
// than these, such as creating keys and assigning policies, by using the console. // than these, such as creating keys and assigning policies, by using the console.
// //
// * Encrypt // - Encrypt
// //
// * Decrypt // - Decrypt
// //
// * GenerateDataKey // - GenerateDataKey
// //
// * GenerateDataKeyWithoutPlaintext // - GenerateDataKeyWithoutPlaintext
// //
// See https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01 for more information on this service. // See https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01 for more information on this service.
// //
// See kms package documentation for more information. // See kms package documentation for more information.
// https://docs.aws.amazon.com/sdk-for-go/api/service/kms/ // https://docs.aws.amazon.com/sdk-for-go/api/service/kms/
// //
// Using the Client // # Using the Client
// //
// To contact AWS Key Management Service with the SDK use the New function to create // To contact AWS Key Management Service with the SDK use the New function to create
// a new service client. With that client you can make API requests to the service. // a new service client. With that client you can make API requests to the service.

View File

@ -18,10 +18,10 @@ const (
// ErrCodeCloudHsmClusterInUseException for service response error code // ErrCodeCloudHsmClusterInUseException for service response error code
// "CloudHsmClusterInUseException". // "CloudHsmClusterInUseException".
// //
// The request was rejected because the specified AWS CloudHSM cluster is already // The request was rejected because the specified CloudHSM cluster is already
// associated with a custom key store or it shares a backup history with a cluster // associated with a custom key store or it shares a backup history with a cluster
// that is associated with a custom key store. Each custom key store must be // that is associated with a custom key store. Each custom key store must be
// associated with a different AWS CloudHSM cluster. // associated with a different CloudHSM cluster.
// //
// Clusters that share a backup history have the same cluster certificate. To // Clusters that share a backup history have the same cluster certificate. To
// view the cluster certificate of a cluster, use the DescribeClusters (https://docs.aws.amazon.com/cloudhsm/latest/APIReference/API_DescribeClusters.html) // view the cluster certificate of a cluster, use the DescribeClusters (https://docs.aws.amazon.com/cloudhsm/latest/APIReference/API_DescribeClusters.html)
@ -31,8 +31,8 @@ const (
// ErrCodeCloudHsmClusterInvalidConfigurationException for service response error code // ErrCodeCloudHsmClusterInvalidConfigurationException for service response error code
// "CloudHsmClusterInvalidConfigurationException". // "CloudHsmClusterInvalidConfigurationException".
// //
// The request was rejected because the associated AWS CloudHSM cluster did // The request was rejected because the associated CloudHSM cluster did not
// not meet the configuration requirements for a custom key store. // meet the configuration requirements for a custom key store.
// //
// * The cluster must be configured with private subnets in at least two // * The cluster must be configured with private subnets in at least two
// different Availability Zones in the Region. // different Availability Zones in the Region.
@ -47,46 +47,44 @@ const (
// operation. // operation.
// //
// * The cluster must contain at least as many HSMs as the operation requires. // * The cluster must contain at least as many HSMs as the operation requires.
// To add HSMs, use the AWS CloudHSM CreateHsm (https://docs.aws.amazon.com/cloudhsm/latest/APIReference/API_CreateHsm.html) // To add HSMs, use the CloudHSM CreateHsm (https://docs.aws.amazon.com/cloudhsm/latest/APIReference/API_CreateHsm.html)
// operation. For the CreateCustomKeyStore, UpdateCustomKeyStore, and CreateKey // operation. For the CreateCustomKeyStore, UpdateCustomKeyStore, and CreateKey
// operations, the AWS CloudHSM cluster must have at least two active HSMs, // operations, the CloudHSM cluster must have at least two active HSMs, each
// each in a different Availability Zone. For the ConnectCustomKeyStore operation, // in a different Availability Zone. For the ConnectCustomKeyStore operation,
// the AWS CloudHSM must contain at least one active HSM. // the CloudHSM must contain at least one active HSM.
// //
// For information about the requirements for an AWS CloudHSM cluster that is // For information about the requirements for an CloudHSM cluster that is associated
// associated with a custom key store, see Assemble the Prerequisites (https://docs.aws.amazon.com/kms/latest/developerguide/create-keystore.html#before-keystore) // with a custom key store, see Assemble the Prerequisites (https://docs.aws.amazon.com/kms/latest/developerguide/create-keystore.html#before-keystore)
// in the AWS Key Management Service Developer Guide. For information about // in the Key Management Service Developer Guide. For information about creating
// creating a private subnet for an AWS CloudHSM cluster, see Create a Private // a private subnet for an CloudHSM cluster, see Create a Private Subnet (https://docs.aws.amazon.com/cloudhsm/latest/userguide/create-subnets.html)
// Subnet (https://docs.aws.amazon.com/cloudhsm/latest/userguide/create-subnets.html) // in the CloudHSM User Guide. For information about cluster security groups,
// in the AWS CloudHSM User Guide. For information about cluster security groups,
// see Configure a Default Security Group (https://docs.aws.amazon.com/cloudhsm/latest/userguide/configure-sg.html) // see Configure a Default Security Group (https://docs.aws.amazon.com/cloudhsm/latest/userguide/configure-sg.html)
// in the AWS CloudHSM User Guide . // in the CloudHSM User Guide .
ErrCodeCloudHsmClusterInvalidConfigurationException = "CloudHsmClusterInvalidConfigurationException" ErrCodeCloudHsmClusterInvalidConfigurationException = "CloudHsmClusterInvalidConfigurationException"
// ErrCodeCloudHsmClusterNotActiveException for service response error code // ErrCodeCloudHsmClusterNotActiveException for service response error code
// "CloudHsmClusterNotActiveException". // "CloudHsmClusterNotActiveException".
// //
// The request was rejected because the AWS CloudHSM cluster that is associated // The request was rejected because the CloudHSM cluster that is associated
// with the custom key store is not active. Initialize and activate the cluster // with the custom key store is not active. Initialize and activate the cluster
// and try the command again. For detailed instructions, see Getting Started // and try the command again. For detailed instructions, see Getting Started
// (https://docs.aws.amazon.com/cloudhsm/latest/userguide/getting-started.html) // (https://docs.aws.amazon.com/cloudhsm/latest/userguide/getting-started.html)
// in the AWS CloudHSM User Guide. // in the CloudHSM User Guide.
ErrCodeCloudHsmClusterNotActiveException = "CloudHsmClusterNotActiveException" ErrCodeCloudHsmClusterNotActiveException = "CloudHsmClusterNotActiveException"
// ErrCodeCloudHsmClusterNotFoundException for service response error code // ErrCodeCloudHsmClusterNotFoundException for service response error code
// "CloudHsmClusterNotFoundException". // "CloudHsmClusterNotFoundException".
// //
// The request was rejected because AWS KMS cannot find the AWS CloudHSM cluster // The request was rejected because KMS cannot find the CloudHSM cluster with
// with the specified cluster ID. Retry the request with a different cluster // the specified cluster ID. Retry the request with a different cluster ID.
// ID.
ErrCodeCloudHsmClusterNotFoundException = "CloudHsmClusterNotFoundException" ErrCodeCloudHsmClusterNotFoundException = "CloudHsmClusterNotFoundException"
// ErrCodeCloudHsmClusterNotRelatedException for service response error code // ErrCodeCloudHsmClusterNotRelatedException for service response error code
// "CloudHsmClusterNotRelatedException". // "CloudHsmClusterNotRelatedException".
// //
// The request was rejected because the specified AWS CloudHSM cluster has a // The request was rejected because the specified CloudHSM cluster has a different
// different cluster certificate than the original cluster. You cannot use the // cluster certificate than the original cluster. You cannot use the operation
// operation to specify an unrelated cluster. // to specify an unrelated cluster.
// //
// Specify a cluster that shares a backup history with the original cluster. // Specify a cluster that shares a backup history with the original cluster.
// This includes clusters that were created from a backup of the current cluster, // This includes clusters that were created from a backup of the current cluster,
@ -101,10 +99,10 @@ const (
// ErrCodeCustomKeyStoreHasCMKsException for service response error code // ErrCodeCustomKeyStoreHasCMKsException for service response error code
// "CustomKeyStoreHasCMKsException". // "CustomKeyStoreHasCMKsException".
// //
// The request was rejected because the custom key store contains AWS KMS customer // The request was rejected because the custom key store contains KMS keys.
// master keys (CMKs). After verifying that you do not need to use the CMKs, // After verifying that you do not need to use the KMS keys, use the ScheduleKeyDeletion
// use the ScheduleKeyDeletion operation to delete the CMKs. After they are // operation to delete the KMS keys. After they are deleted, you can delete
// deleted, you can delete the custom key store. // the custom key store.
ErrCodeCustomKeyStoreHasCMKsException = "CustomKeyStoreHasCMKsException" ErrCodeCustomKeyStoreHasCMKsException = "CustomKeyStoreHasCMKsException"
// ErrCodeCustomKeyStoreInvalidStateException for service response error code // ErrCodeCustomKeyStoreInvalidStateException for service response error code
@ -140,7 +138,7 @@ const (
// ErrCodeCustomKeyStoreNotFoundException for service response error code // ErrCodeCustomKeyStoreNotFoundException for service response error code
// "CustomKeyStoreNotFoundException". // "CustomKeyStoreNotFoundException".
// //
// The request was rejected because AWS KMS cannot find a custom key store with // The request was rejected because KMS cannot find a custom key store with
// the specified key store name or ID. // the specified key store name or ID.
ErrCodeCustomKeyStoreNotFoundException = "CustomKeyStoreNotFoundException" ErrCodeCustomKeyStoreNotFoundException = "CustomKeyStoreNotFoundException"
@ -154,7 +152,7 @@ const (
// ErrCodeDisabledException for service response error code // ErrCodeDisabledException for service response error code
// "DisabledException". // "DisabledException".
// //
// The request was rejected because the specified CMK is not enabled. // The request was rejected because the specified KMS key is not enabled.
ErrCodeDisabledException = "DisabledException" ErrCodeDisabledException = "DisabledException"
// ErrCodeExpiredImportTokenException for service response error code // ErrCodeExpiredImportTokenException for service response error code
@ -168,9 +166,9 @@ const (
// ErrCodeIncorrectKeyException for service response error code // ErrCodeIncorrectKeyException for service response error code
// "IncorrectKeyException". // "IncorrectKeyException".
// //
// The request was rejected because the specified CMK cannot decrypt the data. // The request was rejected because the specified KMS key cannot decrypt the
// The KeyId in a Decrypt request and the SourceKeyId in a ReEncrypt request // data. The KeyId in a Decrypt request and the SourceKeyId in a ReEncrypt request
// must identify the same CMK that was used to encrypt the ciphertext. // must identify the same KMS key that was used to encrypt the ciphertext.
ErrCodeIncorrectKeyException = "IncorrectKeyException" ErrCodeIncorrectKeyException = "IncorrectKeyException"
// ErrCodeIncorrectKeyMaterialException for service response error code // ErrCodeIncorrectKeyMaterialException for service response error code
@ -178,14 +176,14 @@ const (
// //
// The request was rejected because the key material in the request is, expired, // The request was rejected because the key material in the request is, expired,
// invalid, or is not the same key material that was previously imported into // invalid, or is not the same key material that was previously imported into
// this customer master key (CMK). // this KMS key.
ErrCodeIncorrectKeyMaterialException = "IncorrectKeyMaterialException" ErrCodeIncorrectKeyMaterialException = "IncorrectKeyMaterialException"
// ErrCodeIncorrectTrustAnchorException for service response error code // ErrCodeIncorrectTrustAnchorException for service response error code
// "IncorrectTrustAnchorException". // "IncorrectTrustAnchorException".
// //
// The request was rejected because the trust anchor certificate in the request // The request was rejected because the trust anchor certificate in the request
// is not the trust anchor certificate for the specified AWS CloudHSM cluster. // is not the trust anchor certificate for the specified CloudHSM cluster.
// //
// When you initialize the cluster (https://docs.aws.amazon.com/cloudhsm/latest/userguide/initialize-cluster.html#sign-csr), // When you initialize the cluster (https://docs.aws.amazon.com/cloudhsm/latest/userguide/initialize-cluster.html#sign-csr),
// you create the trust anchor certificate and save it in the customerCA.crt // you create the trust anchor certificate and save it in the customerCA.crt
@ -220,8 +218,8 @@ const (
// the ciphertext, such as the encryption context, is corrupted, missing, or // the ciphertext, such as the encryption context, is corrupted, missing, or
// otherwise invalid. // otherwise invalid.
// //
// From the ImportKeyMaterial operation, the request was rejected because AWS // From the ImportKeyMaterial operation, the request was rejected because KMS
// KMS could not decrypt the encrypted (wrapped) key material. // could not decrypt the encrypted (wrapped) key material.
ErrCodeInvalidCiphertextException = "InvalidCiphertextException" ErrCodeInvalidCiphertextException = "InvalidCiphertextException"
// ErrCodeInvalidGrantIdException for service response error code // ErrCodeInvalidGrantIdException for service response error code
@ -240,7 +238,7 @@ const (
// "InvalidImportTokenException". // "InvalidImportTokenException".
// //
// The request was rejected because the provided import token is invalid or // The request was rejected because the provided import token is invalid or
// is associated with a different customer master key (CMK). // is associated with a different KMS key.
ErrCodeInvalidImportTokenException = "InvalidImportTokenException" ErrCodeInvalidImportTokenException = "InvalidImportTokenException"
// ErrCodeInvalidKeyUsageException for service response error code // ErrCodeInvalidKeyUsageException for service response error code
@ -248,17 +246,19 @@ const (
// //
// The request was rejected for one of the following reasons: // The request was rejected for one of the following reasons:
// //
// * The KeyUsage value of the CMK is incompatible with the API operation. // * The KeyUsage value of the KMS key is incompatible with the API operation.
// //
// * The encryption algorithm or signing algorithm specified for the operation // * The encryption algorithm or signing algorithm specified for the operation
// is incompatible with the type of key material in the CMK (CustomerMasterKeySpec). // is incompatible with the type of key material in the KMS key (KeySpec).
// //
// For encrypting, decrypting, re-encrypting, and generating data keys, the // For encrypting, decrypting, re-encrypting, and generating data keys, the
// KeyUsage must be ENCRYPT_DECRYPT. For signing and verifying, the KeyUsage // KeyUsage must be ENCRYPT_DECRYPT. For signing and verifying messages, the
// must be SIGN_VERIFY. To find the KeyUsage of a CMK, use the DescribeKey operation. // KeyUsage must be SIGN_VERIFY. For generating and verifying message authentication
// codes (MACs), the KeyUsage must be GENERATE_VERIFY_MAC. To find the KeyUsage
// of a KMS key, use the DescribeKey operation.
// //
// To find the encryption or signing algorithms supported for a particular CMK, // To find the encryption or signing algorithms supported for a particular KMS
// use the DescribeKey operation. // key, use the DescribeKey operation.
ErrCodeInvalidKeyUsageException = "InvalidKeyUsageException" ErrCodeInvalidKeyUsageException = "InvalidKeyUsageException"
// ErrCodeInvalidMarkerException for service response error code // ErrCodeInvalidMarkerException for service response error code
@ -274,24 +274,32 @@ const (
// The request was rejected because the state of the specified resource is not // The request was rejected because the state of the specified resource is not
// valid for this request. // valid for this request.
// //
// For more information about how key state affects the use of a CMK, see How // For more information about how key state affects the use of a KMS key, see
// Key State Affects Use of a Customer Master Key (https://docs.aws.amazon.com/kms/latest/developerguide/key-state.html) // Key states of KMS keys (https://docs.aws.amazon.com/kms/latest/developerguide/key-state.html)
// in the AWS Key Management Service Developer Guide . // in the Key Management Service Developer Guide .
ErrCodeInvalidStateException = "KMSInvalidStateException" ErrCodeInvalidStateException = "KMSInvalidStateException"
// ErrCodeKMSInvalidMacException for service response error code
// "KMSInvalidMacException".
//
// The request was rejected because the HMAC verification failed. HMAC verification
// fails when the HMAC computed by using the specified message, HMAC KMS key,
// and MAC algorithm does not match the HMAC specified in the request.
ErrCodeKMSInvalidMacException = "KMSInvalidMacException"
// ErrCodeKMSInvalidSignatureException for service response error code // ErrCodeKMSInvalidSignatureException for service response error code
// "KMSInvalidSignatureException". // "KMSInvalidSignatureException".
// //
// The request was rejected because the signature verification failed. Signature // The request was rejected because the signature verification failed. Signature
// verification fails when it cannot confirm that signature was produced by // verification fails when it cannot confirm that signature was produced by
// signing the specified message with the specified CMK and signing algorithm. // signing the specified message with the specified KMS key and signing algorithm.
ErrCodeKMSInvalidSignatureException = "KMSInvalidSignatureException" ErrCodeKMSInvalidSignatureException = "KMSInvalidSignatureException"
// ErrCodeKeyUnavailableException for service response error code // ErrCodeKeyUnavailableException for service response error code
// "KeyUnavailableException". // "KeyUnavailableException".
// //
// The request was rejected because the specified CMK was not available. You // The request was rejected because the specified KMS key was not available.
// can retry the request. // You can retry the request.
ErrCodeKeyUnavailableException = "KeyUnavailableException" ErrCodeKeyUnavailableException = "KeyUnavailableException"
// ErrCodeLimitExceededException for service response error code // ErrCodeLimitExceededException for service response error code
@ -299,7 +307,7 @@ const (
// //
// The request was rejected because a quota was exceeded. For more information, // The request was rejected because a quota was exceeded. For more information,
// see Quotas (https://docs.aws.amazon.com/kms/latest/developerguide/limits.html) // see Quotas (https://docs.aws.amazon.com/kms/latest/developerguide/limits.html)
// in the AWS Key Management Service Developer Guide. // in the Key Management Service Developer Guide.
ErrCodeLimitExceededException = "LimitExceededException" ErrCodeLimitExceededException = "LimitExceededException"
// ErrCodeMalformedPolicyDocumentException for service response error code // ErrCodeMalformedPolicyDocumentException for service response error code
@ -357,6 +365,7 @@ var exceptionFromCode = map[string]func(protocol.ResponseMetadata) error{
"InvalidKeyUsageException": newErrorInvalidKeyUsageException, "InvalidKeyUsageException": newErrorInvalidKeyUsageException,
"InvalidMarkerException": newErrorInvalidMarkerException, "InvalidMarkerException": newErrorInvalidMarkerException,
"KMSInvalidStateException": newErrorInvalidStateException, "KMSInvalidStateException": newErrorInvalidStateException,
"KMSInvalidMacException": newErrorKMSInvalidMacException,
"KMSInvalidSignatureException": newErrorKMSInvalidSignatureException, "KMSInvalidSignatureException": newErrorKMSInvalidSignatureException,
"KeyUnavailableException": newErrorKeyUnavailableException, "KeyUnavailableException": newErrorKeyUnavailableException,
"LimitExceededException": newErrorLimitExceededException, "LimitExceededException": newErrorLimitExceededException,

View File

@ -40,33 +40,39 @@ const (
// aws.Config parameter to add your extra config. // aws.Config parameter to add your extra config.
// //
// Example: // Example:
// mySession := session.Must(session.NewSession())
// //
// // Create a KMS client from just a session. // mySession := session.Must(session.NewSession())
// svc := kms.New(mySession)
// //
// // Create a KMS client with additional configuration // // Create a KMS client from just a session.
// svc := kms.New(mySession, aws.NewConfig().WithRegion("us-west-2")) // svc := kms.New(mySession)
//
// // Create a KMS client with additional configuration
// svc := kms.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func New(p client.ConfigProvider, cfgs ...*aws.Config) *KMS { func New(p client.ConfigProvider, cfgs ...*aws.Config) *KMS {
c := p.ClientConfig(EndpointsID, cfgs...) c := p.ClientConfig(EndpointsID, cfgs...)
return newClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName) if c.SigningNameDerived || len(c.SigningName) == 0 {
c.SigningName = EndpointsID
// No Fallback
}
return newClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName, c.ResolvedRegion)
} }
// newClient creates, initializes and returns a new service client instance. // newClient creates, initializes and returns a new service client instance.
func newClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *KMS { func newClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName, resolvedRegion string) *KMS {
svc := &KMS{ svc := &KMS{
Client: client.New( Client: client.New(
cfg, cfg,
metadata.ClientInfo{ metadata.ClientInfo{
ServiceName: ServiceName, ServiceName: ServiceName,
ServiceID: ServiceID, ServiceID: ServiceID,
SigningName: signingName, SigningName: signingName,
SigningRegion: signingRegion, SigningRegion: signingRegion,
PartitionID: partitionID, PartitionID: partitionID,
Endpoint: endpoint, Endpoint: endpoint,
APIVersion: "2014-11-01", APIVersion: "2014-11-01",
JSONVersion: "1.1", ResolvedRegion: resolvedRegion,
TargetPrefix: "TrentService", JSONVersion: "1.1",
TargetPrefix: "TrentService",
}, },
handlers, handlers,
), ),

View File

@ -29,14 +29,13 @@ const opGetRoleCredentials = "GetRoleCredentials"
// This method is useful when you want to inject custom logic or configuration // This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic. // into the SDK's request lifecycle. Such as custom headers, or retry logic.
// //
// // Example sending a request using the GetRoleCredentialsRequest method.
// req, resp := client.GetRoleCredentialsRequest(params)
// //
// // Example sending a request using the GetRoleCredentialsRequest method. // err := req.Send()
// req, resp := client.GetRoleCredentialsRequest(params) // if err == nil { // resp is now filled
// // fmt.Println(resp)
// err := req.Send() // }
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
// //
// See also, https://docs.aws.amazon.com/goto/WebAPI/sso-2019-06-10/GetRoleCredentials // See also, https://docs.aws.amazon.com/goto/WebAPI/sso-2019-06-10/GetRoleCredentials
func (c *SSO) GetRoleCredentialsRequest(input *GetRoleCredentialsInput) (req *request.Request, output *GetRoleCredentialsOutput) { func (c *SSO) GetRoleCredentialsRequest(input *GetRoleCredentialsInput) (req *request.Request, output *GetRoleCredentialsOutput) {
@ -69,20 +68,21 @@ func (c *SSO) GetRoleCredentialsRequest(input *GetRoleCredentialsInput) (req *re
// API operation GetRoleCredentials for usage and error information. // API operation GetRoleCredentials for usage and error information.
// //
// Returned Error Types: // Returned Error Types:
// * InvalidRequestException
// Indicates that a problem occurred with the input to the request. For example,
// a required parameter might be missing or out of range.
// //
// * UnauthorizedException // - InvalidRequestException
// Indicates that the request is not authorized. This can happen due to an invalid // Indicates that a problem occurred with the input to the request. For example,
// access token in the request. // a required parameter might be missing or out of range.
// //
// * TooManyRequestsException // - UnauthorizedException
// Indicates that the request is being made too frequently and is more than // Indicates that the request is not authorized. This can happen due to an invalid
// what the server can handle. // access token in the request.
// //
// * ResourceNotFoundException // - TooManyRequestsException
// The specified resource doesn't exist. // Indicates that the request is being made too frequently and is more than
// what the server can handle.
//
// - ResourceNotFoundException
// The specified resource doesn't exist.
// //
// See also, https://docs.aws.amazon.com/goto/WebAPI/sso-2019-06-10/GetRoleCredentials // See also, https://docs.aws.amazon.com/goto/WebAPI/sso-2019-06-10/GetRoleCredentials
func (c *SSO) GetRoleCredentials(input *GetRoleCredentialsInput) (*GetRoleCredentialsOutput, error) { func (c *SSO) GetRoleCredentials(input *GetRoleCredentialsInput) (*GetRoleCredentialsOutput, error) {
@ -122,14 +122,13 @@ const opListAccountRoles = "ListAccountRoles"
// This method is useful when you want to inject custom logic or configuration // This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic. // into the SDK's request lifecycle. Such as custom headers, or retry logic.
// //
// // Example sending a request using the ListAccountRolesRequest method.
// req, resp := client.ListAccountRolesRequest(params)
// //
// // Example sending a request using the ListAccountRolesRequest method. // err := req.Send()
// req, resp := client.ListAccountRolesRequest(params) // if err == nil { // resp is now filled
// // fmt.Println(resp)
// err := req.Send() // }
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
// //
// See also, https://docs.aws.amazon.com/goto/WebAPI/sso-2019-06-10/ListAccountRoles // See also, https://docs.aws.amazon.com/goto/WebAPI/sso-2019-06-10/ListAccountRoles
func (c *SSO) ListAccountRolesRequest(input *ListAccountRolesInput) (req *request.Request, output *ListAccountRolesOutput) { func (c *SSO) ListAccountRolesRequest(input *ListAccountRolesInput) (req *request.Request, output *ListAccountRolesOutput) {
@ -167,20 +166,21 @@ func (c *SSO) ListAccountRolesRequest(input *ListAccountRolesInput) (req *reques
// API operation ListAccountRoles for usage and error information. // API operation ListAccountRoles for usage and error information.
// //
// Returned Error Types: // Returned Error Types:
// * InvalidRequestException
// Indicates that a problem occurred with the input to the request. For example,
// a required parameter might be missing or out of range.
// //
// * UnauthorizedException // - InvalidRequestException
// Indicates that the request is not authorized. This can happen due to an invalid // Indicates that a problem occurred with the input to the request. For example,
// access token in the request. // a required parameter might be missing or out of range.
// //
// * TooManyRequestsException // - UnauthorizedException
// Indicates that the request is being made too frequently and is more than // Indicates that the request is not authorized. This can happen due to an invalid
// what the server can handle. // access token in the request.
// //
// * ResourceNotFoundException // - TooManyRequestsException
// The specified resource doesn't exist. // Indicates that the request is being made too frequently and is more than
// what the server can handle.
//
// - ResourceNotFoundException
// The specified resource doesn't exist.
// //
// See also, https://docs.aws.amazon.com/goto/WebAPI/sso-2019-06-10/ListAccountRoles // See also, https://docs.aws.amazon.com/goto/WebAPI/sso-2019-06-10/ListAccountRoles
func (c *SSO) ListAccountRoles(input *ListAccountRolesInput) (*ListAccountRolesOutput, error) { func (c *SSO) ListAccountRoles(input *ListAccountRolesInput) (*ListAccountRolesOutput, error) {
@ -212,15 +212,14 @@ func (c *SSO) ListAccountRolesWithContext(ctx aws.Context, input *ListAccountRol
// //
// Note: This operation can generate multiple requests to a service. // Note: This operation can generate multiple requests to a service.
// //
// // Example iterating over at most 3 pages of a ListAccountRoles operation. // // Example iterating over at most 3 pages of a ListAccountRoles operation.
// pageNum := 0 // pageNum := 0
// err := client.ListAccountRolesPages(params, // err := client.ListAccountRolesPages(params,
// func(page *sso.ListAccountRolesOutput, lastPage bool) bool { // func(page *sso.ListAccountRolesOutput, lastPage bool) bool {
// pageNum++ // pageNum++
// fmt.Println(page) // fmt.Println(page)
// return pageNum <= 3 // return pageNum <= 3
// }) // })
//
func (c *SSO) ListAccountRolesPages(input *ListAccountRolesInput, fn func(*ListAccountRolesOutput, bool) bool) error { func (c *SSO) ListAccountRolesPages(input *ListAccountRolesInput, fn func(*ListAccountRolesOutput, bool) bool) error {
return c.ListAccountRolesPagesWithContext(aws.BackgroundContext(), input, fn) return c.ListAccountRolesPagesWithContext(aws.BackgroundContext(), input, fn)
} }
@ -272,14 +271,13 @@ const opListAccounts = "ListAccounts"
// This method is useful when you want to inject custom logic or configuration // This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic. // into the SDK's request lifecycle. Such as custom headers, or retry logic.
// //
// // Example sending a request using the ListAccountsRequest method.
// req, resp := client.ListAccountsRequest(params)
// //
// // Example sending a request using the ListAccountsRequest method. // err := req.Send()
// req, resp := client.ListAccountsRequest(params) // if err == nil { // resp is now filled
// // fmt.Println(resp)
// err := req.Send() // }
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
// //
// See also, https://docs.aws.amazon.com/goto/WebAPI/sso-2019-06-10/ListAccounts // See also, https://docs.aws.amazon.com/goto/WebAPI/sso-2019-06-10/ListAccounts
func (c *SSO) ListAccountsRequest(input *ListAccountsInput) (req *request.Request, output *ListAccountsOutput) { func (c *SSO) ListAccountsRequest(input *ListAccountsInput) (req *request.Request, output *ListAccountsOutput) {
@ -310,7 +308,8 @@ func (c *SSO) ListAccountsRequest(input *ListAccountsInput) (req *request.Reques
// Lists all AWS accounts assigned to the user. These AWS accounts are assigned // Lists all AWS accounts assigned to the user. These AWS accounts are assigned
// by the administrator of the account. For more information, see Assign User // by the administrator of the account. For more information, see Assign User
// Access (https://docs.aws.amazon.com/singlesignon/latest/userguide/useraccess.html#assignusers) // Access (https://docs.aws.amazon.com/singlesignon/latest/userguide/useraccess.html#assignusers)
// in the AWS SSO User Guide. This operation returns a paginated response. // in the IAM Identity Center User Guide. This operation returns a paginated
// response.
// //
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions // Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about // with awserr.Error's Code and Message methods to get detailed information about
@ -320,20 +319,21 @@ func (c *SSO) ListAccountsRequest(input *ListAccountsInput) (req *request.Reques
// API operation ListAccounts for usage and error information. // API operation ListAccounts for usage and error information.
// //
// Returned Error Types: // Returned Error Types:
// * InvalidRequestException
// Indicates that a problem occurred with the input to the request. For example,
// a required parameter might be missing or out of range.
// //
// * UnauthorizedException // - InvalidRequestException
// Indicates that the request is not authorized. This can happen due to an invalid // Indicates that a problem occurred with the input to the request. For example,
// access token in the request. // a required parameter might be missing or out of range.
// //
// * TooManyRequestsException // - UnauthorizedException
// Indicates that the request is being made too frequently and is more than // Indicates that the request is not authorized. This can happen due to an invalid
// what the server can handle. // access token in the request.
// //
// * ResourceNotFoundException // - TooManyRequestsException
// The specified resource doesn't exist. // Indicates that the request is being made too frequently and is more than
// what the server can handle.
//
// - ResourceNotFoundException
// The specified resource doesn't exist.
// //
// See also, https://docs.aws.amazon.com/goto/WebAPI/sso-2019-06-10/ListAccounts // See also, https://docs.aws.amazon.com/goto/WebAPI/sso-2019-06-10/ListAccounts
func (c *SSO) ListAccounts(input *ListAccountsInput) (*ListAccountsOutput, error) { func (c *SSO) ListAccounts(input *ListAccountsInput) (*ListAccountsOutput, error) {
@ -365,15 +365,14 @@ func (c *SSO) ListAccountsWithContext(ctx aws.Context, input *ListAccountsInput,
// //
// Note: This operation can generate multiple requests to a service. // Note: This operation can generate multiple requests to a service.
// //
// // Example iterating over at most 3 pages of a ListAccounts operation. // // Example iterating over at most 3 pages of a ListAccounts operation.
// pageNum := 0 // pageNum := 0
// err := client.ListAccountsPages(params, // err := client.ListAccountsPages(params,
// func(page *sso.ListAccountsOutput, lastPage bool) bool { // func(page *sso.ListAccountsOutput, lastPage bool) bool {
// pageNum++ // pageNum++
// fmt.Println(page) // fmt.Println(page)
// return pageNum <= 3 // return pageNum <= 3
// }) // })
//
func (c *SSO) ListAccountsPages(input *ListAccountsInput, fn func(*ListAccountsOutput, bool) bool) error { func (c *SSO) ListAccountsPages(input *ListAccountsInput, fn func(*ListAccountsOutput, bool) bool) error {
return c.ListAccountsPagesWithContext(aws.BackgroundContext(), input, fn) return c.ListAccountsPagesWithContext(aws.BackgroundContext(), input, fn)
} }
@ -425,14 +424,13 @@ const opLogout = "Logout"
// This method is useful when you want to inject custom logic or configuration // This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic. // into the SDK's request lifecycle. Such as custom headers, or retry logic.
// //
// // Example sending a request using the LogoutRequest method.
// req, resp := client.LogoutRequest(params)
// //
// // Example sending a request using the LogoutRequest method. // err := req.Send()
// req, resp := client.LogoutRequest(params) // if err == nil { // resp is now filled
// // fmt.Println(resp)
// err := req.Send() // }
// if err == nil { // resp is now filled
// fmt.Println(resp)
// }
// //
// See also, https://docs.aws.amazon.com/goto/WebAPI/sso-2019-06-10/Logout // See also, https://docs.aws.amazon.com/goto/WebAPI/sso-2019-06-10/Logout
func (c *SSO) LogoutRequest(input *LogoutInput) (req *request.Request, output *LogoutOutput) { func (c *SSO) LogoutRequest(input *LogoutInput) (req *request.Request, output *LogoutOutput) {
@ -455,7 +453,21 @@ func (c *SSO) LogoutRequest(input *LogoutInput) (req *request.Request, output *L
// Logout API operation for AWS Single Sign-On. // Logout API operation for AWS Single Sign-On.
// //
// Removes the client- and server-side session that is associated with the user. // Removes the locally stored SSO tokens from the client-side cache and sends
// an API call to the IAM Identity Center service to invalidate the corresponding
// server-side IAM Identity Center sign in session.
//
// If a user uses IAM Identity Center to access the AWS CLI, the users IAM
// Identity Center sign in session is used to obtain an IAM session, as specified
// in the corresponding IAM Identity Center permission set. More specifically,
// IAM Identity Center assumes an IAM role in the target account on behalf of
// the user, and the corresponding temporary AWS credentials are returned to
// the client.
//
// After user logout, any existing IAM role sessions that were created by using
// IAM Identity Center permission sets continue based on the duration configured
// in the permission set. For more information, see User authentications (https://docs.aws.amazon.com/singlesignon/latest/userguide/authconcept.html)
// in the IAM Identity Center User Guide.
// //
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions // Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about // with awserr.Error's Code and Message methods to get detailed information about
@ -465,17 +477,18 @@ func (c *SSO) LogoutRequest(input *LogoutInput) (req *request.Request, output *L
// API operation Logout for usage and error information. // API operation Logout for usage and error information.
// //
// Returned Error Types: // Returned Error Types:
// * InvalidRequestException
// Indicates that a problem occurred with the input to the request. For example,
// a required parameter might be missing or out of range.
// //
// * UnauthorizedException // - InvalidRequestException
// Indicates that the request is not authorized. This can happen due to an invalid // Indicates that a problem occurred with the input to the request. For example,
// access token in the request. // a required parameter might be missing or out of range.
// //
// * TooManyRequestsException // - UnauthorizedException
// Indicates that the request is being made too frequently and is more than // Indicates that the request is not authorized. This can happen due to an invalid
// what the server can handle. // access token in the request.
//
// - TooManyRequestsException
// Indicates that the request is being made too frequently and is more than
// what the server can handle.
// //
// See also, https://docs.aws.amazon.com/goto/WebAPI/sso-2019-06-10/Logout // See also, https://docs.aws.amazon.com/goto/WebAPI/sso-2019-06-10/Logout
func (c *SSO) Logout(input *LogoutInput) (*LogoutOutput, error) { func (c *SSO) Logout(input *LogoutInput) (*LogoutOutput, error) {
@ -513,12 +526,20 @@ type AccountInfo struct {
EmailAddress *string `locationName:"emailAddress" min:"1" type:"string"` EmailAddress *string `locationName:"emailAddress" min:"1" type:"string"`
} }
// String returns the string representation // String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s AccountInfo) String() string { func (s AccountInfo) String() string {
return awsutil.Prettify(s) return awsutil.Prettify(s)
} }
// GoString returns the string representation // GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s AccountInfo) GoString() string { func (s AccountInfo) GoString() string {
return s.String() return s.String()
} }
@ -542,11 +563,15 @@ func (s *AccountInfo) SetEmailAddress(v string) *AccountInfo {
} }
type GetRoleCredentialsInput struct { type GetRoleCredentialsInput struct {
_ struct{} `type:"structure"` _ struct{} `type:"structure" nopayload:"true"`
// The token issued by the CreateToken API call. For more information, see CreateToken // The token issued by the CreateToken API call. For more information, see CreateToken
// (https://docs.aws.amazon.com/singlesignon/latest/OIDCAPIReference/API_CreateToken.html) // (https://docs.aws.amazon.com/singlesignon/latest/OIDCAPIReference/API_CreateToken.html)
// in the AWS SSO OIDC API Reference Guide. // in the IAM Identity Center OIDC API Reference Guide.
//
// AccessToken is a sensitive parameter and its value will be
// replaced with "sensitive" in string returned by GetRoleCredentialsInput's
// String and GoString methods.
// //
// AccessToken is a required field // AccessToken is a required field
AccessToken *string `location:"header" locationName:"x-amz-sso_bearer_token" type:"string" required:"true" sensitive:"true"` AccessToken *string `location:"header" locationName:"x-amz-sso_bearer_token" type:"string" required:"true" sensitive:"true"`
@ -562,12 +587,20 @@ type GetRoleCredentialsInput struct {
RoleName *string `location:"querystring" locationName:"role_name" type:"string" required:"true"` RoleName *string `location:"querystring" locationName:"role_name" type:"string" required:"true"`
} }
// String returns the string representation // String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GetRoleCredentialsInput) String() string { func (s GetRoleCredentialsInput) String() string {
return awsutil.Prettify(s) return awsutil.Prettify(s)
} }
// GoString returns the string representation // GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GetRoleCredentialsInput) GoString() string { func (s GetRoleCredentialsInput) GoString() string {
return s.String() return s.String()
} }
@ -616,12 +649,20 @@ type GetRoleCredentialsOutput struct {
RoleCredentials *RoleCredentials `locationName:"roleCredentials" type:"structure"` RoleCredentials *RoleCredentials `locationName:"roleCredentials" type:"structure"`
} }
// String returns the string representation // String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GetRoleCredentialsOutput) String() string { func (s GetRoleCredentialsOutput) String() string {
return awsutil.Prettify(s) return awsutil.Prettify(s)
} }
// GoString returns the string representation // GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s GetRoleCredentialsOutput) GoString() string { func (s GetRoleCredentialsOutput) GoString() string {
return s.String() return s.String()
} }
@ -641,12 +682,20 @@ type InvalidRequestException struct {
Message_ *string `locationName:"message" type:"string"` Message_ *string `locationName:"message" type:"string"`
} }
// String returns the string representation // String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s InvalidRequestException) String() string { func (s InvalidRequestException) String() string {
return awsutil.Prettify(s) return awsutil.Prettify(s)
} }
// GoString returns the string representation // GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s InvalidRequestException) GoString() string { func (s InvalidRequestException) GoString() string {
return s.String() return s.String()
} }
@ -690,11 +739,15 @@ func (s *InvalidRequestException) RequestID() string {
} }
type ListAccountRolesInput struct { type ListAccountRolesInput struct {
_ struct{} `type:"structure"` _ struct{} `type:"structure" nopayload:"true"`
// The token issued by the CreateToken API call. For more information, see CreateToken // The token issued by the CreateToken API call. For more information, see CreateToken
// (https://docs.aws.amazon.com/singlesignon/latest/OIDCAPIReference/API_CreateToken.html) // (https://docs.aws.amazon.com/singlesignon/latest/OIDCAPIReference/API_CreateToken.html)
// in the AWS SSO OIDC API Reference Guide. // in the IAM Identity Center OIDC API Reference Guide.
//
// AccessToken is a sensitive parameter and its value will be
// replaced with "sensitive" in string returned by ListAccountRolesInput's
// String and GoString methods.
// //
// AccessToken is a required field // AccessToken is a required field
AccessToken *string `location:"header" locationName:"x-amz-sso_bearer_token" type:"string" required:"true" sensitive:"true"` AccessToken *string `location:"header" locationName:"x-amz-sso_bearer_token" type:"string" required:"true" sensitive:"true"`
@ -712,12 +765,20 @@ type ListAccountRolesInput struct {
NextToken *string `location:"querystring" locationName:"next_token" type:"string"` NextToken *string `location:"querystring" locationName:"next_token" type:"string"`
} }
// String returns the string representation // String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListAccountRolesInput) String() string { func (s ListAccountRolesInput) String() string {
return awsutil.Prettify(s) return awsutil.Prettify(s)
} }
// GoString returns the string representation // GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListAccountRolesInput) GoString() string { func (s ListAccountRolesInput) GoString() string {
return s.String() return s.String()
} }
@ -776,12 +837,20 @@ type ListAccountRolesOutput struct {
RoleList []*RoleInfo `locationName:"roleList" type:"list"` RoleList []*RoleInfo `locationName:"roleList" type:"list"`
} }
// String returns the string representation // String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListAccountRolesOutput) String() string { func (s ListAccountRolesOutput) String() string {
return awsutil.Prettify(s) return awsutil.Prettify(s)
} }
// GoString returns the string representation // GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListAccountRolesOutput) GoString() string { func (s ListAccountRolesOutput) GoString() string {
return s.String() return s.String()
} }
@ -799,11 +868,15 @@ func (s *ListAccountRolesOutput) SetRoleList(v []*RoleInfo) *ListAccountRolesOut
} }
type ListAccountsInput struct { type ListAccountsInput struct {
_ struct{} `type:"structure"` _ struct{} `type:"structure" nopayload:"true"`
// The token issued by the CreateToken API call. For more information, see CreateToken // The token issued by the CreateToken API call. For more information, see CreateToken
// (https://docs.aws.amazon.com/singlesignon/latest/OIDCAPIReference/API_CreateToken.html) // (https://docs.aws.amazon.com/singlesignon/latest/OIDCAPIReference/API_CreateToken.html)
// in the AWS SSO OIDC API Reference Guide. // in the IAM Identity Center OIDC API Reference Guide.
//
// AccessToken is a sensitive parameter and its value will be
// replaced with "sensitive" in string returned by ListAccountsInput's
// String and GoString methods.
// //
// AccessToken is a required field // AccessToken is a required field
AccessToken *string `location:"header" locationName:"x-amz-sso_bearer_token" type:"string" required:"true" sensitive:"true"` AccessToken *string `location:"header" locationName:"x-amz-sso_bearer_token" type:"string" required:"true" sensitive:"true"`
@ -816,12 +889,20 @@ type ListAccountsInput struct {
NextToken *string `location:"querystring" locationName:"next_token" type:"string"` NextToken *string `location:"querystring" locationName:"next_token" type:"string"`
} }
// String returns the string representation // String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListAccountsInput) String() string { func (s ListAccountsInput) String() string {
return awsutil.Prettify(s) return awsutil.Prettify(s)
} }
// GoString returns the string representation // GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListAccountsInput) GoString() string { func (s ListAccountsInput) GoString() string {
return s.String() return s.String()
} }
@ -871,12 +952,20 @@ type ListAccountsOutput struct {
NextToken *string `locationName:"nextToken" type:"string"` NextToken *string `locationName:"nextToken" type:"string"`
} }
// String returns the string representation // String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListAccountsOutput) String() string { func (s ListAccountsOutput) String() string {
return awsutil.Prettify(s) return awsutil.Prettify(s)
} }
// GoString returns the string representation // GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ListAccountsOutput) GoString() string { func (s ListAccountsOutput) GoString() string {
return s.String() return s.String()
} }
@ -894,22 +983,34 @@ func (s *ListAccountsOutput) SetNextToken(v string) *ListAccountsOutput {
} }
type LogoutInput struct { type LogoutInput struct {
_ struct{} `type:"structure"` _ struct{} `type:"structure" nopayload:"true"`
// The token issued by the CreateToken API call. For more information, see CreateToken // The token issued by the CreateToken API call. For more information, see CreateToken
// (https://docs.aws.amazon.com/singlesignon/latest/OIDCAPIReference/API_CreateToken.html) // (https://docs.aws.amazon.com/singlesignon/latest/OIDCAPIReference/API_CreateToken.html)
// in the AWS SSO OIDC API Reference Guide. // in the IAM Identity Center OIDC API Reference Guide.
//
// AccessToken is a sensitive parameter and its value will be
// replaced with "sensitive" in string returned by LogoutInput's
// String and GoString methods.
// //
// AccessToken is a required field // AccessToken is a required field
AccessToken *string `location:"header" locationName:"x-amz-sso_bearer_token" type:"string" required:"true" sensitive:"true"` AccessToken *string `location:"header" locationName:"x-amz-sso_bearer_token" type:"string" required:"true" sensitive:"true"`
} }
// String returns the string representation // String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s LogoutInput) String() string { func (s LogoutInput) String() string {
return awsutil.Prettify(s) return awsutil.Prettify(s)
} }
// GoString returns the string representation // GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s LogoutInput) GoString() string { func (s LogoutInput) GoString() string {
return s.String() return s.String()
} }
@ -937,12 +1038,20 @@ type LogoutOutput struct {
_ struct{} `type:"structure"` _ struct{} `type:"structure"`
} }
// String returns the string representation // String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s LogoutOutput) String() string { func (s LogoutOutput) String() string {
return awsutil.Prettify(s) return awsutil.Prettify(s)
} }
// GoString returns the string representation // GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s LogoutOutput) GoString() string { func (s LogoutOutput) GoString() string {
return s.String() return s.String()
} }
@ -955,12 +1064,20 @@ type ResourceNotFoundException struct {
Message_ *string `locationName:"message" type:"string"` Message_ *string `locationName:"message" type:"string"`
} }
// String returns the string representation // String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ResourceNotFoundException) String() string { func (s ResourceNotFoundException) String() string {
return awsutil.Prettify(s) return awsutil.Prettify(s)
} }
// GoString returns the string representation // GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s ResourceNotFoundException) GoString() string { func (s ResourceNotFoundException) GoString() string {
return s.String() return s.String()
} }
@ -1020,20 +1137,36 @@ type RoleCredentials struct {
// The key that is used to sign the request. For more information, see Using // The key that is used to sign the request. For more information, see Using
// Temporary Security Credentials to Request Access to AWS Resources (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_use-resources.html) // Temporary Security Credentials to Request Access to AWS Resources (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_use-resources.html)
// in the AWS IAM User Guide. // in the AWS IAM User Guide.
//
// SecretAccessKey is a sensitive parameter and its value will be
// replaced with "sensitive" in string returned by RoleCredentials's
// String and GoString methods.
SecretAccessKey *string `locationName:"secretAccessKey" type:"string" sensitive:"true"` SecretAccessKey *string `locationName:"secretAccessKey" type:"string" sensitive:"true"`
// The token used for temporary credentials. For more information, see Using // The token used for temporary credentials. For more information, see Using
// Temporary Security Credentials to Request Access to AWS Resources (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_use-resources.html) // Temporary Security Credentials to Request Access to AWS Resources (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_use-resources.html)
// in the AWS IAM User Guide. // in the AWS IAM User Guide.
//
// SessionToken is a sensitive parameter and its value will be
// replaced with "sensitive" in string returned by RoleCredentials's
// String and GoString methods.
SessionToken *string `locationName:"sessionToken" type:"string" sensitive:"true"` SessionToken *string `locationName:"sessionToken" type:"string" sensitive:"true"`
} }
// String returns the string representation // String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s RoleCredentials) String() string { func (s RoleCredentials) String() string {
return awsutil.Prettify(s) return awsutil.Prettify(s)
} }
// GoString returns the string representation // GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s RoleCredentials) GoString() string { func (s RoleCredentials) GoString() string {
return s.String() return s.String()
} }
@ -1073,12 +1206,20 @@ type RoleInfo struct {
RoleName *string `locationName:"roleName" type:"string"` RoleName *string `locationName:"roleName" type:"string"`
} }
// String returns the string representation // String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s RoleInfo) String() string { func (s RoleInfo) String() string {
return awsutil.Prettify(s) return awsutil.Prettify(s)
} }
// GoString returns the string representation // GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s RoleInfo) GoString() string { func (s RoleInfo) GoString() string {
return s.String() return s.String()
} }
@ -1104,12 +1245,20 @@ type TooManyRequestsException struct {
Message_ *string `locationName:"message" type:"string"` Message_ *string `locationName:"message" type:"string"`
} }
// String returns the string representation // String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s TooManyRequestsException) String() string { func (s TooManyRequestsException) String() string {
return awsutil.Prettify(s) return awsutil.Prettify(s)
} }
// GoString returns the string representation // GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s TooManyRequestsException) GoString() string { func (s TooManyRequestsException) GoString() string {
return s.String() return s.String()
} }
@ -1161,12 +1310,20 @@ type UnauthorizedException struct {
Message_ *string `locationName:"message" type:"string"` Message_ *string `locationName:"message" type:"string"`
} }
// String returns the string representation // String returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s UnauthorizedException) String() string { func (s UnauthorizedException) String() string {
return awsutil.Prettify(s) return awsutil.Prettify(s)
} }
// GoString returns the string representation // GoString returns the string representation.
//
// API parameter values that are decorated as "sensitive" in the API will not
// be included in the string output. The member name will be present, but the
// value will be replaced with "sensitive".
func (s UnauthorizedException) GoString() string { func (s UnauthorizedException) GoString() string {
return s.String() return s.String()
} }

View File

@ -3,30 +3,31 @@
// Package sso provides the client and types for making API // Package sso provides the client and types for making API
// requests to AWS Single Sign-On. // requests to AWS Single Sign-On.
// //
// AWS Single Sign-On Portal is a web service that makes it easy for you to // AWS IAM Identity Center (successor to AWS Single Sign-On) Portal is a web
// assign user access to AWS SSO resources such as the user portal. Users can // service that makes it easy for you to assign user access to IAM Identity
// get AWS account applications and roles assigned to them and get federated // Center resources such as the AWS access portal. Users can get AWS account
// into the application. // applications and roles assigned to them and get federated into the application.
// //
// For general information about AWS SSO, see What is AWS Single Sign-On? (https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html) // Although AWS Single Sign-On was renamed, the sso and identitystore API namespaces
// in the AWS SSO User Guide. // will continue to retain their original name for backward compatibility purposes.
// For more information, see IAM Identity Center rename (https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html#renamed).
// //
// This API reference guide describes the AWS SSO Portal operations that you // This reference guide describes the IAM Identity Center Portal operations
// can call programatically and includes detailed information on data types // that you can call programatically and includes detailed information on data
// and errors. // types and errors.
// //
// AWS provides SDKs that consist of libraries and sample code for various programming // AWS provides SDKs that consist of libraries and sample code for various programming
// languages and platforms, such as Java, Ruby, .Net, iOS, or Android. The SDKs // languages and platforms, such as Java, Ruby, .Net, iOS, or Android. The SDKs
// provide a convenient way to create programmatic access to AWS SSO and other // provide a convenient way to create programmatic access to IAM Identity Center
// AWS services. For more information about the AWS SDKs, including how to download // and other AWS services. For more information about the AWS SDKs, including
// and install them, see Tools for Amazon Web Services (http://aws.amazon.com/tools/). // how to download and install them, see Tools for Amazon Web Services (http://aws.amazon.com/tools/).
// //
// See https://docs.aws.amazon.com/goto/WebAPI/sso-2019-06-10 for more information on this service. // See https://docs.aws.amazon.com/goto/WebAPI/sso-2019-06-10 for more information on this service.
// //
// See sso package documentation for more information. // See sso package documentation for more information.
// https://docs.aws.amazon.com/sdk-for-go/api/service/sso/ // https://docs.aws.amazon.com/sdk-for-go/api/service/sso/
// //
// Using the Client // # Using the Client
// //
// To contact AWS Single Sign-On with the SDK use the New function to create // To contact AWS Single Sign-On with the SDK use the New function to create
// a new service client. With that client you can make API requests to the service. // a new service client. With that client you can make API requests to the service.

View File

@ -40,34 +40,36 @@ const (
// aws.Config parameter to add your extra config. // aws.Config parameter to add your extra config.
// //
// Example: // Example:
// mySession := session.Must(session.NewSession())
// //
// // Create a SSO client from just a session. // mySession := session.Must(session.NewSession())
// svc := sso.New(mySession)
// //
// // Create a SSO client with additional configuration // // Create a SSO client from just a session.
// svc := sso.New(mySession, aws.NewConfig().WithRegion("us-west-2")) // svc := sso.New(mySession)
//
// // Create a SSO client with additional configuration
// svc := sso.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func New(p client.ConfigProvider, cfgs ...*aws.Config) *SSO { func New(p client.ConfigProvider, cfgs ...*aws.Config) *SSO {
c := p.ClientConfig(EndpointsID, cfgs...) c := p.ClientConfig(EndpointsID, cfgs...)
if c.SigningNameDerived || len(c.SigningName) == 0 { if c.SigningNameDerived || len(c.SigningName) == 0 {
c.SigningName = "awsssoportal" c.SigningName = "awsssoportal"
} }
return newClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName) return newClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName, c.ResolvedRegion)
} }
// newClient creates, initializes and returns a new service client instance. // newClient creates, initializes and returns a new service client instance.
func newClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *SSO { func newClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName, resolvedRegion string) *SSO {
svc := &SSO{ svc := &SSO{
Client: client.New( Client: client.New(
cfg, cfg,
metadata.ClientInfo{ metadata.ClientInfo{
ServiceName: ServiceName, ServiceName: ServiceName,
ServiceID: ServiceID, ServiceID: ServiceID,
SigningName: signingName, SigningName: signingName,
SigningRegion: signingRegion, SigningRegion: signingRegion,
PartitionID: partitionID, PartitionID: partitionID,
Endpoint: endpoint, Endpoint: endpoint,
APIVersion: "2019-06-10", APIVersion: "2019-06-10",
ResolvedRegion: resolvedRegion,
}, },
handlers, handlers,
), ),

View File

@ -23,37 +23,37 @@ import (
// can be stubbed out for unit testing your code with the SDK without needing // can be stubbed out for unit testing your code with the SDK without needing
// to inject custom request handlers into the SDK's request pipeline. // to inject custom request handlers into the SDK's request pipeline.
// //
// // myFunc uses an SDK service client to make a request to // // myFunc uses an SDK service client to make a request to
// // AWS Single Sign-On. // // AWS Single Sign-On.
// func myFunc(svc ssoiface.SSOAPI) bool { // func myFunc(svc ssoiface.SSOAPI) bool {
// // Make svc.GetRoleCredentials request // // Make svc.GetRoleCredentials request
// } // }
// //
// func main() { // func main() {
// sess := session.New() // sess := session.New()
// svc := sso.New(sess) // svc := sso.New(sess)
// //
// myFunc(svc) // myFunc(svc)
// } // }
// //
// In your _test.go file: // In your _test.go file:
// //
// // Define a mock struct to be used in your unit tests of myFunc. // // Define a mock struct to be used in your unit tests of myFunc.
// type mockSSOClient struct { // type mockSSOClient struct {
// ssoiface.SSOAPI // ssoiface.SSOAPI
// } // }
// func (m *mockSSOClient) GetRoleCredentials(input *sso.GetRoleCredentialsInput) (*sso.GetRoleCredentialsOutput, error) { // func (m *mockSSOClient) GetRoleCredentials(input *sso.GetRoleCredentialsInput) (*sso.GetRoleCredentialsOutput, error) {
// // mock response/functionality // // mock response/functionality
// } // }
// //
// func TestMyFunc(t *testing.T) { // func TestMyFunc(t *testing.T) {
// // Setup Test // // Setup Test
// mockSvc := &mockSSOClient{} // mockSvc := &mockSSOClient{}
// //
// myfunc(mockSvc) // myfunc(mockSvc)
// //
// // Verify myFunc's functionality // // Verify myFunc's functionality
// } // }
// //
// It is important to note that this interface will have breaking changes // It is important to note that this interface will have breaking changes
// when the service model is updated and adds new API operations, paginators, // when the service model is updated and adds new API operations, paginators,

Some files were not shown because too many files have changed in this diff Show More