vendor: update buildkit to master@31c870e82a48

Signed-off-by: Justin Chadwell <me@jedevc.com>
This commit is contained in:
Justin Chadwell
2023-05-15 18:32:31 +01:00
parent 167cd16acb
commit e61a8cf637
269 changed files with 25798 additions and 3371 deletions

View File

@ -1,3 +1,49 @@
# Release (2022-12-02)
* No change notes available for this release.
# Release (2022-10-24)
## Module Highlights
* `github.com/aws/smithy-go`: v1.13.4
* **Bug Fix**: fixed document type checking for encoding nested types
# Release (2022-09-14)
* No change notes available for this release.
# Release (v1.13.2)
* No change notes available for this release.
# Release (v1.13.1)
* No change notes available for this release.
# Release (v1.13.0)
## Module Highlights
* `github.com/aws/smithy-go`: v1.13.0
* **Feature**: Adds support for the Smithy httpBearerAuth authentication trait to smithy-go. This allows the SDK to support the bearer authentication flow for API operations decorated with httpBearerAuth. An API client will need to be provided with its own bearer.TokenProvider implementation or use the bearer.StaticTokenProvider implementation.
# Release (v1.12.1)
## Module Highlights
* `github.com/aws/smithy-go`: v1.12.1
* **Bug Fix**: Fixes a bug where JSON object keys were not escaped.
# Release (v1.12.0)
## Module Highlights
* `github.com/aws/smithy-go`: v1.12.0
* **Feature**: `transport/http`: Add utility for setting context metadata when operation serializer automatically assigns content-type default value.
# Release (v1.11.3)
## Module Highlights
* `github.com/aws/smithy-go`: v1.11.3
* **Dependency Update**: Updates smithy-go unit test dependency go-cmp to 0.5.8.
# Release (v1.11.2)
* No change notes available for this release.

View File

@ -14,6 +14,9 @@ REPOTOOLS_CMD_CHANGELOG = ${REPOTOOLS_MODULE}/cmd/changelog@${REPOTOOLS_VERSION}
REPOTOOLS_CMD_TAG_RELEASE = ${REPOTOOLS_MODULE}/cmd/tagrelease@${REPOTOOLS_VERSION}
REPOTOOLS_CMD_MODULE_VERSION = ${REPOTOOLS_MODULE}/cmd/moduleversion@${REPOTOOLS_VERSION}
UNIT_TEST_TAGS=
BUILD_TAGS=
ifneq ($(PRE_RELEASE_VERSION),)
REPOTOOLS_CMD_CALCULATE_RELEASE_ADDITIONAL_ARGS += -preview=${PRE_RELEASE_VERSION}
endif
@ -27,6 +30,37 @@ smithy-build:
smithy-clean:
cd codegen && ./gradlew clean
##################
# Linting/Verify #
##################
.PHONY: verify vet
verify: vet
vet:
go vet ${BUILD_TAGS} --all ./...
################
# Unit Testing #
################
.PHONY: unit unit-race unit-test unit-race-test
unit: verify
go vet ${BUILD_TAGS} --all ./... && \
go test ${BUILD_TAGS} ${RUN_NONE} ./... && \
go test -timeout=1m ${UNIT_TEST_TAGS} ./...
unit-race: verify
go vet ${BUILD_TAGS} --all ./... && \
go test ${BUILD_TAGS} ${RUN_NONE} ./... && \
go test -timeout=1m ${UNIT_TEST_TAGS} -race -cpu=4 ./...
unit-test: verify
go test -timeout=1m ${UNIT_TEST_TAGS} ./...
unit-race-test: verify
go test -timeout=1m ${UNIT_TEST_TAGS} -race -cpu=4 ./...
#####################
# Release Process #
#####################

View File

