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/armon/circbuf v0.0.0-20150827004946-bbbad097214e
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/container-storage-interface/spec v1.6.0
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/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/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/beorn7/perks => github.com/beorn7/perks v1.0.1
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/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/aws/aws-sdk-go v1.38.49 h1:E31vxjCe6a5I+mJLmUGaZobiWmg9KdWaud9IfceYeYQ=
github.com/aws/aws-sdk-go v1.38.49/go.mod h1:hcU610XS61/+aQV88ixoOzUoG7v3b31pl2zKMmprdro=
github.com/aws/aws-sdk-go v1.44.116 h1:NpLIhcvLWXJZAEwvPj3TDHeqp7DleK6ZUVYyW01WNHY=
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/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA=
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/to v0.4.0
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/google/go-cmp v0.5.9
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-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho=
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.38.49/go.mod h1:hcU610XS61/+aQV88ixoOzUoG7v3b31pl2zKMmprdro=
github.com/aws/aws-sdk-go v1.44.116 h1:NpLIhcvLWXJZAEwvPj3TDHeqp7DleK6ZUVYyW01WNHY=
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 v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8=
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 {
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(n + ": ")
if tag := ft.Tag.Get("sensitive"); tag == "true" {
buf.WriteString("<sensitive>")
} else {
prettify(val, indent+2, buf)
}
if i < len(names)-1 {
buf.WriteString(",\n")

View File

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

View File

@ -16,6 +16,7 @@ type Config struct {
Endpoint string
SigningRegion string
SigningName string
ResolvedRegion string
// States that the signing name did not come from a modeled source but
// 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) {
if !r.Config.LogLevel.AtLeast(aws.LogDebug) {
if !r.Config.LogLevel.AtLeast(aws.LogDebug) || r.Config.Logger == nil {
return
}
@ -94,6 +94,10 @@ var LogHTTPRequestHeaderHandler = request.NamedHandler{
}
func logRequestHeader(r *request.Request) {
if !r.Config.LogLevel.AtLeast(aws.LogDebug) || r.Config.Logger == nil {
return
}
b, err := httputil.DumpRequestOut(r.HTTPRequest, false)
if err != nil {
r.Config.Logger.Log(fmt.Sprintf(logReqErrMsg,
@ -124,7 +128,7 @@ var LogHTTPResponseHandler = request.NamedHandler{
}
func logResponse(r *request.Request) {
if !r.Config.LogLevel.AtLeast(aws.LogDebug) {
if !r.Config.LogLevel.AtLeast(aws.LogDebug) || r.Config.Logger == nil {
return
}
@ -186,7 +190,7 @@ var LogHTTPResponseHeaderHandler = request.NamedHandler{
}
func logResponseHeader(r *request.Request) {
if r.Config.Logger == nil {
if !r.Config.LogLevel.AtLeast(aws.LogDebug) || r.Config.Logger == nil {
return
}

View File

@ -11,4 +11,5 @@ type ClientInfo struct {
SigningRegion string
JSONVersion 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
// 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
// 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{
// 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
// 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
// during the lifecycle of a request. Specifically this will be used for
// 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
}
if other.UseDualStackEndpoint != endpoints.DualStackEndpointStateUnset {
dst.UseDualStackEndpoint = other.UseDualStackEndpoint
}
if other.EC2MetadataDisableTimeoutOverride != nil {
dst.EC2MetadataDisableTimeoutOverride = other.EC2MetadataDisableTimeoutOverride
}
@ -589,6 +607,14 @@ func mergeInConfig(dst *Config, other *Config) {
if other.LowerCaseHeaderMaps != nil {
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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -13,7 +13,6 @@ package ec2metadata
import (
"bytes"
"errors"
"io"
"net/http"
"net/url"
@ -234,7 +233,8 @@ func unmarshalError(r *request.Request) {
// Response body format is not consistent between metadata endpoints.
// 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)
}

View File

@ -81,8 +81,6 @@ func decodeV3Endpoints(modelDef modelDefinition, opts DecodeModelOptions) (Resol
// Customization
for i := 0; i < len(ps); i++ {
p := &ps[i]
custAddEC2Metadata(p)
custAddS3DualStack(p)
custRegionalS3(p)
custRmIotDataService(p)
custFixAppAutoscalingChina(p)
@ -92,15 +90,6 @@ func decodeV3Endpoints(modelDef modelDefinition, opts DecodeModelOptions) (Resol
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) {
if p.ID != "aws" {
return
@ -111,48 +100,28 @@ func custRegionalS3(p *partition) {
return
}
const awsGlobal = "aws-global"
const usEast1 = "us-east-1"
// If global endpoint already exists no customization needed.
if _, ok := service.Endpoints["aws-global"]; ok {
if _, ok := service.Endpoints[endpointKey{Region: awsGlobal}]; ok {
return
}
service.PartitionEndpoint = "aws-global"
service.Endpoints["us-east-1"] = endpoint{}
service.Endpoints["aws-global"] = endpoint{
service.PartitionEndpoint = awsGlobal
if _, ok := service.Endpoints[endpointKey{Region: usEast1}]; !ok {
service.Endpoints[endpointKey{Region: usEast1}] = endpoint{}
}
service.Endpoints[endpointKey{Region: awsGlobal}] = endpoint{
Hostname: "s3.amazonaws.com",
CredentialScope: credentialScope{
Region: "us-east-1",
Region: usEast1,
},
}
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) {
delete(p.Services, "data.iot")
}
@ -169,12 +138,13 @@ func custFixAppAutoscalingChina(p *partition) {
}
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)
return
}
s.Defaults.Hostname = expectHostname + ".cn"
serviceDefault.Hostname = expectHostname + ".cn"
s.Defaults[defaultKey{}] = serviceDefault
p.Services[serviceName] = s
}
@ -189,18 +159,25 @@ func custFixAppAutoscalingUsGov(p *partition) {
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)
return
}
if a := s.Defaults.Hostname; a != "" {
if a := serviceDefault.Hostname; a != "" {
fmt.Printf("custFixAppAutoscalingUsGov: ignoring customization, expected empty hostname, got %s\n", a)
return
}
s.Defaults.CredentialScope.Service = "application-autoscaling"
s.Defaults.Hostname = "autoscaling.{region}.amazonaws.com"
serviceDefault.CredentialScope.Service = "application-autoscaling"
serviceDefault.Hostname = "autoscaling.{region}.amazonaws.com"
if s.Defaults == nil {
s.Defaults = make(endpointDefaults)
}
s.Defaults[defaultKey{}] = serviceDefault
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).
// .
//
// Enumerating Regions and Endpoint Metadata
// # Enumerating Regions and Endpoint Metadata
//
// Casting the Resolver returned by DefaultResolver to a EnumPartitions interface
// will allow you to get access to the list of underlying Partitions with the
@ -32,7 +32,7 @@
// }
// }
//
// Using Custom Endpoints
// # Using Custom Endpoints
//
// 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
@ -47,7 +47,6 @@
// of Resolver.EndpointFor, converting it to a type that satisfies the
// Resolver interface.
//
//
// myCustomResolver := func(service, region string, optFns ...func(*endpoints.Options)) (endpoints.ResolvedEndpoint, error) {
// if service == endpoints.S3ServiceID {
// return endpoints.ResolvedEndpoint{

View File

@ -8,6 +8,41 @@ import (
"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
// endpoints will be resolved.
type Options struct {
@ -21,8 +56,19 @@ type Options struct {
// be returned. This endpoint may not be valid. If StrictMatching is
// enabled only services that are known to support dualstack will return
// 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
// 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.
// If the partition doesn't enumerate the exact service and region an
// 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.
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
STSRegionalEndpoint STSRegionalEndpoint
// S3 Regional Endpoint flag helps with resolving the S3 endpoint
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
@ -166,10 +266,25 @@ func DisableSSLOption(o *Options) {
// UseDualStackOption sets the UseDualStack option. Can be used as a functional
// 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) {
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
// option when resolving endpoints.
func StrictMatchingOption(o *Options) {
@ -238,16 +353,18 @@ type EnumPartitions interface {
// as the second parameter.
//
// This example shows how to get the regions for DynamoDB in the AWS partition.
//
// rs, exists := endpoints.RegionsForService(endpoints.DefaultPartitions(), endpoints.AwsPartitionID, endpoints.DynamodbServiceID)
//
// This is equivalent to using the partition directly.
//
// rs := endpoints.AwsPartition().Services()[endpoints.DynamodbServiceID].Regions()
func RegionsForService(ps []Partition, partitionID, serviceID string) (map[string]Region, bool) {
for _, p := range ps {
if p.ID() != partitionID {
continue
}
if _, ok := p.p.Services[serviceID]; !ok {
if _, ok := p.p.Services[serviceID]; !(ok || serviceID == Ec2metadataServiceID) {
break
}
@ -308,8 +425,8 @@ func (p Partition) ID() string { return p.id }
// of new regions and services expansions.
//
// Errors that can be returned.
// * UnknownServiceError
// * UnknownEndpointError
// - UnknownServiceError
// - UnknownEndpointError
func (p Partition) EndpointFor(service, region string, opts ...func(*Options)) (ResolvedEndpoint, error) {
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.
func (p Partition) Services() map[string]Service {
ss := make(map[string]Service, len(p.p.Services))
for id := range p.p.Services {
ss[id] = Service{
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
}
@ -367,7 +494,7 @@ func (r Region) ResolveEndpoint(service string, opts ...func(*Options)) (Resolve
func (r Region) Services() map[string]Service {
ss := map[string]Service{}
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{
id: id,
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.
func (s Service) Regions() map[string]Region {
rs := map[string]Region{}
for id := range s.p.Services[s.id].Endpoints {
if r, ok := s.p.Regions[id]; ok {
rs[id] = Region{
id: id,
service, ok := s.p.Services[s.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,
p: s.p,
}
@ -421,8 +562,11 @@ func (s Service) Regions() map[string]Region {
func (s Service) Endpoints() map[string]Endpoint {
es := make(map[string]Endpoint, len(s.p.Services[s.id].Endpoints))
for id := range s.p.Services[s.id].Endpoints {
es[id] = Endpoint{
id: id,
if id.Variant != 0 {
continue
}
es[id.Region] = Endpoint{
id: id.Region,
serviceID: s.id,
p: s.p,
}

View File

@ -1,12 +1,46 @@
package endpoints
import (
"encoding/json"
"fmt"
"regexp"
"strconv"
"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:]])?$`)
type partitions []partition
@ -15,8 +49,12 @@ func (ps partitions) EndpointFor(service, region string, opts ...func(*Options))
var opt Options
opt.Set(opts...)
if len(opt.ResolvedRegion) > 0 {
region = opt.ResolvedRegion
}
for i := 0; i < len(ps); i++ {
if !ps[i].canResolveEndpoint(service, region, opt.StrictMatching) {
if !ps[i].canResolveEndpoint(service, region, opt) {
continue
}
@ -44,12 +82,74 @@ func (ps partitions) Partitions() []Partition {
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 {
ID string `json:"partition"`
Name string `json:"partitionName"`
DNSSuffix string `json:"dnsSuffix"`
RegionRegex regionRegex `json:"regionRegex"`
Defaults endpoint `json:"defaults"`
Defaults endpointDefaults `json:"defaults"`
Regions regions `json:"regions"`
Services services `json:"services"`
}
@ -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]
_, hasEndpoint := s.Endpoints[region]
_, hasEndpoint := s.Endpoints[endpointKey{
Region: region,
Variant: options.getEndpointVariant(service),
}]
if hasEndpoint && hasService {
return true
}
if strictMatch {
if options.StrictMatching {
return false
}
@ -101,7 +204,17 @@ func (p partition) EndpointFor(service, region string, opts ...func(*Options)) (
var opt Options
opt.Set(opts...)
if len(opt.ResolvedRegion) > 0 {
region = opt.ResolvedRegion
}
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) {
// Only return error if the resolver will not fallback to creating
// 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
}
if (service == "sts" && opt.STSRegionalEndpoint != RegionalSTSEndpoint) ||
(service == "s3" && opt.S3UsEast1RegionalEndpoint != RegionalS3UsEast1Endpoint) {
if r, ok := isLegacyGlobalRegion(service, region, opt); ok {
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 {
region = "aws-global"
return awsGlobal, true
}
}
e, hasEndpoint := s.endpointForRegion(region)
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)
return region, false
}
func serviceList(ss services) []string {
@ -136,10 +322,13 @@ func serviceList(ss services) []string {
}
return list
}
func endpointList(es endpoints) []string {
func endpointList(es serviceEndpoints, variant endpointVariant) []string {
list := make([]string, 0, len(es))
for k := range es {
list = append(list, k)
if k.Variant != variant {
continue
}
list = append(list, k.Region)
}
return list
}
@ -173,17 +362,17 @@ type services map[string]service
type service struct {
PartitionEndpoint string `json:"partitionEndpoint"`
IsRegionalized boxedBool `json:"isRegionalized,omitempty"`
Defaults endpoint `json:"defaults"`
Endpoints endpoints `json:"endpoints"`
Defaults endpointDefaults `json:"defaults"`
Endpoints serviceEndpoints `json:"endpoints"`
}
func (s *service) endpointForRegion(region string) (endpoint, bool) {
if e, ok := s.Endpoints[region]; ok {
func (s *service) endpointForRegion(region string, endpoints serviceEndpoints, variant endpointVariant) (endpoint, bool) {
if e, ok := endpoints[endpointKey{Region: region, Variant: variant}]; ok {
return e, true
}
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
@ -191,22 +380,73 @@ func (s *service) endpointForRegion(region string) (endpoint, bool) {
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 {
Hostname string `json:"hostname"`
Protocols []string `json:"protocols"`
CredentialScope credentialScope `json:"credentialScope"`
// Custom fields not modeled
HasDualStack boxedBool `json:"-"`
DualStackHostname string `json:"-"`
DNSSuffix string `json:"dnsSuffix"`
// Signature Version not used
SignatureVersions []string `json:"signatureVersions"`
// SSLCommonName not used.
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 (
@ -235,7 +475,7 @@ func getByPriority(s []string, p []string, def string) string {
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
for _, def := range defs {
merged.mergeIn(def)
@ -256,23 +496,26 @@ func (e endpoint) resolve(service, partitionID, region, dnsSuffix string, defs [
}
hostname := e.Hostname
// Offset the hostname for dualstack if enabled
if opts.UseDualStack && e.HasDualStack == boxedTrue {
hostname = e.DualStackHostname
region = signingRegion
}
if !validateInputRegion(region) {
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(u, "{region}", region, 1)
u = strings.Replace(u, "{dnsSuffix}", dnsSuffix, 1)
u = strings.Replace(u, dnsSuffixTemplateVariable, dnsSuffix, 1)
scheme := getEndpointScheme(e.Protocols, opts.DisableSSL)
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{
URL: u,
PartitionID: partitionID,
@ -310,11 +553,11 @@ func (e *endpoint) mergeIn(other endpoint) {
if len(other.SSLCommonName) > 0 {
e.SSLCommonName = other.SSLCommonName
}
if other.HasDualStack != boxedBoolUnset {
e.HasDualStack = other.HasDualStack
if len(other.DNSSuffix) > 0 {
e.DNSSuffix = other.DNSSuffix
}
if len(other.DualStackHostname) > 0 {
e.DualStackHostname = other.DualStackHostname
if other.Deprecated != boxedBoolUnset {
e.Deprecated = other.Deprecated
}
}

View File

@ -1,3 +1,4 @@
//go:build codegen
// +build codegen
package endpoints
@ -154,6 +155,56 @@ func serviceSet(ps partitions) map[string]struct{} {
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{
"ToSymbol": toSymbol,
"QuoteString": quoteString,
@ -166,6 +217,9 @@ var funcMap = template.FuncMap{
"StringSliceIfSet": stringSliceIfSet,
"EndpointIsSet": endpointIsSet,
"ServicesSet": serviceSet,
"EndpointVariantSetter": endpointVariantSetter,
"EndpointKeySetter": endpointKeySetter,
"DefaultKeySetter": defaultKeySetter,
}
const v3Tmpl = `
@ -271,9 +325,9 @@ partition{
{{ StringIfSet "Name: %q,\n" .Name -}}
{{ StringIfSet "DNSSuffix: %q,\n" .DNSSuffix -}}
RegionRegex: {{ template "gocode RegionRegex" .RegionRegex }},
{{ if EndpointIsSet .Defaults -}}
Defaults: {{ template "gocode Endpoint" .Defaults }},
{{- end }}
{{ if (gt (len .Defaults) 0) -}}
Defaults: {{ template "gocode Defaults" .Defaults -}},
{{ end -}}
Regions: {{ template "gocode Regions" .Regions }},
Services: {{ template "gocode Services" .Services }},
}
@ -314,19 +368,27 @@ services{
service{
{{ StringIfSet "PartitionEndpoint: %q,\n" .PartitionEndpoint -}}
{{ BoxedBoolIfSet "IsRegionalized: %s,\n" .IsRegionalized -}}
{{ if EndpointIsSet .Defaults -}}
Defaults: {{ template "gocode Endpoint" .Defaults -}},
{{- end }}
{{ if (gt (len .Defaults) 0) -}}
Defaults: {{ template "gocode Defaults" .Defaults -}},
{{ end -}}
{{ if .Endpoints -}}
Endpoints: {{ template "gocode Endpoints" .Endpoints }},
{{- end }}
}
{{- end }}
{{ define "gocode Endpoints" -}}
endpoints{
{{ define "gocode Defaults" -}}
endpointDefaults{
{{ 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 }}
@ -334,6 +396,7 @@ endpoints{
{{ define "gocode Endpoint" -}}
endpoint{
{{ StringIfSet "Hostname: %q,\n" .Hostname -}}
{{ StringIfSet "DNSSuffix: %q,\n" .DNSSuffix -}}
{{ StringIfSet "SSLCommonName: %q,\n" .SSLCommonName -}}
{{ StringSliceIfSet "Protocols: []string{%s},\n" .Protocols -}}
{{ StringSliceIfSet "SignatureVersions: []string{%s},\n" .SignatureVersions -}}
@ -343,9 +406,7 @@ endpoint{
{{ StringIfSet "Service: %q,\n" .CredentialScope.Service -}}
},
{{- end }}
{{ BoxedBoolIfSet "HasDualStack: %s,\n" .HasDualStack -}}
{{ StringIfSet "DualStackHostname: %q,\n" .DualStackHostname -}}
{{ BoxedBoolIfSet "Deprecated: %s,\n" .Deprecated -}}
}
{{- end }}
`

View File

@ -77,6 +77,9 @@ const (
// wire unmarshaled message content of requests and responses made while
// using the SDK Will also enable LogDebug.
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

View File

@ -330,6 +330,9 @@ func MakeAddToUserAgentFreeFormHandler(s string) func(*Request) {
// WithSetRequestHeaders updates the operation request's HTTP header to contain
// 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.
//
// 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 {
return withRequestHeader(h).SetRequestHeaders
}
@ -338,6 +341,6 @@ type withRequestHeader map[string]string
func (h withRequestHeader) SetRequestHeaders(r *Request) {
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"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"reflect"
@ -129,12 +130,27 @@ func New(cfg aws.Config, clientInfo metadata.ClientInfo, handlers Handlers,
httpReq, _ := http.NewRequest(method, "", nil)
var err error
httpReq.URL, err = url.Parse(clientInfo.Endpoint + operation.HTTPPath)
httpReq.URL, err = url.Parse(clientInfo.Endpoint)
if err != nil {
httpReq.URL = &url.URL{}
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{
Config: cfg,
ClientInfo: clientInfo,
@ -510,6 +526,14 @@ func (r *Request) GetBody() io.ReadSeeker {
// Send will not close the request.Request's body.
func (r *Request) Send() error {
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
// request handlers.
r.Handlers.Complete.Run(r)

View File

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

View File

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

View File

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

View File

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

View File

@ -15,8 +15,8 @@ import (
// and determine if a request API error should be retried.
//
// client.DefaultRetryer is the SDK's default implementation of the Retryer. It
// uses the which uses the Request.IsErrorRetryable and Request.IsErrorThrottle
// methods to determine if the request is retried.
// uses the Request.IsErrorRetryable and Request.IsErrorThrottle methods to
// determine if the request is retried.
type Retryer interface {
// RetryRules return the retry delay that should be used by the SDK before
// 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/request"
"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,
envCfg envConfig, sharedCfg sharedConfig,
handlers request.Handlers,
@ -40,6 +49,7 @@ func resolveCredentials(cfg *aws.Config,
envCfg.WebIdentityTokenFilePath,
envCfg.RoleARN,
envCfg.RoleSessionName,
sessOpts.CredentialsProviderOptions,
)
default:
@ -59,6 +69,7 @@ var WebIdentityEmptyTokenFilePathErr = awserr.New(stscreds.ErrCodeWebIdentity, "
func assumeWebIdentity(cfg *aws.Config, handlers request.Handlers,
filepath string,
roleARN, sessionName string,
credOptions *CredentialsProviderOptions,
) (*credentials.Credentials, error) {
if len(filepath) == 0 {
@ -69,17 +80,18 @@ func assumeWebIdentity(cfg *aws.Config, handlers request.Handlers,
return nil, WebIdentityEmptyRoleARNErr
}
creds := stscreds.NewWebIdentityCredentials(
&Session{
svc := sts.New(&Session{
Config: cfg,
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,
@ -114,6 +126,7 @@ func resolveCredsFromProfile(cfg *aws.Config,
sharedCfg.WebIdentityTokenFile,
sharedCfg.RoleARN,
sharedCfg.RoleSessionName,
sessOpts.CredentialsProviderOptions,
)
case sharedCfg.hasSSOConfiguration():

View File

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

View File

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

View File

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

View File

@ -1,3 +1,4 @@
//go:build !go1.7 && go1.6
// +build !go1.7,go1.6
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.
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

View File

@ -161,10 +161,27 @@ type envConfig struct {
// AWS_S3_USE_ARN_REGION=true
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]
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 (
@ -231,6 +248,9 @@ var (
ec2IMDSEndpointEnvKey = []string{
"AWS_EC2_METADATA_SERVICE_ENDPOINT",
}
ec2IMDSEndpointModeEnvKey = []string{
"AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE",
}
useCABundleKey = []string{
"AWS_CA_BUNDLE",
}
@ -240,6 +260,12 @@ var (
useClientTLSKey = []string{
"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.
@ -364,6 +390,17 @@ func envConfigLoad(enableSharedConfig bool) (envConfig, error) {
}
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
}
@ -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"
"net/http"
"os"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
@ -283,8 +284,8 @@ type Options struct {
Handlers request.Handlers
// 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
// include protocol prefix.
// when making requests to the EC2 IMDS API. The endpoint value should
// 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.
//
@ -298,6 +299,16 @@ type Options struct {
//
// AWS_EC2_METADATA_SERVICE_ENDPOINT=http://[::1]
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,
@ -375,19 +386,23 @@ func Must(sess *Session, err error) *Session {
// Wraps the endpoint resolver with a resolver that will return a custom
// 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(
func(service, region string, opts ...func(*endpoints.Options)) (
endpoints.ResolvedEndpoint, error,
) {
if service == ec2MetadataServiceID {
if service == ec2MetadataServiceID && len(endpoint) > 0 {
return endpoints.ResolvedEndpoint{
URL: endpoint,
SigningName: ec2MetadataServiceID,
SigningRegion: region,
}, 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()
}
if len(envCfg.EC2IMDSEndpoint) != 0 {
cfg.EndpointResolver = wrapEC2IMDSEndpoint(cfg.EndpointResolver, envCfg.EC2IMDSEndpoint)
if !(len(envCfg.EC2IMDSEndpoint) == 0 && envCfg.EC2IMDSEndpointMode == endpoints.EC2IMDSEndpointModeStateUnset) {
cfg.EndpointResolver = wrapEC2IMDSEndpoint(cfg.EndpointResolver, envCfg.EC2IMDSEndpoint, envCfg.EC2IMDSEndpointMode)
}
cfg.Credentials = defaults.CredChain(cfg, handlers)
@ -737,12 +752,32 @@ func mergeConfigSrcs(cfg, userCfg *aws.Config,
endpoints.LegacyS3UsEast1Endpoint,
})
ec2IMDSEndpoint := sessOpts.EC2IMDSEndpoint
if len(ec2IMDSEndpoint) == 0 {
ec2IMDSEndpoint = envCfg.EC2IMDSEndpoint
var ec2IMDSEndpoint string
for _, v := range []string{
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
@ -763,6 +798,20 @@ func mergeConfigSrcs(cfg, userCfg *aws.Config,
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
}
@ -816,8 +865,10 @@ func (s *Session) Copy(cfgs ...*aws.Config) *Session {
func (s *Session) ClientConfig(service string, cfgs ...*aws.Config) client.Config {
s = s.Copy(cfgs...)
resolvedRegion := normalizeRegion(s.Config)
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 {
s.Handlers.Validate.PushBack(func(r *request.Request) {
if len(r.ClientInfo.Endpoint) != 0 {
@ -838,12 +889,13 @@ func (s *Session) ClientConfig(service string, cfgs ...*aws.Config) client.Confi
SigningRegion: resolved.SigningRegion,
SigningNameDerived: resolved.SigningNameDerived,
SigningName: resolved.SigningName,
ResolvedRegion: resolvedRegion,
}
}
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 {
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,
func(opt *endpoints.Options) {
opt.DisableSSL = aws.BoolValue(cfg.DisableSSL)
opt.UseDualStack = aws.BoolValue(cfg.UseDualStack)
opt.UseDualStackEndpoint = cfg.UseDualStackEndpoint
opt.UseFIPSEndpoint = cfg.UseFIPSEndpoint
// Support for STSRegionalEndpoint where the STSRegionalEndpoint is
// provided in envConfig or sharedConfig with envConfig getting
// 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
// endpoint metadata is not available.
opt.ResolveUnknownService = true
opt.ResolvedRegion = resolvedRegion
opt.Logger = cfg.Logger
opt.LogDeprecated = cfg.LogLevel.Matches(aws.LogDebugWithDeprecated)
},
)
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 {
s = s.Copy(cfgs...)
resolvedRegion := normalizeRegion(s.Config)
var resolved endpoints.ResolvedEndpoint
if ep := aws.StringValue(s.Config.Endpoint); len(ep) > 0 {
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,
SigningNameDerived: resolved.SigningNameDerived,
SigningName: resolved.SigningName,
ResolvedRegion: resolvedRegion,
}
}
@ -910,3 +975,23 @@ func (s *Session) logDeprecatedNewSessionError(msg string, err error, cfgs []*aw
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
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.
@ -145,6 +157,28 @@ type sharedConfig struct {
//
// s3_use_arn_region=true
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 {
@ -334,6 +368,16 @@ func (cfg *sharedConfig) setFromIniFile(profile string, file sharedConfigFile, e
updateString(&cfg.SSORegion, section, ssoRegionKey)
updateString(&cfg.SSORoleName, section, ssoRoleNameKey)
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)
@ -364,6 +408,14 @@ func (cfg *sharedConfig) setFromIniFile(profile string, file sharedConfigFile, e
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 {
if err := cfg.validateCredentialsRequireARN(profile); err != nil {
return err
@ -643,3 +695,35 @@ func (e CredentialRequiresARNError) OrigErr() error {
func (e CredentialRequiresARNError) Error() string {
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
}
// whitelist is a generic rule for whitelisting
type whitelist struct {
// allowList is a generic rule for allow listing
type allowList struct {
rule
}
// IsValid for whitelist checks if the value is within the whitelist
func (w whitelist) IsValid(value string) bool {
// IsValid for allow list checks if the value is within the allow list
func (w allowList) IsValid(value string) bool {
return w.rule.IsValid(value)
}
// blacklist is a generic rule for blacklisting
type blacklist struct {
// excludeList is a generic rule for exclude listing
type excludeList struct {
rule
}
// IsValid for whitelist checks if the value is within the whitelist
func (b blacklist) IsValid(value string) bool {
// IsValid for exclude list checks if the value is within the exclude list
func (b excludeList) IsValid(value string) bool {
return !b.rule.IsValid(value)
}

View File

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

View File

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

View File

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

View File

@ -90,7 +90,7 @@ const (
)
var ignoredHeaders = rules{
blacklist{
excludeList{
mapRule{
authorizationHeader: 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{
whitelist{
allowList{
mapRule{
"Cache-Control": struct{}{},
"Content-Disposition": struct{}{},
@ -145,12 +145,13 @@ var requiredSignedHeaders = rules{
},
},
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.
var allowedQueryHoisting = inclusiveRules{
blacklist{requiredSignedHeaders},
excludeList{requiredSignedHeaders},
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
// 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
// not created by a service client's API operation method use the "Sign" or
// "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)
}
headerValues := make([]string, len(headers))
headerItems := make([]string, len(headers))
for i, k := range headers {
if k == "host" {
if ctx.Request.Host != "" {
headerValues[i] = "host:" + ctx.Request.Host
headerItems[i] = "host:" + ctx.Request.Host
} else {
headerValues[i] = "host:" + ctx.Request.URL.Host
headerItems[i] = "host:" + ctx.Request.URL.Host
}
} else {
headerValues[i] = k + ":" +
strings.Join(ctx.SignedHeaderVals[k], ",")
headerValues := make([]string, len(ctx.SignedHeaderVals[k]))
for i, v := range ctx.SignedHeaderVals[k] {
headerValues[i] = strings.TrimSpace(v)
}
headerItems[i] = k + ":" +
strings.Join(headerValues, ",")
}
}
stripExcessSpaces(headerValues)
ctx.canonicalHeaders = strings.Join(headerValues, "\n")
stripExcessSpaces(headerItems)
ctx.canonicalHeaders = strings.Join(headerItems, "\n")
}
func (ctx *signingCtx) buildCanonicalString() {

View File

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

View File

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

View File

@ -5,4 +5,4 @@ package aws
const SDKName = "aws-sdk-go"
// 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
package context

View File

@ -14,14 +14,27 @@
//
// Below is the BNF that describes this parser
// Grammar:
// stmt -> value stmt'
// stmt' -> epsilon | op stmt
// value -> number | string | boolean | quoted_string
// stmt -> section | stmt'
// stmt' -> epsilon | expr
// 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' -> value section_close
// section' -> section_value 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 -> ]
//
// 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) ?
//
// SkipState will skip (NL WS)+
//
// comment -> # comment' | ; comment'

View File

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

View File

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

View File

@ -4,6 +4,7 @@ import (
"fmt"
"strconv"
"strings"
"unicode"
)
var (
@ -18,7 +19,7 @@ var literalValues = [][]rune{
func isBoolValue(b []rune) bool {
for _, lv := range literalValues {
if isLitValue(lv, b) {
if isCaselessLitValue(lv, b) {
return true
}
}
@ -39,6 +40,21 @@ func isLitValue(want, have []rune) bool {
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
// a byte slice is a number. A number is delimited by whitespace or
// the newline token.
@ -177,7 +193,7 @@ func newValue(t ValueType, base int, raw []rune) (Value, error) {
case QuotedStringType:
v.str = string(raw[1 : len(raw)-1])
case BoolType:
v.boolean = runeCompare(v.raw, runesTrue)
v.boolean = isCaselessLitValue(runesTrue, v.raw)
}
// issue 2253

View File

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

View File

@ -50,7 +50,10 @@ func (v *DefaultVisitor) VisitExpr(expr AST) error {
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")
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -4,6 +4,7 @@ package ec2query
import (
"encoding/xml"
"strings"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/request"
@ -70,7 +71,7 @@ func UnmarshalError(r *request.Request) {
}
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,
respErr.RequestID,
)

View File

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

View File

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

View File

@ -3,6 +3,7 @@ package query
import (
"encoding/xml"
"fmt"
"strings"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/request"
@ -62,7 +63,7 @@ func UnmarshalError(r *request.Request) {
}
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,
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
// 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.
if field.Tag.Get("marshal-as") == "blob" {
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) {
case string:
if tag.Get("suppressedJSONValue") == "true" && tag.Get("location") == "header" {
value = base64.StdEncoding.EncodeToString([]byte(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:
str = base64.StdEncoding.EncodeToString(value)
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())
return "", err
}
return str, nil
}

View File

@ -28,18 +28,27 @@ func PayloadMember(i interface{}) interface{} {
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 {
v := reflect.Indirect(reflect.ValueOf(i))
if !v.IsValid() {
return ""
}
if field, ok := v.Type().FieldByName("_"); ok {
if noPayload := field.Tag.Get(nopayloadPayloadType); noPayload != "" {
return nopayloadPayloadType
}
if payloadName := field.Tag.Get("payload"); payloadName != "" {
if member, ok := v.Type().FieldByName(payloadName); ok {
return member.Tag.Get("type")
}
}
}
return ""
}

View File

@ -140,7 +140,7 @@ func unmarshalLocationElements(resp *http.Response, v reflect.Value, lowerCaseHe
prefix := field.Tag.Get("locationName")
err := unmarshalHeaderMap(m, resp.Header, prefix, lowerCaseHeaderMaps)
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) {
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))
case []byte:
b, err := base64.StdEncoding.DecodeString(header)

View File

@ -1,6 +1,8 @@
package protocol
import (
"bytes"
"fmt"
"math"
"strconv"
"time"
@ -20,12 +22,15 @@ const (
const (
// 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"
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
RFC822OutputTimeFormat = "Mon, 02 Jan 2006 15:04:05 GMT"
// RFC3339 a subset of the ISO8601 timestamp format. e.g 2014-04-29T18:30:38Z
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
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.
func ParseTime(formatName, value string) (time.Time, error) {
switch formatName {
case RFC822TimeFormatName:
return time.Parse(RFC822TimeFormat, value)
case ISO8601TimeFormatName:
return time.Parse(ISO8601TimeFormat, value)
case RFC822TimeFormatName: // Smithy HTTPDate format
return tryParse(value,
RFC822TimeFormat,
rfc822TimeFormatSingleDigitDay,
rfc822TimeFormatSingleDigitDayTwoDigitYear,
time.RFC850,
time.ANSIC,
)
case ISO8601TimeFormatName: // Smithy DateTime format
return tryParse(value,
ISO8601TimeFormat,
iso8601TimeFormatNoZ,
time.RFC3339Nano,
time.RFC3339,
)
case UnixTimeFormatName:
v, err := strconv.ParseFloat(value, 64)
_, dec := math.Modf(v)
@ -83,3 +99,36 @@ func ParseTime(formatName, value string) (time.Time, error) {
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
// 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,
// and health checks.
//
// For more information about Amazon EC2 Auto Scaling, see the Amazon EC2 Auto
// Scaling User Guide (https://docs.aws.amazon.com/autoscaling/ec2/userguide/what-is-amazon-ec2-auto-scaling.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.
// For more information, see the Amazon EC2 Auto Scaling User Guide (https://docs.aws.amazon.com/autoscaling/ec2/userguide/)
// and the Amazon EC2 Auto Scaling API Reference (https://docs.aws.amazon.com/autoscaling/ec2/APIReference/Welcome.html).
//
// 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.
// 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
// a new service client. With that client you can make API requests to the service.

View File

@ -39,6 +39,7 @@ const (
// aws.Config parameter to add your extra config.
//
// Example:
//
// mySession := session.Must(session.NewSession())
//
// // Create a AutoScaling client from just a session.
@ -48,11 +49,15 @@ const (
// svc := autoscaling.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func New(p client.ConfigProvider, cfgs ...*aws.Config) *AutoScaling {
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.
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{
Client: client.New(
cfg,
@ -64,6 +69,7 @@ func newClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint,
PartitionID: partitionID,
Endpoint: endpoint,
APIVersion: "2011-01-01",
ResolvedRegion: resolvedRegion,
},
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) {
opt.DisableSSL = aws.BoolValue(cfg.DisableSSL)
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 {

View File

@ -4,35 +4,36 @@
// requests to Amazon Elastic Compute Cloud.
//
// Amazon Elastic Compute Cloud (Amazon EC2) provides secure and resizable computing
// capacity in the AWS Cloud. Using Amazon EC2 eliminates the need to invest
// in hardware up front, so you can develop and deploy applications faster.
// Amazon Virtual Private Cloud (Amazon VPC) enables you to provision a logically
// isolated section of the AWS Cloud where you can launch AWS resources in a
// virtual network that you've defined. Amazon Elastic Block Store (Amazon EBS)
// provides block level storage volumes for use with EC2 instances. EBS volumes
// are highly available and reliable storage volumes that can be attached to
// any running instance and used like a hard drive.
// capacity in the Amazon Web Services Cloud. Using Amazon EC2 eliminates the
// need to invest in hardware up front, so you can develop and deploy applications
// faster. Amazon Virtual Private Cloud (Amazon VPC) enables you to provision
// a logically isolated section of the Amazon Web Services Cloud where you can
// launch Amazon Web Services resources in a virtual network that you've defined.
// Amazon Elastic Block Store (Amazon EBS) provides block level storage volumes
// for use with EC2 instances. EBS volumes are highly available and reliable
// storage volumes that can be attached to any running instance and used like
// a hard drive.
//
// 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)
//
// * 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)
//
// * 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)
//
// * AWS VPN: AWS VPN product page (http://aws.amazon.com/vpn), AWS VPN documentation
// (http://aws.amazon.com/documentation/vpn)
// - Amazon Web Services VPN: Amazon Web Services VPN product page (http://aws.amazon.com/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 ec2 package documentation for more information.
// 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
// a new service client. With that client you can make API requests to the service.

View File

@ -39,6 +39,7 @@ const (
// aws.Config parameter to add your extra config.
//
// Example:
//
// mySession := session.Must(session.NewSession())
//
// // Create a EC2 client from just a session.
@ -48,11 +49,15 @@ const (
// svc := ec2.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func New(p client.ConfigProvider, cfgs ...*aws.Config) *EC2 {
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.
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{
Client: client.New(
cfg,
@ -64,6 +69,7 @@ func newClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint,
PartitionID: partitionID,
Endpoint: endpoint,
APIVersion: "2016-11-15",
ResolvedRegion: resolvedRegion,
},
handlers,
),

View File

@ -738,6 +738,57 @@ func (c *EC2) WaitUntilInstanceTerminatedWithContext(ctx aws.Context, input *Des
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
// 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
@ -855,6 +906,57 @@ func (c *EC2) WaitUntilNatGatewayAvailableWithContext(ctx aws.Context, input *De
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
// 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
@ -1030,6 +1132,11 @@ func (c *EC2) WaitUntilSnapshotCompletedWithContext(ctx aws.Context, input *Desc
Matcher: request.PathAllWaiterMatch, Argument: "Snapshots[].State",
Expected: "completed",
},
{
State: request.FailureWaiterState,
Matcher: request.PathAnyWaiterMatch, Argument: "Snapshots[].State",
Expected: "error",
},
},
Logger: c.Config.Logger,
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
// 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 ecr package documentation for more information.
// 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
// a new service client. With that client you can make API requests to the service.

View File

@ -125,10 +125,24 @@ const (
// "LimitExceededException".
//
// 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.
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
// "ReferencedImagesNotFoundException".
//
@ -194,6 +208,12 @@ const (
// The image is of a type that cannot be scanned.
ErrCodeUnsupportedImageTypeException = "UnsupportedImageTypeException"
// ErrCodeUnsupportedUpstreamRegistryException for service response error code
// "UnsupportedUpstreamRegistryException".
//
// The specified upstream registry isn't supported.
ErrCodeUnsupportedUpstreamRegistryException = "UnsupportedUpstreamRegistryException"
// ErrCodeUploadNotFoundException for service response error code
// "UploadNotFoundException".
//
@ -227,6 +247,8 @@ var exceptionFromCode = map[string]func(protocol.ResponseMetadata) error{
"LifecyclePolicyPreviewInProgressException": newErrorLifecyclePolicyPreviewInProgressException,
"LifecyclePolicyPreviewNotFoundException": newErrorLifecyclePolicyPreviewNotFoundException,
"LimitExceededException": newErrorLimitExceededException,
"PullThroughCacheRuleAlreadyExistsException": newErrorPullThroughCacheRuleAlreadyExistsException,
"PullThroughCacheRuleNotFoundException": newErrorPullThroughCacheRuleNotFoundException,
"ReferencedImagesNotFoundException": newErrorReferencedImagesNotFoundException,
"RegistryPolicyNotFoundException": newErrorRegistryPolicyNotFoundException,
"RepositoryAlreadyExistsException": newErrorRepositoryAlreadyExistsException,
@ -237,6 +259,7 @@ var exceptionFromCode = map[string]func(protocol.ResponseMetadata) error{
"ServerException": newErrorServerException,
"TooManyTagsException": newErrorTooManyTagsException,
"UnsupportedImageTypeException": newErrorUnsupportedImageTypeException,
"UnsupportedUpstreamRegistryException": newErrorUnsupportedUpstreamRegistryException,
"UploadNotFoundException": newErrorUploadNotFoundException,
"ValidationException": newErrorValidationException,
}

View File

@ -40,6 +40,7 @@ const (
// aws.Config parameter to add your extra config.
//
// Example:
//
// mySession := session.Must(session.NewSession())
//
// // Create a ECR client from just a session.
@ -52,11 +53,11 @@ func New(p client.ConfigProvider, cfgs ...*aws.Config) *ECR {
if c.SigningNameDerived || len(c.SigningName) == 0 {
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.
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{
Client: client.New(
cfg,
@ -68,6 +69,7 @@ func newClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint,
PartitionID: partitionID,
Endpoint: endpoint,
APIVersion: "2015-09-21",
ResolvedRegion: resolvedRegion,
JSONVersion: "1.1",
TargetPrefix: "AmazonEC2ContainerRegistry_V20150921",
},

File diff suppressed because it is too large Load Diff

View File

@ -32,7 +32,7 @@
// See elb package documentation for more information.
// 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
// a new service client. With that client you can make API requests to the service.

View File

@ -39,6 +39,7 @@ const (
// aws.Config parameter to add your extra config.
//
// Example:
//
// mySession := session.Must(session.NewSession())
//
// // Create a ELB client from just a session.
@ -48,11 +49,15 @@ const (
// svc := elb.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func New(p client.ConfigProvider, cfgs ...*aws.Config) *ELB {
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.
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{
Client: client.New(
cfg,
@ -64,6 +69,7 @@ func newClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint,
PartitionID: partitionID,
Endpoint: endpoint,
APIVersion: "2012-06-01",
ResolvedRegion: resolvedRegion,
},
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. 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.
//
// * 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.
//
// * 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/).
//
@ -36,7 +36,7 @@
// See elbv2 package documentation for more information.
// 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
// 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
// "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"
// ErrCodeTooManyRegistrationsForTargetIdException for service response error code
@ -208,7 +209,8 @@ const (
// ErrCodeTooManyTargetGroupsException for service response error code
// "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"
// ErrCodeTooManyTargetsException for service response error code

View File

@ -39,6 +39,7 @@ const (
// aws.Config parameter to add your extra config.
//
// Example:
//
// mySession := session.Must(session.NewSession())
//
// // Create a ELBV2 client from just a session.
@ -48,11 +49,15 @@ const (
// svc := elbv2.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func New(p client.ConfigProvider, cfgs ...*aws.Config) *ELBV2 {
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.
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{
Client: client.New(
cfg,
@ -64,6 +69,7 @@ func newClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint,
PartitionID: partitionID,
Endpoint: endpoint,
APIVersion: "2015-12-01",
ResolvedRegion: resolvedRegion,
},
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
// requests to AWS Key Management Service.
//
// AWS Key Management Service (AWS KMS) is an encryption and key management
// web service. This guide describes the AWS KMS operations that you can call
// programmatically. For general information about AWS KMS, see the AWS Key
// Management Service Developer Guide (https://docs.aws.amazon.com/kms/latest/developerguide/).
// Key Management Service (KMS) is an encryption and key management web service.
// This guide describes the KMS operations that you can call programmatically.
// For general information about KMS, see the Key Management Service Developer
// Guide (https://docs.aws.amazon.com/kms/latest/developerguide/).
//
// AWS provides SDKs that consist of libraries and sample code for various programming
// languages and platforms (Java, Ruby, .Net, macOS, Android, etc.). The SDKs
// provide a convenient way to create programmatic access to AWS KMS and other
// 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/).
// KMS is replacing the term customer master key (CMK) with KMS key and KMS
// key. The concept has not changed. To prevent breaking changes, KMS is keeping
// some variations of this term.
//
// We recommend that you use the AWS SDKs to make programmatic API calls to
// AWS KMS.
// Amazon Web Services provides SDKs that consist of libraries and sample code
// 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
// 1.2. 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.
// We recommend that you use the Amazon Web Services SDKs to make programmatic
// API calls to KMS.
//
// 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.
// We strongly recommend that you do not use your AWS account (root) access
// key ID and secret key for everyday work with AWS KMS. Instead, use the access
// key ID and secret access key for an IAM user. You can also use the AWS Security
// Token Service to generate temporary security credentials that you can use
// to sign requests.
// We strongly recommend that you do not use your Amazon Web Services account
// (root) access key ID and secret key for everyday work with KMS. Instead,
// use the access key ID and secret access key for an IAM user. You can also
// use the Amazon Web Services Security Token Service to generate temporary
// 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
// events for your AWS account and delivers them to an Amazon S3 bucket that
// you specify. By using the information collected by CloudTrail, you can determine
// what requests were made to AWS KMS, who made the request, when it was made,
// and so on. To learn more about CloudTrail, including how to turn it on and
// find your log files, see the AWS CloudTrail User Guide (https://docs.aws.amazon.com/awscloudtrail/latest/userguide/).
// KMS supports CloudTrail, a service that logs Amazon Web Services API calls
// and related events for your Amazon Web Services account and delivers them
// to an Amazon S3 bucket that you specify. By using the information collected
// by CloudTrail, you can determine what requests were made to KMS, who made
// the request, when it was made, and so on. To learn more about CloudTrail,
// 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:
//
// * AWS 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.
// - 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 to access Amazon Web Services.
//
// - Temporary Security Credentials (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html)
//
// * Temporary Security Credentials (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html)
// - 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)
// - 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
// # Commonly Used API Operations
//
// Of the API operations discussed in this guide, the following will prove the
// most useful for most applications. You will likely perform operations other
// 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 kms package documentation for more information.
// 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
// 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
// "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
// 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
// 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
// "CloudHsmClusterInvalidConfigurationException".
//
// The request was rejected because the associated AWS CloudHSM cluster did
// not meet the configuration requirements for a custom key store.
// The request was rejected because the associated CloudHSM cluster did not
// meet the configuration requirements for a custom key store.
//
// * The cluster must be configured with private subnets in at least two
// different Availability Zones in the Region.
@ -47,46 +47,44 @@ const (
// operation.
//
// * 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
// operations, the AWS CloudHSM cluster must have at least two active HSMs,
// each in a different Availability Zone. For the ConnectCustomKeyStore operation,
// the AWS CloudHSM must contain at least one active HSM.
// operations, the CloudHSM cluster must have at least two active HSMs, each
// in a different Availability Zone. For the ConnectCustomKeyStore operation,
// the CloudHSM must contain at least one active HSM.
//
// For information about the requirements for an AWS CloudHSM cluster that is
// associated 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
// creating a private subnet for an AWS CloudHSM cluster, see Create a Private
// Subnet (https://docs.aws.amazon.com/cloudhsm/latest/userguide/create-subnets.html)
// in the AWS CloudHSM User Guide. For information about cluster security groups,
// For information about the requirements for an CloudHSM cluster that is associated
// with a custom key store, see Assemble the Prerequisites (https://docs.aws.amazon.com/kms/latest/developerguide/create-keystore.html#before-keystore)
// in the Key Management Service Developer Guide. For information about creating
// a private subnet for an CloudHSM cluster, see Create a Private Subnet (https://docs.aws.amazon.com/cloudhsm/latest/userguide/create-subnets.html)
// in the 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)
// in the AWS CloudHSM User Guide .
// in the CloudHSM User Guide .
ErrCodeCloudHsmClusterInvalidConfigurationException = "CloudHsmClusterInvalidConfigurationException"
// ErrCodeCloudHsmClusterNotActiveException for service response error code
// "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
// and try the command again. For detailed instructions, see Getting Started
// (https://docs.aws.amazon.com/cloudhsm/latest/userguide/getting-started.html)
// in the AWS CloudHSM User Guide.
// in the CloudHSM User Guide.
ErrCodeCloudHsmClusterNotActiveException = "CloudHsmClusterNotActiveException"
// ErrCodeCloudHsmClusterNotFoundException for service response error code
// "CloudHsmClusterNotFoundException".
//
// The request was rejected because AWS KMS cannot find the AWS CloudHSM cluster
// with the specified cluster ID. Retry the request with a different cluster
// ID.
// The request was rejected because KMS cannot find the CloudHSM cluster with
// the specified cluster ID. Retry the request with a different cluster ID.
ErrCodeCloudHsmClusterNotFoundException = "CloudHsmClusterNotFoundException"
// ErrCodeCloudHsmClusterNotRelatedException for service response error code
// "CloudHsmClusterNotRelatedException".
//
// The request was rejected because the specified AWS CloudHSM cluster has a
// different cluster certificate than the original cluster. You cannot use the
// operation to specify an unrelated cluster.
// The request was rejected because the specified CloudHSM cluster has a different
// cluster certificate than the original cluster. You cannot use the operation
// to specify an unrelated 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,
@ -101,10 +99,10 @@ const (
// ErrCodeCustomKeyStoreHasCMKsException for service response error code
// "CustomKeyStoreHasCMKsException".
//
// The request was rejected because the custom key store contains AWS KMS customer
// master keys (CMKs). After verifying that you do not need to use the CMKs,
// use the ScheduleKeyDeletion operation to delete the CMKs. After they are
// deleted, you can delete the custom key store.
// The request was rejected because the custom key store contains KMS keys.
// After verifying that you do not need to use the KMS keys, use the ScheduleKeyDeletion
// operation to delete the KMS keys. After they are deleted, you can delete
// the custom key store.
ErrCodeCustomKeyStoreHasCMKsException = "CustomKeyStoreHasCMKsException"
// ErrCodeCustomKeyStoreInvalidStateException for service response error code
@ -140,7 +138,7 @@ const (
// ErrCodeCustomKeyStoreNotFoundException for service response error code
// "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.
ErrCodeCustomKeyStoreNotFoundException = "CustomKeyStoreNotFoundException"
@ -154,7 +152,7 @@ const (
// ErrCodeDisabledException for service response error code
// "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"
// ErrCodeExpiredImportTokenException for service response error code
@ -168,9 +166,9 @@ const (
// ErrCodeIncorrectKeyException for service response error code
// "IncorrectKeyException".
//
// The request was rejected because the specified CMK cannot decrypt the 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.
// The request was rejected because the specified KMS key cannot decrypt the
// data. The KeyId in a Decrypt request and the SourceKeyId in a ReEncrypt request
// must identify the same KMS key that was used to encrypt the ciphertext.
ErrCodeIncorrectKeyException = "IncorrectKeyException"
// ErrCodeIncorrectKeyMaterialException for service response error code
@ -178,14 +176,14 @@ const (
//
// 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
// this customer master key (CMK).
// this KMS key.
ErrCodeIncorrectKeyMaterialException = "IncorrectKeyMaterialException"
// ErrCodeIncorrectTrustAnchorException for service response error code
// "IncorrectTrustAnchorException".
//
// 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),
// 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
// otherwise invalid.
//
// From the ImportKeyMaterial operation, the request was rejected because AWS
// KMS could not decrypt the encrypted (wrapped) key material.
// From the ImportKeyMaterial operation, the request was rejected because KMS
// could not decrypt the encrypted (wrapped) key material.
ErrCodeInvalidCiphertextException = "InvalidCiphertextException"
// ErrCodeInvalidGrantIdException for service response error code
@ -240,7 +238,7 @@ const (
// "InvalidImportTokenException".
//
// 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"
// ErrCodeInvalidKeyUsageException for service response error code
@ -248,17 +246,19 @@ const (
//
// 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
// 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
// KeyUsage must be ENCRYPT_DECRYPT. For signing and verifying, the KeyUsage
// must be SIGN_VERIFY. To find the KeyUsage of a CMK, use the DescribeKey operation.
// KeyUsage must be ENCRYPT_DECRYPT. For signing and verifying messages, the
// 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,
// use the DescribeKey operation.
// To find the encryption or signing algorithms supported for a particular KMS
// key, use the DescribeKey operation.
ErrCodeInvalidKeyUsageException = "InvalidKeyUsageException"
// ErrCodeInvalidMarkerException for service response error code
@ -274,24 +274,32 @@ const (
// The request was rejected because the state of the specified resource is not
// valid for this request.
//
// For more information about how key state affects the use of a CMK, see How
// Key State Affects Use of a Customer Master Key (https://docs.aws.amazon.com/kms/latest/developerguide/key-state.html)
// in the AWS Key Management Service Developer Guide .
// For more information about how key state affects the use of a KMS key, see
// Key states of KMS keys (https://docs.aws.amazon.com/kms/latest/developerguide/key-state.html)
// in the Key Management Service Developer Guide .
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
// "KMSInvalidSignatureException".
//
// The request was rejected because the signature verification failed. Signature
// 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"
// ErrCodeKeyUnavailableException for service response error code
// "KeyUnavailableException".
//
// The request was rejected because the specified CMK was not available. You
// can retry the request.
// The request was rejected because the specified KMS key was not available.
// You can retry the request.
ErrCodeKeyUnavailableException = "KeyUnavailableException"
// ErrCodeLimitExceededException for service response error code
@ -299,7 +307,7 @@ const (
//
// The request was rejected because a quota was exceeded. For more information,
// 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"
// ErrCodeMalformedPolicyDocumentException for service response error code
@ -357,6 +365,7 @@ var exceptionFromCode = map[string]func(protocol.ResponseMetadata) error{
"InvalidKeyUsageException": newErrorInvalidKeyUsageException,
"InvalidMarkerException": newErrorInvalidMarkerException,
"KMSInvalidStateException": newErrorInvalidStateException,
"KMSInvalidMacException": newErrorKMSInvalidMacException,
"KMSInvalidSignatureException": newErrorKMSInvalidSignatureException,
"KeyUnavailableException": newErrorKeyUnavailableException,
"LimitExceededException": newErrorLimitExceededException,

View File

@ -40,6 +40,7 @@ const (
// aws.Config parameter to add your extra config.
//
// Example:
//
// mySession := session.Must(session.NewSession())
//
// // Create a KMS client from just a session.
@ -49,11 +50,15 @@ const (
// svc := kms.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func New(p client.ConfigProvider, cfgs ...*aws.Config) *KMS {
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.
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{
Client: client.New(
cfg,
@ -65,6 +70,7 @@ func newClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint,
PartitionID: partitionID,
Endpoint: endpoint,
APIVersion: "2014-11-01",
ResolvedRegion: resolvedRegion,
JSONVersion: "1.1",
TargetPrefix: "TrentService",
},

View File

@ -29,7 +29,6 @@ const opGetRoleCredentials = "GetRoleCredentials"
// 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.
//
//
// // Example sending a request using the GetRoleCredentialsRequest method.
// req, resp := client.GetRoleCredentialsRequest(params)
//
@ -69,19 +68,20 @@ func (c *SSO) GetRoleCredentialsRequest(input *GetRoleCredentialsInput) (req *re
// API operation GetRoleCredentials for usage and error information.
//
// Returned Error Types:
// * InvalidRequestException
//
// - 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
// - UnauthorizedException
// Indicates that the request is not authorized. This can happen due to an invalid
// access token in the request.
//
// * TooManyRequestsException
// - TooManyRequestsException
// Indicates that the request is being made too frequently and is more than
// what the server can handle.
//
// * ResourceNotFoundException
// - ResourceNotFoundException
// The specified resource doesn't exist.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/sso-2019-06-10/GetRoleCredentials
@ -122,7 +122,6 @@ const opListAccountRoles = "ListAccountRoles"
// 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.
//
//
// // Example sending a request using the ListAccountRolesRequest method.
// req, resp := client.ListAccountRolesRequest(params)
//
@ -167,19 +166,20 @@ func (c *SSO) ListAccountRolesRequest(input *ListAccountRolesInput) (req *reques
// API operation ListAccountRoles for usage and error information.
//
// Returned Error Types:
// * InvalidRequestException
//
// - 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
// - UnauthorizedException
// Indicates that the request is not authorized. This can happen due to an invalid
// access token in the request.
//
// * TooManyRequestsException
// - TooManyRequestsException
// Indicates that the request is being made too frequently and is more than
// what the server can handle.
//
// * ResourceNotFoundException
// - ResourceNotFoundException
// The specified resource doesn't exist.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/sso-2019-06-10/ListAccountRoles
@ -220,7 +220,6 @@ func (c *SSO) ListAccountRolesWithContext(ctx aws.Context, input *ListAccountRol
// fmt.Println(page)
// return pageNum <= 3
// })
//
func (c *SSO) ListAccountRolesPages(input *ListAccountRolesInput, fn func(*ListAccountRolesOutput, bool) bool) error {
return c.ListAccountRolesPagesWithContext(aws.BackgroundContext(), input, fn)
}
@ -272,7 +271,6 @@ const opListAccounts = "ListAccounts"
// 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.
//
//
// // Example sending a request using the ListAccountsRequest method.
// req, resp := client.ListAccountsRequest(params)
//
@ -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
// by the administrator of the account. For more information, see Assign User
// 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
// with awserr.Error's Code and Message methods to get detailed information about
@ -320,19 +319,20 @@ func (c *SSO) ListAccountsRequest(input *ListAccountsInput) (req *request.Reques
// API operation ListAccounts for usage and error information.
//
// Returned Error Types:
// * InvalidRequestException
//
// - 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
// - UnauthorizedException
// Indicates that the request is not authorized. This can happen due to an invalid
// access token in the request.
//
// * TooManyRequestsException
// - TooManyRequestsException
// Indicates that the request is being made too frequently and is more than
// what the server can handle.
//
// * ResourceNotFoundException
// - ResourceNotFoundException
// The specified resource doesn't exist.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/sso-2019-06-10/ListAccounts
@ -373,7 +373,6 @@ func (c *SSO) ListAccountsWithContext(ctx aws.Context, input *ListAccountsInput,
// fmt.Println(page)
// return pageNum <= 3
// })
//
func (c *SSO) ListAccountsPages(input *ListAccountsInput, fn func(*ListAccountsOutput, bool) bool) error {
return c.ListAccountsPagesWithContext(aws.BackgroundContext(), input, fn)
}
@ -425,7 +424,6 @@ const opLogout = "Logout"
// 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.
//
//
// // Example sending a request using the LogoutRequest method.
// req, resp := client.LogoutRequest(params)
//
@ -455,7 +453,21 @@ func (c *SSO) LogoutRequest(input *LogoutInput) (req *request.Request, output *L
// 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
// with awserr.Error's Code and Message methods to get detailed information about
@ -465,15 +477,16 @@ func (c *SSO) LogoutRequest(input *LogoutInput) (req *request.Request, output *L
// API operation Logout for usage and error information.
//
// Returned Error Types:
// * InvalidRequestException
//
// - 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
// - UnauthorizedException
// Indicates that the request is not authorized. This can happen due to an invalid
// access token in the request.
//
// * TooManyRequestsException
// - TooManyRequestsException
// Indicates that the request is being made too frequently and is more than
// what the server can handle.
//
@ -513,12 +526,20 @@ type AccountInfo struct {
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 {
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 {
return s.String()
}
@ -542,11 +563,15 @@ func (s *AccountInfo) SetEmailAddress(v string) *AccountInfo {
}
type GetRoleCredentialsInput struct {
_ struct{} `type:"structure"`
_ struct{} `type:"structure" nopayload:"true"`
// The token issued by the CreateToken API call. For more information, see CreateToken
// (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 *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"`
}
// 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 {
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 {
return s.String()
}
@ -616,12 +649,20 @@ type GetRoleCredentialsOutput struct {
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 {
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 {
return s.String()
}
@ -641,12 +682,20 @@ type InvalidRequestException struct {
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 {
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 {
return s.String()
}
@ -690,11 +739,15 @@ func (s *InvalidRequestException) RequestID() string {
}
type ListAccountRolesInput struct {
_ struct{} `type:"structure"`
_ struct{} `type:"structure" nopayload:"true"`
// The token issued by the CreateToken API call. For more information, see CreateToken
// (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 *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"`
}
// 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 {
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 {
return s.String()
}
@ -776,12 +837,20 @@ type ListAccountRolesOutput struct {
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 {
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 {
return s.String()
}
@ -799,11 +868,15 @@ func (s *ListAccountRolesOutput) SetRoleList(v []*RoleInfo) *ListAccountRolesOut
}
type ListAccountsInput struct {
_ struct{} `type:"structure"`
_ struct{} `type:"structure" nopayload:"true"`
// The token issued by the CreateToken API call. For more information, see CreateToken
// (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 *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"`
}
// 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 {
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 {
return s.String()
}
@ -871,12 +952,20 @@ type ListAccountsOutput struct {
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 {
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 {
return s.String()
}
@ -894,22 +983,34 @@ func (s *ListAccountsOutput) SetNextToken(v string) *ListAccountsOutput {
}
type LogoutInput struct {
_ struct{} `type:"structure"`
_ struct{} `type:"structure" nopayload:"true"`
// The token issued by the CreateToken API call. For more information, see CreateToken
// (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 *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 {
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 {
return s.String()
}
@ -937,12 +1038,20 @@ type LogoutOutput struct {
_ 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 {
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 {
return s.String()
}
@ -955,12 +1064,20 @@ type ResourceNotFoundException struct {
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 {
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 {
return s.String()
}
@ -1020,20 +1137,36 @@ type RoleCredentials struct {
// 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)
// 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"`
// 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)
// 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"`
}
// 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 {
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 {
return s.String()
}
@ -1073,12 +1206,20 @@ type RoleInfo struct {
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 {
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 {
return s.String()
}
@ -1104,12 +1245,20 @@ type TooManyRequestsException struct {
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 {
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 {
return s.String()
}
@ -1161,12 +1310,20 @@ type UnauthorizedException struct {
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 {
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 {
return s.String()
}

View File

@ -3,30 +3,31 @@
// Package sso provides the client and types for making API
// requests to AWS Single Sign-On.
//
// AWS Single Sign-On Portal is a web service that makes it easy for you to
// assign user access to AWS SSO resources such as the user portal. Users can
// get AWS account applications and roles assigned to them and get federated
// into the application.
// AWS IAM Identity Center (successor to AWS Single Sign-On) Portal is a web
// service that makes it easy for you to assign user access to IAM Identity
// Center resources such as the AWS access portal. Users can get AWS account
// 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)
// in the AWS SSO User Guide.
// Although AWS Single Sign-On was renamed, the sso and identitystore API namespaces
// 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
// can call programatically and includes detailed information on data types
// and errors.
// This reference guide describes the IAM Identity Center Portal operations
// that you can call programatically and includes detailed information on data
// types and errors.
//
// 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
// provide a convenient way to create programmatic access to AWS SSO and other
// AWS services. 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/).
// provide a convenient way to create programmatic access to IAM Identity Center
// and other AWS services. 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/).
//
// 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.
// 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
// a new service client. With that client you can make API requests to the service.

View File

@ -40,6 +40,7 @@ const (
// aws.Config parameter to add your extra config.
//
// Example:
//
// mySession := session.Must(session.NewSession())
//
// // Create a SSO client from just a session.
@ -52,11 +53,11 @@ func New(p client.ConfigProvider, cfgs ...*aws.Config) *SSO {
if c.SigningNameDerived || len(c.SigningName) == 0 {
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.
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{
Client: client.New(
cfg,
@ -68,6 +69,7 @@ func newClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint,
PartitionID: partitionID,
Endpoint: endpoint,
APIVersion: "2019-06-10",
ResolvedRegion: resolvedRegion,
},
handlers,
),

File diff suppressed because it is too large Load Diff

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