@ -2,7 +2,7 @@
[![Go Build Status](https://github.com/aws/smithy-go/actions/workflows/go.yml/badge.svg?branch=main)](https://github.com/aws/smithy-go/actions/workflows/go.yml)[![Codegen Build Status](https://github.com/aws/smithy-go/actions/workflows/codegen.yml/badge.svg?branch=main)](https://github.com/aws/smithy-go/actions/workflows/codegen.yml)
Smithy code generators for Go.
[Smithy](https://smithy.io/) code generators for Go.
**WARNING: All interfaces are subject to change.**

3
vendor/github.com/aws/smithy-go/auth/bearer/docs.go generated vendored Normal file
View File

@ -0,0 +1,3 @@
// Package bearer provides middleware and utilities for authenticating API
// operation calls with a Bearer Token.
package bearer

View File

@ -0,0 +1,104 @@
package bearer
import (
"context"
"fmt"
"github.com/aws/smithy-go/middleware"
smithyhttp "github.com/aws/smithy-go/transport/http"
)
// Message is the middleware stack's request transport message value.
type Message interface{}
// Signer provides an interface for implementations to decorate a request
// message with a bearer token. The signer is responsible for validating the
// message type is compatible with the signer.
type Signer interface {
SignWithBearerToken(context.Context, Token, Message) (Message, error)
}
// AuthenticationMiddleware provides the Finalize middleware step for signing
// an request message with a bearer token.
type AuthenticationMiddleware struct {
signer Signer
tokenProvider TokenProvider
}
// AddAuthenticationMiddleware helper adds the AuthenticationMiddleware to the
// middleware Stack in the Finalize step with the options provided.
func AddAuthenticationMiddleware(s *middleware.Stack, signer Signer, tokenProvider TokenProvider) error {
return s.Finalize.Add(
NewAuthenticationMiddleware(signer, tokenProvider),
middleware.After,
)
}
// NewAuthenticationMiddleware returns an initialized AuthenticationMiddleware.
func NewAuthenticationMiddleware(signer Signer, tokenProvider TokenProvider) *AuthenticationMiddleware {
return &AuthenticationMiddleware{
signer: signer,
tokenProvider: tokenProvider,
}
}
const authenticationMiddlewareID = "BearerTokenAuthentication"
// ID returns the resolver identifier
func (m *AuthenticationMiddleware) ID() string {
return authenticationMiddlewareID
}
// HandleFinalize implements the FinalizeMiddleware interface in order to
// update the request with bearer token authentication.
func (m *AuthenticationMiddleware) HandleFinalize(
ctx context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler,
) (
out middleware.FinalizeOutput, metadata middleware.Metadata, err error,
) {
token, err := m.tokenProvider.RetrieveBearerToken(ctx)
if err != nil {
return out, metadata, fmt.Errorf("failed AuthenticationMiddleware wrap message, %w", err)
}
signedMessage, err := m.signer.SignWithBearerToken(ctx, token, in.Request)
if err != nil {
return out, metadata, fmt.Errorf("failed AuthenticationMiddleware sign message, %w", err)
}
in.Request = signedMessage
return next.HandleFinalize(ctx, in)
}
// SignHTTPSMessage provides a bearer token authentication implementation that
// will sign the message with the provided bearer token.
//
// Will fail if the message is not a smithy-go HTTP request or the request is
// not HTTPS.
type SignHTTPSMessage struct{}
// NewSignHTTPSMessage returns an initialized signer for HTTP messages.
func NewSignHTTPSMessage() *SignHTTPSMessage {
return &SignHTTPSMessage{}
}
// SignWithBearerToken returns a copy of the HTTP request with the bearer token
// added via the "Authorization" header, per RFC 6750, https://datatracker.ietf.org/doc/html/rfc6750.
//
// Returns an error if the request's URL scheme is not HTTPS, or the request
// message is not an smithy-go HTTP Request pointer type.
func (SignHTTPSMessage) SignWithBearerToken(ctx context.Context, token Token, message Message) (Message, error) {
req, ok := message.(*smithyhttp.Request)
if !ok {
return nil, fmt.Errorf("expect smithy-go HTTP Request, got %T", message)
}
if !req.IsHTTPS() {
return nil, fmt.Errorf("bearer token with HTTP request requires HTTPS")
}
reqClone := req.Clone()
reqClone.Header.Set("Authorization", "Bearer "+token.Value)
return reqClone, nil
}

50
vendor/github.com/aws/smithy-go/auth/bearer/token.go generated vendored Normal file
View File

@ -0,0 +1,50 @@
package bearer
import (
"context"
"time"
)
// Token provides a type wrapping a bearer token and expiration metadata.
type Token struct {
Value string
CanExpire bool
Expires time.Time
}
// Expired returns if the token's Expires time is before or equal to the time
// provided. If CanExpires is false, Expired will always return false.
func (t Token) Expired(now time.Time) bool {
if !t.CanExpire {
return false
}
now = now.Round(0)
return now.Equal(t.Expires) || now.After(t.Expires)
}
// TokenProvider provides interface for retrieving bearer tokens.
type TokenProvider interface {
RetrieveBearerToken(context.Context) (Token, error)
}
// TokenProviderFunc provides a helper utility to wrap a function as a type
// that implements the TokenProvider interface.
type TokenProviderFunc func(context.Context) (Token, error)
// RetrieveBearerToken calls the wrapped function, returning the Token or
// error.
func (fn TokenProviderFunc) RetrieveBearerToken(ctx context.Context) (Token, error) {
return fn(ctx)
}
// StaticTokenProvider provides a utility for wrapping a static bearer token
// value within an implementation of a token provider.
type StaticTokenProvider struct {
Token Token
}
// RetrieveBearerToken returns the static token specified.
func (s StaticTokenProvider) RetrieveBearerToken(context.Context) (Token, error) {
return s.Token, nil
}

View File

@ -0,0 +1,208 @@
package bearer
import (
"context"
"fmt"
"sync/atomic"
"time"
smithycontext "github.com/aws/smithy-go/context"
"github.com/aws/smithy-go/internal/sync/singleflight"
)
// package variable that can be override in unit tests.
var timeNow = time.Now
// TokenCacheOptions provides a set of optional configuration options for the
// TokenCache TokenProvider.
type TokenCacheOptions struct {
// The duration before the token will expire when the credentials will be
// refreshed. If DisableAsyncRefresh is true, the RetrieveBearerToken calls
// will be blocking.
//
// Asynchronous refreshes are deduplicated, and only one will be in-flight
// at a time. If the token expires while an asynchronous refresh is in
// flight, the next call to RetrieveBearerToken will block on that refresh
// to return.
RefreshBeforeExpires time.Duration
// The timeout the underlying TokenProvider's RetrieveBearerToken call must
// return within, or will be canceled. Defaults to 0, no timeout.
//
// If 0 timeout, its possible for the underlying tokenProvider's
// RetrieveBearerToken call to block forever. Preventing subsequent
// TokenCache attempts to refresh the token.
//
// If this timeout is reached all pending deduplicated calls to
// TokenCache RetrieveBearerToken will fail with an error.
RetrieveBearerTokenTimeout time.Duration
// The minimum duration between asynchronous refresh attempts. If the next
// asynchronous recent refresh attempt was within the minimum delay
// duration, the call to retrieve will return the current cached token, if
// not expired.
//
// The asynchronous retrieve is deduplicated across multiple calls when
// RetrieveBearerToken is called. The asynchronous retrieve is not a
// periodic task. It is only performed when the token has not yet expired,
// and the current item is within the RefreshBeforeExpires window, and the
// TokenCache's RetrieveBearerToken method is called.
//
// If 0, (default) there will be no minimum delay between asynchronous
// refresh attempts.
//
// If DisableAsyncRefresh is true, this option is ignored.
AsyncRefreshMinimumDelay time.Duration
// Sets if the TokenCache will attempt to refresh the token in the
// background asynchronously instead of blocking for credentials to be
// refreshed. If disabled token refresh will be blocking.
//
// The first call to RetrieveBearerToken will always be blocking, because
// there is no cached token.
DisableAsyncRefresh bool
}
// TokenCache provides an utility to cache Bearer Authentication tokens from a
// wrapped TokenProvider. The TokenCache can be has options to configure the
// cache's early and asynchronous refresh of the token.
type TokenCache struct {
options TokenCacheOptions
provider TokenProvider
cachedToken atomic.Value
lastRefreshAttemptTime atomic.Value
sfGroup singleflight.Group
}
// NewTokenCache returns a initialized TokenCache that implements the
// TokenProvider interface. Wrapping the provider passed in. Also taking a set
// of optional functional option parameters to configure the token cache.
func NewTokenCache(provider TokenProvider, optFns ...func(*TokenCacheOptions)) *TokenCache {
var options TokenCacheOptions
for _, fn := range optFns {
fn(&options)
}
return &TokenCache{
options: options,
provider: provider,
}
}
// RetrieveBearerToken returns the token if it could be obtained, or error if a
// valid token could not be retrieved.
//
// The passed in Context's cancel/deadline/timeout will impacting only this
// individual retrieve call and not any other already queued up calls. This
// means underlying provider's RetrieveBearerToken calls could block for ever,
// and not be canceled with the Context. Set RetrieveBearerTokenTimeout to
// provide a timeout, preventing the underlying TokenProvider blocking forever.
//
// By default, if the passed in Context is canceled, all of its values will be
// considered expired. The wrapped TokenProvider will not be able to lookup the
// values from the Context once it is expired. This is done to protect against
// expired values no longer being valid. To disable this behavior, use
// smithy-go's context.WithPreserveExpiredValues to add a value to the Context
// before calling RetrieveBearerToken to enable support for expired values.
//
// Without RetrieveBearerTokenTimeout there is the potential for a underlying
// Provider's RetrieveBearerToken call to sit forever. Blocking in subsequent
// attempts at refreshing the token.
func (p *TokenCache) RetrieveBearerToken(ctx context.Context) (Token, error) {
cachedToken, ok := p.getCachedToken()
if !ok || cachedToken.Expired(timeNow()) {
return p.refreshBearerToken(ctx)
}
// Check if the token should be refreshed before it expires.
refreshToken := cachedToken.Expired(timeNow().Add(p.options.RefreshBeforeExpires))
if !refreshToken {
return cachedToken, nil
}
if p.options.DisableAsyncRefresh {
return p.refreshBearerToken(ctx)
}
p.tryAsyncRefresh(ctx)
return cachedToken, nil
}
// tryAsyncRefresh attempts to asynchronously refresh the token returning the
// already cached token. If it AsyncRefreshMinimumDelay option is not zero, and
// the duration since the last refresh is less than that value, nothing will be
// done.
func (p *TokenCache) tryAsyncRefresh(ctx context.Context) {
if p.options.AsyncRefreshMinimumDelay != 0 {
var lastRefreshAttempt time.Time
if v := p.lastRefreshAttemptTime.Load(); v != nil {
lastRefreshAttempt = v.(time.Time)
}
if timeNow().Before(lastRefreshAttempt.Add(p.options.AsyncRefreshMinimumDelay)) {
return
}
}
// Ignore the returned channel so this won't be blocking, and limit the
// number of additional goroutines created.
p.sfGroup.DoChan("async-refresh", func() (interface{}, error) {
res, err := p.refreshBearerToken(ctx)
if p.options.AsyncRefreshMinimumDelay != 0 {
var refreshAttempt time.Time
if err != nil {
refreshAttempt = timeNow()
}
p.lastRefreshAttemptTime.Store(refreshAttempt)
}
return res, err
})
}
func (p *TokenCache) refreshBearerToken(ctx context.Context) (Token, error) {
resCh := p.sfGroup.DoChan("refresh-token", func() (interface{}, error) {
ctx := smithycontext.WithSuppressCancel(ctx)
if v := p.options.RetrieveBearerTokenTimeout; v != 0 {
var cancel func()
ctx, cancel = context.WithTimeout(ctx, v)
defer cancel()
}
return p.singleRetrieve(ctx)
})
select {
case res := <-resCh:
return res.Val.(Token), res.Err
case <-ctx.Done():
return Token{}, fmt.Errorf("retrieve bearer token canceled, %w", ctx.Err())
}
}
func (p *TokenCache) singleRetrieve(ctx context.Context) (interface{}, error) {
token, err := p.provider.RetrieveBearerToken(ctx)
if err != nil {
return Token{}, fmt.Errorf("failed to retrieve bearer token, %w", err)
}
p.cachedToken.Store(&token)
return token, nil
}
// getCachedToken returns the currently cached token and true if found. Returns
// false if no token is cached.
func (p *TokenCache) getCachedToken() (Token, bool) {
v := p.cachedToken.Load()
if v == nil {
return Token{}, false
}
t := v.(*Token)
if t == nil || t.Value == "" {
return Token{}, false
}
return *t, true
}

View File

@ -0,0 +1,81 @@
package context
import "context"
// valueOnlyContext provides a utility to preserve only the values of a
// Context. Suppressing any cancellation or deadline on that context being
// propagated downstream of this value.
//
// If preserveExpiredValues is false (default), and the valueCtx is canceled,
// calls to lookup values with the Values method, will always return nil. Setting
// preserveExpiredValues to true, will allow the valueOnlyContext to lookup
// values in valueCtx even if valueCtx is canceled.
//
// Based on the Go standard libraries net/lookup.go onlyValuesCtx utility.
// https://github.com/golang/go/blob/da2773fe3e2f6106634673a38dc3a6eb875fe7d8/src/net/lookup.go
type valueOnlyContext struct {
context.Context
preserveExpiredValues bool
valuesCtx context.Context
}
var _ context.Context = (*valueOnlyContext)(nil)
// Value looks up the key, returning its value. If configured to not preserve
// values of expired context, and the wrapping context is canceled, nil will be
// returned.
func (v *valueOnlyContext) Value(key interface{}) interface{} {
if !v.preserveExpiredValues {
select {
case <-v.valuesCtx.Done():
return nil
default:
}
}
return v.valuesCtx.Value(key)
}
// WithSuppressCancel wraps the Context value, suppressing its deadline and
// cancellation events being propagated downstream to consumer of the returned
// context.
//
// By default the wrapped Context's Values are available downstream until the
// wrapped Context is canceled. Once the wrapped Context is canceled, Values
// method called on the context return will no longer lookup any key. As they
// are now considered expired.
//
// To override this behavior, use WithPreserveExpiredValues on the Context
// before it is wrapped by WithSuppressCancel. This will make the Context
// returned by WithSuppressCancel allow lookup of expired values.
func WithSuppressCancel(ctx context.Context) context.Context {
return &valueOnlyContext{
Context: context.Background(),
valuesCtx: ctx,
preserveExpiredValues: GetPreserveExpiredValues(ctx),
}
}
type preserveExpiredValuesKey struct{}
// WithPreserveExpiredValues adds a Value to the Context if expired values
// should be preserved, and looked up by a Context wrapped by
// WithSuppressCancel.
//
// WithPreserveExpiredValues must be added as a value to a Context, before that
// Context is wrapped by WithSuppressCancel
func WithPreserveExpiredValues(ctx context.Context, enable bool) context.Context {
return context.WithValue(ctx, preserveExpiredValuesKey{}, enable)
}
// GetPreserveExpiredValues looks up, and returns the PreserveExpressValues
// value in the context. Returning true if enabled, false otherwise.
func GetPreserveExpiredValues(ctx context.Context) bool {
v := ctx.Value(preserveExpiredValuesKey{})
if v != nil {
return v.(bool)
}
return false
}

35
vendor/github.com/aws/smithy-go/encoding/json/array.go generated vendored Normal file
View File

@ -0,0 +1,35 @@
package json
import (
"bytes"
)
// Array represents the encoding of a JSON Array
type Array struct {
w *bytes.Buffer
writeComma bool
scratch *[]byte
}
func newArray(w *bytes.Buffer, scratch *[]byte) *Array {
w.WriteRune(leftBracket)
return &Array{w: w, scratch: scratch}
}
// Value adds a new element to the JSON Array.
// Returns a Value type that is used to encode
// the array element.
func (a *Array) Value() Value {
if a.writeComma {
a.w.WriteRune(comma)
} else {
a.writeComma = true
}
return newValue(a.w, a.scratch)
}
// Close encodes the end of the JSON Array
func (a *Array) Close() {
a.w.WriteRune(rightBracket)
}

View File

@ -0,0 +1,15 @@
package json
const (
leftBrace = '{'
rightBrace = '}'
leftBracket = '['
rightBracket = ']'
comma = ','
quote = '"'
colon = ':'
null = "null"
)

View File

@ -0,0 +1,139 @@
package json
import (
"bytes"
"encoding/json"
"fmt"
"io"
)
// DiscardUnknownField discards unknown fields from a decoder body.
// This function is useful while deserializing a JSON body with additional
// unknown information that should be discarded.
func DiscardUnknownField(decoder *json.Decoder) error {
// This deliberately does not share logic with CollectUnknownField, even
// though it could, because if we were to delegate to that then we'd incur
// extra allocations and general memory usage.
v, err := decoder.Token()
if err == io.EOF {
return nil
}
if err != nil {
return err
}
if _, ok := v.(json.Delim); ok {
for decoder.More() {
err = DiscardUnknownField(decoder)
}
endToken, err := decoder.Token()
if err != nil {
return err
}
if _, ok := endToken.(json.Delim); !ok {
return fmt.Errorf("invalid JSON : expected json delimiter, found %T %v",
endToken, endToken)
}
}
return nil
}
// CollectUnknownField grabs the contents of unknown fields from the decoder body
// and returns them as a byte slice. This is useful for skipping unknown fields without
// completely discarding them.
func CollectUnknownField(decoder *json.Decoder) ([]byte, error) {
result, err := collectUnknownField(decoder)
if err != nil {
return nil, err
}
buff := bytes.NewBuffer(nil)
encoder := json.NewEncoder(buff)
if err := encoder.Encode(result); err != nil {
return nil, err
}
return buff.Bytes(), nil
}
func collectUnknownField(decoder *json.Decoder) (interface{}, error) {
// Grab the initial value. This could either be a concrete value like a string or a a
// delimiter.
token, err := decoder.Token()
if err == io.EOF {
return nil, nil
}
if err != nil {
return nil, err
}
// If it's an array or object, we'll need to recurse.
delim, ok := token.(json.Delim)
if ok {
var result interface{}
if delim == '{' {
result, err = collectUnknownObject(decoder)
if err != nil {
return nil, err
}
} else {
result, err = collectUnknownArray(decoder)
if err != nil {
return nil, err
}
}
// Discard the closing token. decoder.Token handles checking for matching delimiters
if _, err := decoder.Token(); err != nil {
return nil, err
}
return result, nil
}
return token, nil
}
func collectUnknownArray(decoder *json.Decoder) ([]interface{}, error) {
// We need to create an empty array here instead of a nil array, since by getting
// into this function at all we necessarily have seen a non-nil list.
array := []interface{}{}
for decoder.More() {
value, err := collectUnknownField(decoder)
if err != nil {
return nil, err
}
array = append(array, value)
}
return array, nil
}
func collectUnknownObject(decoder *json.Decoder) (map[string]interface{}, error) {
object := make(map[string]interface{})
for decoder.More() {
key, err := collectUnknownField(decoder)
if err != nil {
return nil, err
}
// Keys have to be strings, which is particularly important as the encoder
// won't except a map with interface{} keys
stringKey, ok := key.(string)
if !ok {
return nil, fmt.Errorf("expected string key, found %T", key)
}
value, err := collectUnknownField(decoder)
if err != nil {
return nil, err
}
object[stringKey] = value
}
return object, nil
}

View File

@ -0,0 +1,30 @@
package json
import (
"bytes"
)
// Encoder is JSON encoder that supports construction of JSON values
// using methods.
type Encoder struct {
w *bytes.Buffer
Value
}
// NewEncoder returns a new JSON encoder
func NewEncoder() *Encoder {
writer := bytes.NewBuffer(nil)
scratch := make([]byte, 64)
return &Encoder{w: writer, Value: newValue(writer, &scratch)}
}
// String returns the String output of the JSON encoder
func (e Encoder) String() string {
return e.w.String()
}
// Bytes returns the []byte slice of the JSON encoder
func (e Encoder) Bytes() []byte {
return e.w.Bytes()
}

198
vendor/github.com/aws/smithy-go/encoding/json/escape.go generated vendored Normal file
View File

@ -0,0 +1,198 @@
// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Copied and modified from Go 1.8 stdlib's encoding/json/#safeSet
package json
import (
"bytes"
"unicode/utf8"
)
// safeSet holds the value true if the ASCII character with the given array
// position can be represented inside a JSON string without any further
// escaping.
//
// All values are true except for the ASCII control characters (0-31), the
// double quote ("), and the backslash character ("\").
var safeSet = [utf8.RuneSelf]bool{
' ': true,
'!': true,
'"': false,
'#': true,
'$': true,
'%': true,
'&': true,
'\'': true,
'(': true,
')': true,
'*': true,
'+': true,
',': true,
'-': true,
'.': true,
'/': true,
'0': true,
'1': true,
'2': true,
'3': true,
'4': true,
'5': true,
'6': true,
'7': true,
'8': true,
'9': true,
':': true,
';': true,
'<': true,
'=': true,
'>': true,
'?': true,
'@': true,
'A': true,
'B': true,
'C': true,
'D': true,
'E': true,
'F': true,
'G': true,
'H': true,
'I': true,
'J': true,
'K': true,
'L': true,
'M': true,
'N': true,
'O': true,
'P': true,
'Q': true,
'R': true,
'S': true,
'T': true,
'U': true,
'V': true,
'W': true,
'X': true,
'Y': true,
'Z': true,
'[': true,
'\\': false,
']': true,
'^': true,
'_': true,
'`': true,
'a': true,
'b': true,
'c': true,
'd': true,
'e': true,
'f': true,
'g': true,
'h': true,
'i': true,
'j': true,
'k': true,
'l': true,
'm': true,
'n': true,
'o': true,
'p': true,
'q': true,
'r': true,
's': true,
't': true,
'u': true,
'v': true,
'w': true,
'x': true,
'y': true,
'z': true,
'{': true,
'|': true,
'}': true,
'~': true,
'\u007f': true,
}
// copied from Go 1.8 stdlib's encoding/json/#hex
var hex = "0123456789abcdef"
// escapeStringBytes escapes and writes the passed in string bytes to the dst
// buffer
//
// Copied and modifed from Go 1.8 stdlib's encodeing/json/#encodeState.stringBytes
func escapeStringBytes(e *bytes.Buffer, s []byte) {
e.WriteByte('"')
start := 0
for i := 0; i < len(s); {
if b := s[i]; b < utf8.RuneSelf {
if safeSet[b] {
i++
continue
}
if start < i {
e.Write(s[start:i])
}
switch b {
case '\\', '"':
e.WriteByte('\\')
e.WriteByte(b)
case '\n':
e.WriteByte('\\')
e.WriteByte('n')
case '\r':
e.WriteByte('\\')
e.WriteByte('r')
case '\t':
e.WriteByte('\\')
e.WriteByte('t')
default:
// This encodes bytes < 0x20 except for \t, \n and \r.
// If escapeHTML is set, it also escapes <, >, and &
// because they can lead to security holes when
// user-controlled strings are rendered into JSON
// and served to some browsers.
e.WriteString(`\u00`)
e.WriteByte(hex[b>>4])
e.WriteByte(hex[b&0xF])
}
i++
start = i
continue
}
c, size := utf8.DecodeRune(s[i:])
if c == utf8.RuneError && size == 1 {
if start < i {
e.Write(s[start:i])
}
e.WriteString(`\ufffd`)
i += size
start = i
continue
}
// U+2028 is LINE SEPARATOR.
// U+2029 is PARAGRAPH SEPARATOR.
// They are both technically valid characters in JSON strings,
// but don't work in JSONP, which has to be evaluated as JavaScript,
// and can lead to security holes there. It is valid JSON to
// escape them, so we do so unconditionally.
// See http://timelessrepo.com/json-isnt-a-javascript-subset for discussion.
if c == '\u2028' || c == '\u2029' {
if start < i {
e.Write(s[start:i])
}
e.WriteString(`\u202`)
e.WriteByte(hex[c&0xF])
i += size
start = i
continue
}
i += size
}
if start < len(s) {
e.Write(s[start:])
}
e.WriteByte('"')
}

View File

@ -0,0 +1,40 @@
package json
import (
"bytes"
)
// Object represents the encoding of a JSON Object type
type Object struct {
w *bytes.Buffer
writeComma bool
scratch *[]byte
}
func newObject(w *bytes.Buffer, scratch *[]byte) *Object {
w.WriteRune(leftBrace)
return &Object{w: w, scratch: scratch}
}
func (o *Object) writeKey(key string) {
escapeStringBytes(o.w, []byte(key))
o.w.WriteRune(colon)
}
// Key adds the given named key to the JSON object.
// Returns a Value encoder that should be used to encode
// a JSON value type.
func (o *Object) Key(name string) Value {
if o.writeComma {
o.w.WriteRune(comma)
} else {
o.writeComma = true
}
o.writeKey(name)
return newValue(o.w, o.scratch)
}
// Close encodes the end of the JSON Object
func (o *Object) Close() {
o.w.WriteRune(rightBrace)
}

149
vendor/github.com/aws/smithy-go/encoding/json/value.go generated vendored Normal file
View File

@ -0,0 +1,149 @@
package json
import (
"bytes"
"encoding/base64"
"math/big"
"strconv"
"github.com/aws/smithy-go/encoding"
)
// Value represents a JSON Value type
// JSON Value types: Object, Array, String, Number, Boolean, and Null
type Value struct {
w *bytes.Buffer
scratch *[]byte
}
// newValue returns a new Value encoder
func newValue(w *bytes.Buffer, scratch *[]byte) Value {
return Value{w: w, scratch: scratch}
}
// String encodes v as a JSON string
func (jv Value) String(v string) {
escapeStringBytes(jv.w, []byte(v))
}
// Byte encodes v as a JSON number
func (jv Value) Byte(v int8) {
jv.Long(int64(v))
}
// Short encodes v as a JSON number
func (jv Value) Short(v int16) {
jv.Long(int64(v))
}
// Integer encodes v as a JSON number
func (jv Value) Integer(v int32) {
jv.Long(int64(v))
}
// Long encodes v as a JSON number
func (jv Value) Long(v int64) {
*jv.scratch = strconv.AppendInt((*jv.scratch)[:0], v, 10)
jv.w.Write(*jv.scratch)
}
// ULong encodes v as a JSON number
func (jv Value) ULong(v uint64) {
*jv.scratch = strconv.AppendUint((*jv.scratch)[:0], v, 10)
jv.w.Write(*jv.scratch)
}
// Float encodes v as a JSON number
func (jv Value) Float(v float32) {
jv.float(float64(v), 32)
}
// Double encodes v as a JSON number
func (jv Value) Double(v float64) {
jv.float(v, 64)
}
func (jv Value) float(v float64, bits int) {
*jv.scratch = encoding.EncodeFloat((*jv.scratch)[:0], v, bits)
jv.w.Write(*jv.scratch)
}
// Boolean encodes v as a JSON boolean
func (jv Value) Boolean(v bool) {
*jv.scratch = strconv.AppendBool((*jv.scratch)[:0], v)
jv.w.Write(*jv.scratch)
}
// Base64EncodeBytes writes v as a base64 value in JSON string
func (jv Value) Base64EncodeBytes(v []byte) {
encodeByteSlice(jv.w, (*jv.scratch)[:0], v)
}
// Write writes v directly to the JSON document
func (jv Value) Write(v []byte) {
jv.w.Write(v)
}
// Array returns a new Array encoder
func (jv Value) Array() *Array {
return newArray(jv.w, jv.scratch)
}
// Object returns a new Object encoder
func (jv Value) Object() *Object {
return newObject(jv.w, jv.scratch)
}
// Null encodes a null JSON value
func (jv Value) Null() {
jv.w.WriteString(null)
}
// BigInteger encodes v as JSON value
func (jv Value) BigInteger(v *big.Int) {
jv.w.Write([]byte(v.Text(10)))
}
// BigDecimal encodes v as JSON value
func (jv Value) BigDecimal(v *big.Float) {
if i, accuracy := v.Int64(); accuracy == big.Exact {
jv.Long(i)
return
}
// TODO: Should this try to match ES6 ToString similar to stdlib JSON?
jv.w.Write([]byte(v.Text('e', -1)))
}
// Based on encoding/json encodeByteSlice from the Go Standard Library
// https://golang.org/src/encoding/json/encode.go
func encodeByteSlice(w *bytes.Buffer, scratch []byte, v []byte) {
if v == nil {
w.WriteString(null)
return
}
w.WriteRune(quote)
encodedLen := base64.StdEncoding.EncodedLen(len(v))
if encodedLen <= len(scratch) {
// If the encoded bytes fit in e.scratch, avoid an extra
// allocation and use the cheaper Encoding.Encode.
dst := scratch[:encodedLen]
base64.StdEncoding.Encode(dst, v)
w.Write(dst)
} else if encodedLen <= 1024 {
// The encoded bytes are short enough to allocate for, and
// Encoding.Encode is still cheaper.
dst := make([]byte, encodedLen)
base64.StdEncoding.Encode(dst, v)
w.Write(dst)
} else {
// The encoded bytes are too long to cheaply allocate, and
// Encoding.Encode is no longer noticeably cheaper.
enc := base64.NewEncoder(base64.StdEncoding, w)
enc.Write(v)
enc.Close()
}
w.WriteRune(quote)
}

View File

@ -2,7 +2,7 @@
Package xml holds the XMl encoder utility. This utility is written in accordance to our design to delegate to
shape serializer function in which a xml.Value will be passed around.
Resources followed: https://awslabs.github.io/smithy/1.0/spec/core/xml-traits.html#
Resources followed: https://smithy.io/2.0/spec/protocol-traits.html#xml-bindings
Member Element

View File

@ -3,4 +3,4 @@
package smithy
// goModuleVersion is the tagged release for this module
const goModuleVersion = "1.11.2"
const goModuleVersion = "1.13.5"

View File

@ -0,0 +1,28 @@
Copyright (c) 2009 The Go Authors. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google Inc. nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View File

@ -0,0 +1,8 @@
// Package singleflight provides a duplicate function call suppression
// mechanism. This package is a fork of the Go golang.org/x/sync/singleflight
// package. The package is forked, because the package a part of the unstable
// and unversioned golang.org/x/sync module.
//
// https://github.com/golang/sync/tree/67f06af15bc961c363a7260195bcd53487529a21/singleflight
package singleflight

View File

@ -0,0 +1,210 @@
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package singleflight
import (
"bytes"
"errors"
"fmt"
"runtime"
"runtime/debug"
"sync"
)
// errGoexit indicates the runtime.Goexit was called in
// the user given function.
var errGoexit = errors.New("runtime.Goexit was called")
// A panicError is an arbitrary value recovered from a panic
// with the stack trace during the execution of given function.
type panicError struct {
value interface{}
stack []byte
}
// Error implements error interface.
func (p *panicError) Error() string {
return fmt.Sprintf("%v\n\n%s", p.value, p.stack)
}
func newPanicError(v interface{}) error {
stack := debug.Stack()
// The first line of the stack trace is of the form "goroutine N [status]:"
// but by the time the panic reaches Do the goroutine may no longer exist
// and its status will have changed. Trim out the misleading line.
if line := bytes.IndexByte(stack[:], '\n'); line >= 0 {
stack = stack[line+1:]
}
return &panicError{value: v, stack: stack}
}
// call is an in-flight or completed singleflight.Do call
type call struct {
wg sync.WaitGroup
// These fields are written once before the WaitGroup is done
// and are only read after the WaitGroup is done.
val interface{}
err error
// forgotten indicates whether Forget was called with this call's key
// while the call was still in flight.
forgotten bool
// These fields are read and written with the singleflight
// mutex held before the WaitGroup is done, and are read but
// not written after the WaitGroup is done.
dups int
chans []chan<- Result
}
// Group represents a class of work and forms a namespace in
// which units of work can be executed with duplicate suppression.
type Group struct {
mu sync.Mutex // protects m
m map[string]*call // lazily initialized
}
// Result holds the results of Do, so they can be passed
// on a channel.
type Result struct {
Val interface{}
Err error
Shared bool
}
// Do executes and returns the results of the given function, making
// sure that only one execution is in-flight for a given key at a
// time. If a duplicate comes in, the duplicate caller waits for the
// original to complete and receives the same results.
// The return value shared indicates whether v was given to multiple callers.
func (g *Group) Do(key string, fn func() (interface{}, error)) (v interface{}, err error, shared bool) {
g.mu.Lock()
if g.m == nil {
g.m = make(map[string]*call)
}
if c, ok := g.m[key]; ok {
c.dups++
g.mu.Unlock()
c.wg.Wait()
if e, ok := c.err.(*panicError); ok {
panic(e)
} else if c.err == errGoexit {
runtime.Goexit()
}
return c.val, c.err, true
}
c := new(call)
c.wg.Add(1)
g.m[key] = c
g.mu.Unlock()
g.doCall(c, key, fn)
return c.val, c.err, c.dups > 0
}
// DoChan is like Do but returns a channel that will receive the
// results when they are ready.
//
// The returned channel will not be closed.
func (g *Group) DoChan(key string, fn func() (interface{}, error)) <-chan Result {
ch := make(chan Result, 1)
g.mu.Lock()
if g.m == nil {
g.m = make(map[string]*call)
}
if c, ok := g.m[key]; ok {
c.dups++
c.chans = append(c.chans, ch)
g.mu.Unlock()
return ch
}
c := &call{chans: []chan<- Result{ch}}
c.wg.Add(1)
g.m[key] = c
g.mu.Unlock()
go g.doCall(c, key, fn)
return ch
}
// doCall handles the single call for a key.
func (g *Group) doCall(c *call, key string, fn func() (interface{}, error)) {
normalReturn := false
recovered := false
// use double-defer to distinguish panic from runtime.Goexit,
// more details see https://golang.org/cl/134395
defer func() {
// the given function invoked runtime.Goexit
if !normalReturn && !recovered {
c.err = errGoexit
}
c.wg.Done()
g.mu.Lock()
defer g.mu.Unlock()
if !c.forgotten {
delete(g.m, key)
}
if e, ok := c.err.(*panicError); ok {
// In order to prevent the waiting channels from being blocked forever,
// needs to ensure that this panic cannot be recovered.
if len(c.chans) > 0 {
go panic(e)
select {} // Keep this goroutine around so that it will appear in the crash dump.
} else {
panic(e)
}
} else if c.err == errGoexit {
// Already in the process of goexit, no need to call again
} else {
// Normal return
for _, ch := range c.chans {
ch <- Result{c.val, c.err, c.dups > 0}
}
}
}()
func() {
defer func() {
if !normalReturn {
// Ideally, we would wait to take a stack trace until we've determined
// whether this is a panic or a runtime.Goexit.
//
// Unfortunately, the only way we can distinguish the two is to see
// whether the recover stopped the goroutine from terminating, and by
// the time we know that, the part of the stack trace relevant to the
// panic has been discarded.
if r := recover(); r != nil {
c.err = newPanicError(r)
}
}
}()
c.val, c.err = fn()
normalReturn = true
}()
if !normalReturn {
recovered = true
}
}
// Forget tells the singleflight to forget about a key. Future calls
// to Do for this key will call the function rather than waiting for
// an earlier call to complete.
func (g *Group) Forget(key string) {
g.mu.Lock()
if c, ok := g.m[key]; ok {
c.forgotten = true
}
delete(g.m, key)
g.mu.Unlock()
}

11
vendor/github.com/aws/smithy-go/modman.toml generated vendored Normal file
View File

@ -0,0 +1,11 @@
[dependencies]
"github.com/google/go-cmp" = "v0.5.8"
"github.com/jmespath/go-jmespath" = "v0.4.0"
[modules]
[modules.codegen]
no_tag = true
[modules."codegen/smithy-go-codegen/build/test-generated/go/internal/testmodule"]
no_tag = true

View File

@ -7,6 +7,85 @@ import (
"github.com/aws/smithy-go/middleware"
)
type isContentTypeAutoSet struct{}
// SetIsContentTypeDefaultValue returns a Context specifying if the request's
// content-type header was set to a default value.
func SetIsContentTypeDefaultValue(ctx context.Context, isDefault bool) context.Context {
return context.WithValue(ctx, isContentTypeAutoSet{}, isDefault)
}
// GetIsContentTypeDefaultValue returns if the content-type HTTP header on the
// request is a default value that was auto assigned by an operation
// serializer. Allows middleware post serialization to know if the content-type
// was auto set to a default value or not.
//
// Also returns false if the Context value was never updated to include if
// content-type was set to a default value.
func GetIsContentTypeDefaultValue(ctx context.Context) bool {
v, _ := ctx.Value(isContentTypeAutoSet{}).(bool)
return v
}
// AddNoPayloadDefaultContentTypeRemover Adds the DefaultContentTypeRemover
// middleware to the stack after the operation serializer. This middleware will
// remove the content-type header from the request if it was set as a default
// value, and no request payload is present.
//
// Returns error if unable to add the middleware.
func AddNoPayloadDefaultContentTypeRemover(stack *middleware.Stack) (err error) {
err = stack.Serialize.Insert(removeDefaultContentType{},
"OperationSerializer", middleware.After)
if err != nil {
return fmt.Errorf("failed to add %s serialize middleware, %w",
removeDefaultContentType{}.ID(), err)
}
return nil
}
// RemoveNoPayloadDefaultContentTypeRemover removes the
// DefaultContentTypeRemover middleware from the stack. Returns an error if
// unable to remove the middleware.
func RemoveNoPayloadDefaultContentTypeRemover(stack *middleware.Stack) (err error) {
_, err = stack.Serialize.Remove(removeDefaultContentType{}.ID())
if err != nil {
return fmt.Errorf("failed to remove %s serialize middleware, %w",
removeDefaultContentType{}.ID(), err)
}
return nil
}
// removeDefaultContentType provides after serialization middleware that will
// remove the content-type header from an HTTP request if the header was set as
// a default value by the operation serializer, and there is no request payload.
type removeDefaultContentType struct{}
// ID returns the middleware ID
func (removeDefaultContentType) ID() string { return "RemoveDefaultContentType" }
// HandleSerialize implements the serialization middleware.
func (removeDefaultContentType) HandleSerialize(
ctx context.Context, input middleware.SerializeInput, next middleware.SerializeHandler,
) (
out middleware.SerializeOutput, meta middleware.Metadata, err error,
) {
req, ok := input.Request.(*Request)
if !ok {
return out, meta, fmt.Errorf(
"unexpected request type %T for removeDefaultContentType middleware",
input.Request)
}
if GetIsContentTypeDefaultValue(ctx) && req.GetStream() == nil {
req.Header.Del("Content-Type")
input.Request = req
}
return next.HandleSerialize(ctx, input)
}
type headerValue struct {
header string
value string

View File

@ -7,6 +7,7 @@ import (
"io/ioutil"
"net/http"
"net/url"
"strings"
iointernal "github.com/aws/smithy-go/transport/http/internal/io"
)
@ -33,6 +34,14 @@ func NewStackRequest() interface{} {
}
}
// IsHTTPS returns if the request is HTTPS. Returns false if no endpoint URL is set.
func (r *Request) IsHTTPS() bool {
if r.URL == nil {
return false
}
return strings.EqualFold(r.URL.Scheme, "https")
}
// Clone returns a deep copy of the Request for the new context. A reference to
// the Stream is copied, but the underlying stream is not copied.
func (r *Request) Clone() *Request {