diff --git a/Gopkg.lock b/Gopkg.lock index aec9bdd..5138022 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -28,6 +28,26 @@ pruneopts = "NUT" revision = "cd527374f1e5bff4938207604a14f2e38a9cf512" +[[projects]] + digest = "1:d5f84ab6442ff802bac0cdbf88a28200220401701ea713d2986c225140676ca2" + name = "github.com/aws/aws-sdk-go-v2" + packages = [ + "aws", + "aws/awserr", + "aws/signer/v4", + "internal/awsutil", + "internal/sdk", + "private/protocol", + "private/protocol/json/jsonutil", + "private/protocol/jsonrpc", + "private/protocol/rest", + "service/acmpca", + "service/acmpca/acmpcaiface", + ] + pruneopts = "NUT" + revision = "c2b476bac53067cebc587747e866881b2e383625" + version = "v0.7.0" + [[projects]] digest = "1:063db6a0b87d39e99b3102a293cf675c23bb82074acea0a3e9276b3331216c2a" name = "github.com/cenkalti/backoff" @@ -256,15 +276,21 @@ version = "v1.0.2" [[projects]] - branch = "master" - digest = "1:60982783cd8054c5c5fc3cf4e30861a64ca4196487df224655daf01f1a5b2fc3" + digest = "1:1f2aebae7e7c856562355ec0198d8ca2fa222fb05e5b1b66632a1fce39631885" + name = "github.com/jmespath/go-jmespath" + packages = ["."] + pruneopts = "NUT" + revision = "c2b33e84" + +[[projects]] + digest = "1:7bebc379efb58f69e1a25422674120b143194f61a7c3bcf8e58704d2f2ce8697" name = "github.com/matryer/moq" packages = [ ".", "pkg/moq", ] pruneopts = "NUT" - revision = "39f6db0ed38f1ce0d1d60e18e6a9ab27c3834bd6" + revision = "c4521bcc9dbca426d823d54b775a85c30cc527db" [[projects]] branch = "master" @@ -317,11 +343,13 @@ version = "v1.4.0" [[projects]] - digest = "1:feed851b93f9debbe8180092067c4e29a51c06dbb5fe2f643ec9feea039670a3" + digest = "1:2818b181473a181ae7b727cb5e505ca0e8e5b696b6929c050262820c6152d63b" name = "github.com/onsi/gomega" packages = [ ".", "format", + "gstruct", + "gstruct/errors", "internal/assertion", "internal/asyncassertion", "internal/oraclematcher", @@ -572,6 +600,9 @@ analyzer-name = "dep" analyzer-version = 1 input-imports = [ + "github.com/aws/aws-sdk-go-v2/aws", + "github.com/aws/aws-sdk-go-v2/service/acmpca", + "github.com/aws/aws-sdk-go-v2/service/acmpca/acmpcaiface", "github.com/cloudflare/cfssl/api/client", "github.com/cloudflare/cfssl/auth", "github.com/cloudflare/cfssl/config", @@ -585,6 +616,7 @@ "github.com/onsi/ginkgo", "github.com/onsi/ginkgo/ginkgo", "github.com/onsi/gomega", + "github.com/onsi/gomega/gstruct", "github.com/ory/dockertest", "golang.org/x/net/context", "golang.org/x/sync/singleflight", diff --git a/Gopkg.toml b/Gopkg.toml index f929399..f6cfbf9 100644 --- a/Gopkg.toml +++ b/Gopkg.toml @@ -20,3 +20,12 @@ required = [ [[constraint]] name = "github.com/cloudflare/cfssl" version = "1.3.2" + +[[constraint]] + name = "github.com/aws/aws-sdk-go-v2" + version = "0.7.0" + +[[constraint]] + name = "github.com/matryer/moq" + # Pending https://github.com/matryer/moq/issues/86 + revision = "c4521bcc9dbca426d823d54b775a85c30cc527db" diff --git a/issuers/aws/.gitignore b/issuers/aws/.gitignore new file mode 100644 index 0000000..cf0726f --- /dev/null +++ b/issuers/aws/.gitignore @@ -0,0 +1 @@ +aws_secret_test.go diff --git a/issuers/aws/aws.go b/issuers/aws/aws.go new file mode 100644 index 0000000..43618fe --- /dev/null +++ b/issuers/aws/aws.go @@ -0,0 +1,178 @@ +package aws + +import ( + "context" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/tls" + "crypto/x509" + "crypto/x509/pkix" + "encoding/pem" + "errors" + "fmt" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/acmpca" + iface "github.com/aws/aws-sdk-go-v2/service/acmpca/acmpcaiface" + + "github.com/johanbrandhorst/certify" +) + +// Issuer implements the Issuer interface with a +// AWS Certificate Manager Private Certificate Authority backend. +// +// Client and CertificateAuthorityARN are required. +type Issuer struct { + // Client is a pre-created ACMPCA client. It can be created + // via, for example: + // conf, err := external.LoadDefaultAWSConfig() + // if err != nil { + // return nil, err + // } + // conf.Region = endpoints.EuWest2RegionID + // conf.Credentials = aws.NewStaticCredentialsProvider("YOURKEY", "YOURKEYSECRET", "") + // cli := acmpca.New(conf) + Client iface.ACMPCAAPI + // CertificateAuthorityARN specifies the ARN of a pre-created CA + // which will be used to issue the certificates. + CertificateAuthorityARN string + + // TimeToLive configures the lifetime of certificates + // requested from the AWS CA, in number of days. + // If unset, defaults to 30 days. + TimeToLive int + + caCert *x509.Certificate + signAlgo acmpca.SigningAlgorithm +} + +// Issue issues a certificate from the configured AWS CA backend. +func (i Issuer) Issue(ctx context.Context, commonName string, conf *certify.CertConfig) (*tls.Certificate, error) { + if i.caCert == nil { + caReq := i.Client.GetCertificateAuthorityCertificateRequest(&acmpca.GetCertificateAuthorityCertificateInput{ + CertificateAuthorityArn: aws.String(i.CertificateAuthorityARN), + }) + + caResp, err := caReq.Send() + if err != nil { + return nil, err + } + + caBlock, _ := pem.Decode([]byte(*caResp.Certificate)) + if caBlock == nil { + return nil, errors.New("could not parse AWS CA cert") + } + + if caBlock.Type != "CERTIFICATE" { + return nil, errors.New("saw unexpected PEM Type while requesting AWS CA cert: " + caBlock.Type) + } + + i.caCert, err = x509.ParseCertificate(caBlock.Bytes) + if err != nil { + return nil, err + } + + switch i.caCert.SignatureAlgorithm { + case x509.SHA256WithRSA: + i.signAlgo = acmpca.SigningAlgorithmSha256withrsa + case x509.SHA384WithRSA: + i.signAlgo = acmpca.SigningAlgorithmSha384withrsa + case x509.SHA512WithRSA: + i.signAlgo = acmpca.SigningAlgorithmSha512withrsa + case x509.ECDSAWithSHA256: + i.signAlgo = acmpca.SigningAlgorithmSha256withecdsa + case x509.ECDSAWithSHA384: + i.signAlgo = acmpca.SigningAlgorithmSha384withecdsa + case x509.ECDSAWithSHA512: + i.signAlgo = acmpca.SigningAlgorithmSha512withecdsa + default: + return nil, fmt.Errorf("unsupported CA cert signing algorithm: %T", i.caCert.SignatureAlgorithm) + } + } + + pk, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + return nil, err + } + + keyBytes, err := x509.MarshalECPrivateKey(pk) + if err != nil { + return nil, err + } + + keyPEM := pem.EncodeToMemory(&pem.Block{ + Type: "EC PRIVATE KEY", + Bytes: keyBytes, + }) + + template := &x509.CertificateRequest{ + SignatureAlgorithm: x509.ECDSAWithSHA256, + Subject: pkix.Name{ + CommonName: commonName, + }, + } + + if conf != nil { + template.DNSNames = conf.SubjectAlternativeNames + template.IPAddresses = conf.IPSubjectAlternativeNames + } + + csr, err := x509.CreateCertificateRequest(rand.Reader, template, pk) + if err != nil { + return nil, err + } + + csrPEM := pem.EncodeToMemory(&pem.Block{ + Type: "CERTIFICATE REQUEST", + Bytes: csr, + }) + + // Default to 30 days if unset. + ttl := int64(30) + if i.TimeToLive > 0 { + ttl = int64(i.TimeToLive) + } + + csrReq := i.Client.IssueCertificateRequest(&acmpca.IssueCertificateInput{ + CertificateAuthorityArn: aws.String(i.CertificateAuthorityARN), + Csr: csrPEM, + SigningAlgorithm: i.signAlgo, + Validity: &acmpca.Validity{ + Type: acmpca.ValidityPeriodTypeDays, + Value: aws.Int64(ttl), + }, + }) + + csrResp, err := csrReq.Send() + if err != nil { + return nil, err + } + + getReq := &acmpca.GetCertificateInput{ + CertificateArn: csrResp.CertificateArn, + CertificateAuthorityArn: aws.String(i.CertificateAuthorityARN), + } + err = i.Client.WaitUntilCertificateIssuedWithContext(ctx, getReq) + if err != nil { + return nil, err + } + + certReq := i.Client.GetCertificateRequest(getReq) + + certResp, err := certReq.Send() + if err != nil { + return nil, err + } + + caChainPEM := append([]byte(*certResp.Certificate), []byte(*certResp.CertificateChain)...) + + tlsCert, err := tls.X509KeyPair(caChainPEM, keyPEM) + if err != nil { + return nil, err + } + + // This can't error since it's called in tls.X509KeyPair above successfully + tlsCert.Leaf, _ = x509.ParseCertificate(tlsCert.Certificate[0]) + return &tlsCert, nil +} diff --git a/issuers/aws/aws_suite_test.go b/issuers/aws/aws_suite_test.go new file mode 100644 index 0000000..e827b42 --- /dev/null +++ b/issuers/aws/aws_suite_test.go @@ -0,0 +1,13 @@ +package aws_test + +import ( + "testing" + + . "github.com/onsi/ginkgo" + . "github.com/onsi/gomega" +) + +func TestAws(t *testing.T) { + RegisterFailHandler(Fail) + RunSpecs(t, "Aws Suite") +} diff --git a/issuers/aws/aws_test.go b/issuers/aws/aws_test.go new file mode 100644 index 0000000..f9155d5 --- /dev/null +++ b/issuers/aws/aws_test.go @@ -0,0 +1,229 @@ +package aws_test + +import ( + "context" + "crypto/rand" + "crypto/rsa" + "crypto/x509" + "crypto/x509/pkix" + "encoding/pem" + "math/big" + "net" + "time" + + api "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/acmpca" + . "github.com/onsi/ginkgo" + . "github.com/onsi/gomega" + . "github.com/onsi/gomega/gstruct" + + "github.com/johanbrandhorst/certify" + "github.com/johanbrandhorst/certify/issuers/aws" + "github.com/johanbrandhorst/certify/issuers/aws/mocks" +) + +//go:generate moq -out mocks/client.mock.go -pkg mocks ../../vendor/github.com/aws/aws-sdk-go-v2/service/acmpca/acmpcaiface ACMPCAAPI + +var _ = Describe("AWS Issuer", func() { + It("issues a certificate", func() { + caARN := "someARN" + certARN := "anotherARN" + caCert, caKey, err := generateCertAndKey() + Expect(err).To(Succeed()) + client := &mocks.ACMPCAAPIMock{} + iss := &aws.Issuer{ + CertificateAuthorityARN: caARN, + Client: client, + TimeToLive: 25, + } + var signedCert []byte + client.IssueCertificateRequestFunc = func(in1 *acmpca.IssueCertificateInput) acmpca.IssueCertificateRequest { + Expect(in1.CertificateAuthorityArn).To(PointTo(Equal(caARN))) + Expect(in1.Validity.Value).To(PointTo(BeEquivalentTo(iss.TimeToLive))) + b, _ := pem.Decode(in1.Csr) + csr, err := x509.ParseCertificateRequest(b.Bytes) + Expect(err).NotTo(HaveOccurred()) + serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128) + serialNumber, err := rand.Int(rand.Reader, serialNumberLimit) + Expect(err).NotTo(HaveOccurred()) + template := &x509.Certificate{ + SerialNumber: serialNumber, + Subject: csr.Subject, + PublicKeyAlgorithm: csr.PublicKeyAlgorithm, + PublicKey: csr.PublicKey, + SignatureAlgorithm: x509.SHA256WithRSA, + DNSNames: csr.DNSNames, + IPAddresses: csr.IPAddresses, + EmailAddresses: csr.EmailAddresses, + URIs: csr.URIs, + NotBefore: time.Now(), + NotAfter: time.Now().AddDate(0, 0, int(*in1.Validity.Value)), + } + crt, err := x509.CreateCertificate(rand.Reader, template, caCert.cert, csr.PublicKey, caKey.key) + Expect(err).NotTo(HaveOccurred()) + signedCert = pem.EncodeToMemory(&pem.Block{ + Type: "CERTIFICATE", + Bytes: crt, + }) + hl := api.HandlerList{} + hl.PushBackNamed(api.NamedHandler{ + Name: "Send", + Fn: func(in *api.Request) { + in.Data = &acmpca.IssueCertificateOutput{ + CertificateArn: api.String(certARN), + } + }, + }) + return acmpca.IssueCertificateRequest{ + Request: &api.Request{ + Handlers: api.Handlers{ + Send: hl, + }, + }, + Input: in1, + } + } + client.GetCertificateRequestFunc = func(in1 *acmpca.GetCertificateInput) acmpca.GetCertificateRequest { + Expect(in1.CertificateArn).To(PointTo(Equal(certARN))) + Expect(in1.CertificateAuthorityArn).To(PointTo(Equal(caARN))) + hl := api.HandlerList{} + hl.PushBackNamed(api.NamedHandler{ + Name: "Send", + Fn: func(in *api.Request) { + in.Data = &acmpca.GetCertificateOutput{ + Certificate: api.String(string(signedCert)), + CertificateChain: api.String(string(caCert.pem)), + } + }, + }) + return acmpca.GetCertificateRequest{ + Request: &api.Request{ + Handlers: api.Handlers{ + Send: hl, + }, + }, + Input: in1, + } + } + client.GetCertificateAuthorityCertificateRequestFunc = func(in1 *acmpca.GetCertificateAuthorityCertificateInput) acmpca.GetCertificateAuthorityCertificateRequest { + Expect(in1.CertificateAuthorityArn).To(PointTo(Equal(caARN))) + hl := api.HandlerList{} + hl.PushBackNamed(api.NamedHandler{ + Name: "Send", + Fn: func(in *api.Request) { + in.Data = &acmpca.GetCertificateAuthorityCertificateOutput{ + Certificate: api.String(string(caCert.pem)), + CertificateChain: api.String(string(caCert.pem)), + } + }, + }) + return acmpca.GetCertificateAuthorityCertificateRequest{ + Request: &api.Request{ + Handlers: api.Handlers{ + Send: hl, + }, + }, + Input: in1, + } + } + client.WaitUntilCertificateIssuedWithContextFunc = func(in1 api.Context, in2 *acmpca.GetCertificateInput, in3 ...api.WaiterOption) error { + Expect(in2.CertificateAuthorityArn).To(PointTo(Equal(caARN))) + Expect(in2.CertificateArn).To(PointTo(Equal(certARN))) + hl := api.HandlerList{} + hl.PushBackNamed(api.NamedHandler{ + Name: "Send", + Fn: func(in *api.Request) { + in.Data = &acmpca.GetCertificateAuthorityCertificateOutput{ + Certificate: api.String(string(caCert.pem)), + CertificateChain: api.String(string(caCert.pem)), + } + }, + }) + return nil + } + + cn := "somename.com" + conf := &certify.CertConfig{ + SubjectAlternativeNames: []string{"extraname.com", "otherextraname.com"}, + IPSubjectAlternativeNames: []net.IP{net.IPv4(1, 2, 3, 4), net.IPv6loopback}, + } + tlsCert, err := iss.Issue(context.Background(), cn, conf) + Expect(err).NotTo(HaveOccurred()) + + Expect(tlsCert.Leaf).NotTo(BeNil(), "tlsCert.Leaf should be populated by Issue to track expiry") + Expect(tlsCert.Leaf.Subject.CommonName).To(Equal(cn)) + Expect(tlsCert.Leaf.DNSNames).To(Equal(conf.SubjectAlternativeNames)) + Expect(tlsCert.Leaf.IPAddresses).To(HaveLen(len(conf.IPSubjectAlternativeNames))) + for i, ip := range tlsCert.Leaf.IPAddresses { + Expect(ip.Equal(conf.IPSubjectAlternativeNames[i])).To(BeTrue()) + } + + // Check that chain is included + Expect(tlsCert.Certificate).To(HaveLen(2)) + crt, err := x509.ParseCertificate(tlsCert.Certificate[1]) + Expect(err).NotTo(HaveOccurred()) + Expect(crt.Subject.SerialNumber).To(Equal(tlsCert.Leaf.Issuer.SerialNumber)) + + Expect(tlsCert.Leaf.NotBefore).To(BeTemporally("<", time.Now())) + Expect(tlsCert.Leaf.NotAfter).To(BeTemporally("~", time.Now().AddDate(0, 0, iss.TimeToLive), 5*time.Second)) + }) +}) + +type key struct { + pem []byte + key *rsa.PrivateKey +} + +type cert struct { + pem []byte + cert *x509.Certificate +} + +func generateCertAndKey() (*cert, *key, error) { + priv, err := rsa.GenerateKey(rand.Reader, 2048) + if err != nil { + return nil, nil, err + } + notBefore := time.Now() + notAfter := notBefore.Add(time.Hour) + serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128) + serialNumber, err := rand.Int(rand.Reader, serialNumberLimit) + if err != nil { + return nil, nil, err + } + template := x509.Certificate{ + SerialNumber: serialNumber, + Subject: pkix.Name{ + CommonName: "Certify Test Cert", + }, + NotBefore: notBefore, + NotAfter: notAfter, + KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, + BasicConstraintsValid: true, + } + derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, priv.Public(), priv) + if err != nil { + return nil, nil, err + } + + k := &key{ + key: priv, + pem: pem.EncodeToMemory(&pem.Block{ + Type: "RSA PRIVATE KEY", + Bytes: x509.MarshalPKCS1PrivateKey(priv), + }), + } + crt, err := x509.ParseCertificate(derBytes) + if err != nil { + return nil, nil, err + } + c := &cert{ + cert: crt, + pem: pem.EncodeToMemory(&pem.Block{ + Type: "CERTIFICATE", + Bytes: derBytes, + }), + } + return c, k, nil +} diff --git a/issuers/aws/mocks/client.mock.go b/issuers/aws/mocks/client.mock.go new file mode 100644 index 0000000..ee8d6f3 --- /dev/null +++ b/issuers/aws/mocks/client.mock.go @@ -0,0 +1,1056 @@ +// Code generated by moq; DO NOT EDIT. +// github.com/matryer/moq + +package mocks + +import ( + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/acmpca" + "sync" +) + +var ( + lockACMPCAAPIMockCreateCertificateAuthorityAuditReportRequest sync.RWMutex + lockACMPCAAPIMockCreateCertificateAuthorityRequest sync.RWMutex + lockACMPCAAPIMockDeleteCertificateAuthorityRequest sync.RWMutex + lockACMPCAAPIMockDescribeCertificateAuthorityAuditReportRequest sync.RWMutex + lockACMPCAAPIMockDescribeCertificateAuthorityRequest sync.RWMutex + lockACMPCAAPIMockGetCertificateAuthorityCertificateRequest sync.RWMutex + lockACMPCAAPIMockGetCertificateAuthorityCsrRequest sync.RWMutex + lockACMPCAAPIMockGetCertificateRequest sync.RWMutex + lockACMPCAAPIMockImportCertificateAuthorityCertificateRequest sync.RWMutex + lockACMPCAAPIMockIssueCertificateRequest sync.RWMutex + lockACMPCAAPIMockListCertificateAuthoritiesRequest sync.RWMutex + lockACMPCAAPIMockListTagsRequest sync.RWMutex + lockACMPCAAPIMockRestoreCertificateAuthorityRequest sync.RWMutex + lockACMPCAAPIMockRevokeCertificateRequest sync.RWMutex + lockACMPCAAPIMockTagCertificateAuthorityRequest sync.RWMutex + lockACMPCAAPIMockUntagCertificateAuthorityRequest sync.RWMutex + lockACMPCAAPIMockUpdateCertificateAuthorityRequest sync.RWMutex + lockACMPCAAPIMockWaitUntilAuditReportCreated sync.RWMutex + lockACMPCAAPIMockWaitUntilAuditReportCreatedWithContext sync.RWMutex + lockACMPCAAPIMockWaitUntilCertificateAuthorityCSRCreated sync.RWMutex + lockACMPCAAPIMockWaitUntilCertificateAuthorityCSRCreatedWithContext sync.RWMutex + lockACMPCAAPIMockWaitUntilCertificateIssued sync.RWMutex + lockACMPCAAPIMockWaitUntilCertificateIssuedWithContext sync.RWMutex +) + +// ACMPCAAPIMock is a mock implementation of ACMPCAAPI. +// +// func TestSomethingThatUsesACMPCAAPI(t *testing.T) { +// +// // make and configure a mocked ACMPCAAPI +// mockedACMPCAAPI := &ACMPCAAPIMock{ +// CreateCertificateAuthorityAuditReportRequestFunc: func(in1 *acmpca.CreateCertificateAuthorityAuditReportInput) acmpca.CreateCertificateAuthorityAuditReportRequest { +// panic("mock out the CreateCertificateAuthorityAuditReportRequest method") +// }, +// CreateCertificateAuthorityRequestFunc: func(in1 *acmpca.CreateCertificateAuthorityInput) acmpca.CreateCertificateAuthorityRequest { +// panic("mock out the CreateCertificateAuthorityRequest method") +// }, +// DeleteCertificateAuthorityRequestFunc: func(in1 *acmpca.DeleteCertificateAuthorityInput) acmpca.DeleteCertificateAuthorityRequest { +// panic("mock out the DeleteCertificateAuthorityRequest method") +// }, +// DescribeCertificateAuthorityAuditReportRequestFunc: func(in1 *acmpca.DescribeCertificateAuthorityAuditReportInput) acmpca.DescribeCertificateAuthorityAuditReportRequest { +// panic("mock out the DescribeCertificateAuthorityAuditReportRequest method") +// }, +// DescribeCertificateAuthorityRequestFunc: func(in1 *acmpca.DescribeCertificateAuthorityInput) acmpca.DescribeCertificateAuthorityRequest { +// panic("mock out the DescribeCertificateAuthorityRequest method") +// }, +// GetCertificateAuthorityCertificateRequestFunc: func(in1 *acmpca.GetCertificateAuthorityCertificateInput) acmpca.GetCertificateAuthorityCertificateRequest { +// panic("mock out the GetCertificateAuthorityCertificateRequest method") +// }, +// GetCertificateAuthorityCsrRequestFunc: func(in1 *acmpca.GetCertificateAuthorityCsrInput) acmpca.GetCertificateAuthorityCsrRequest { +// panic("mock out the GetCertificateAuthorityCsrRequest method") +// }, +// GetCertificateRequestFunc: func(in1 *acmpca.GetCertificateInput) acmpca.GetCertificateRequest { +// panic("mock out the GetCertificateRequest method") +// }, +// ImportCertificateAuthorityCertificateRequestFunc: func(in1 *acmpca.ImportCertificateAuthorityCertificateInput) acmpca.ImportCertificateAuthorityCertificateRequest { +// panic("mock out the ImportCertificateAuthorityCertificateRequest method") +// }, +// IssueCertificateRequestFunc: func(in1 *acmpca.IssueCertificateInput) acmpca.IssueCertificateRequest { +// panic("mock out the IssueCertificateRequest method") +// }, +// ListCertificateAuthoritiesRequestFunc: func(in1 *acmpca.ListCertificateAuthoritiesInput) acmpca.ListCertificateAuthoritiesRequest { +// panic("mock out the ListCertificateAuthoritiesRequest method") +// }, +// ListTagsRequestFunc: func(in1 *acmpca.ListTagsInput) acmpca.ListTagsRequest { +// panic("mock out the ListTagsRequest method") +// }, +// RestoreCertificateAuthorityRequestFunc: func(in1 *acmpca.RestoreCertificateAuthorityInput) acmpca.RestoreCertificateAuthorityRequest { +// panic("mock out the RestoreCertificateAuthorityRequest method") +// }, +// RevokeCertificateRequestFunc: func(in1 *acmpca.RevokeCertificateInput) acmpca.RevokeCertificateRequest { +// panic("mock out the RevokeCertificateRequest method") +// }, +// TagCertificateAuthorityRequestFunc: func(in1 *acmpca.TagCertificateAuthorityInput) acmpca.TagCertificateAuthorityRequest { +// panic("mock out the TagCertificateAuthorityRequest method") +// }, +// UntagCertificateAuthorityRequestFunc: func(in1 *acmpca.UntagCertificateAuthorityInput) acmpca.UntagCertificateAuthorityRequest { +// panic("mock out the UntagCertificateAuthorityRequest method") +// }, +// UpdateCertificateAuthorityRequestFunc: func(in1 *acmpca.UpdateCertificateAuthorityInput) acmpca.UpdateCertificateAuthorityRequest { +// panic("mock out the UpdateCertificateAuthorityRequest method") +// }, +// WaitUntilAuditReportCreatedFunc: func(in1 *acmpca.DescribeCertificateAuthorityAuditReportInput) error { +// panic("mock out the WaitUntilAuditReportCreated method") +// }, +// WaitUntilAuditReportCreatedWithContextFunc: func(in1 aws.Context, in2 *acmpca.DescribeCertificateAuthorityAuditReportInput, in3 ...aws.WaiterOption) error { +// panic("mock out the WaitUntilAuditReportCreatedWithContext method") +// }, +// WaitUntilCertificateAuthorityCSRCreatedFunc: func(in1 *acmpca.GetCertificateAuthorityCsrInput) error { +// panic("mock out the WaitUntilCertificateAuthorityCSRCreated method") +// }, +// WaitUntilCertificateAuthorityCSRCreatedWithContextFunc: func(in1 aws.Context, in2 *acmpca.GetCertificateAuthorityCsrInput, in3 ...aws.WaiterOption) error { +// panic("mock out the WaitUntilCertificateAuthorityCSRCreatedWithContext method") +// }, +// WaitUntilCertificateIssuedFunc: func(in1 *acmpca.GetCertificateInput) error { +// panic("mock out the WaitUntilCertificateIssued method") +// }, +// WaitUntilCertificateIssuedWithContextFunc: func(in1 aws.Context, in2 *acmpca.GetCertificateInput, in3 ...aws.WaiterOption) error { +// panic("mock out the WaitUntilCertificateIssuedWithContext method") +// }, +// } +// +// // use mockedACMPCAAPI in code that requires ACMPCAAPI +// // and then make assertions. +// +// } +type ACMPCAAPIMock struct { + // CreateCertificateAuthorityAuditReportRequestFunc mocks the CreateCertificateAuthorityAuditReportRequest method. + CreateCertificateAuthorityAuditReportRequestFunc func(in1 *acmpca.CreateCertificateAuthorityAuditReportInput) acmpca.CreateCertificateAuthorityAuditReportRequest + + // CreateCertificateAuthorityRequestFunc mocks the CreateCertificateAuthorityRequest method. + CreateCertificateAuthorityRequestFunc func(in1 *acmpca.CreateCertificateAuthorityInput) acmpca.CreateCertificateAuthorityRequest + + // DeleteCertificateAuthorityRequestFunc mocks the DeleteCertificateAuthorityRequest method. + DeleteCertificateAuthorityRequestFunc func(in1 *acmpca.DeleteCertificateAuthorityInput) acmpca.DeleteCertificateAuthorityRequest + + // DescribeCertificateAuthorityAuditReportRequestFunc mocks the DescribeCertificateAuthorityAuditReportRequest method. + DescribeCertificateAuthorityAuditReportRequestFunc func(in1 *acmpca.DescribeCertificateAuthorityAuditReportInput) acmpca.DescribeCertificateAuthorityAuditReportRequest + + // DescribeCertificateAuthorityRequestFunc mocks the DescribeCertificateAuthorityRequest method. + DescribeCertificateAuthorityRequestFunc func(in1 *acmpca.DescribeCertificateAuthorityInput) acmpca.DescribeCertificateAuthorityRequest + + // GetCertificateAuthorityCertificateRequestFunc mocks the GetCertificateAuthorityCertificateRequest method. + GetCertificateAuthorityCertificateRequestFunc func(in1 *acmpca.GetCertificateAuthorityCertificateInput) acmpca.GetCertificateAuthorityCertificateRequest + + // GetCertificateAuthorityCsrRequestFunc mocks the GetCertificateAuthorityCsrRequest method. + GetCertificateAuthorityCsrRequestFunc func(in1 *acmpca.GetCertificateAuthorityCsrInput) acmpca.GetCertificateAuthorityCsrRequest + + // GetCertificateRequestFunc mocks the GetCertificateRequest method. + GetCertificateRequestFunc func(in1 *acmpca.GetCertificateInput) acmpca.GetCertificateRequest + + // ImportCertificateAuthorityCertificateRequestFunc mocks the ImportCertificateAuthorityCertificateRequest method. + ImportCertificateAuthorityCertificateRequestFunc func(in1 *acmpca.ImportCertificateAuthorityCertificateInput) acmpca.ImportCertificateAuthorityCertificateRequest + + // IssueCertificateRequestFunc mocks the IssueCertificateRequest method. + IssueCertificateRequestFunc func(in1 *acmpca.IssueCertificateInput) acmpca.IssueCertificateRequest + + // ListCertificateAuthoritiesRequestFunc mocks the ListCertificateAuthoritiesRequest method. + ListCertificateAuthoritiesRequestFunc func(in1 *acmpca.ListCertificateAuthoritiesInput) acmpca.ListCertificateAuthoritiesRequest + + // ListTagsRequestFunc mocks the ListTagsRequest method. + ListTagsRequestFunc func(in1 *acmpca.ListTagsInput) acmpca.ListTagsRequest + + // RestoreCertificateAuthorityRequestFunc mocks the RestoreCertificateAuthorityRequest method. + RestoreCertificateAuthorityRequestFunc func(in1 *acmpca.RestoreCertificateAuthorityInput) acmpca.RestoreCertificateAuthorityRequest + + // RevokeCertificateRequestFunc mocks the RevokeCertificateRequest method. + RevokeCertificateRequestFunc func(in1 *acmpca.RevokeCertificateInput) acmpca.RevokeCertificateRequest + + // TagCertificateAuthorityRequestFunc mocks the TagCertificateAuthorityRequest method. + TagCertificateAuthorityRequestFunc func(in1 *acmpca.TagCertificateAuthorityInput) acmpca.TagCertificateAuthorityRequest + + // UntagCertificateAuthorityRequestFunc mocks the UntagCertificateAuthorityRequest method. + UntagCertificateAuthorityRequestFunc func(in1 *acmpca.UntagCertificateAuthorityInput) acmpca.UntagCertificateAuthorityRequest + + // UpdateCertificateAuthorityRequestFunc mocks the UpdateCertificateAuthorityRequest method. + UpdateCertificateAuthorityRequestFunc func(in1 *acmpca.UpdateCertificateAuthorityInput) acmpca.UpdateCertificateAuthorityRequest + + // WaitUntilAuditReportCreatedFunc mocks the WaitUntilAuditReportCreated method. + WaitUntilAuditReportCreatedFunc func(in1 *acmpca.DescribeCertificateAuthorityAuditReportInput) error + + // WaitUntilAuditReportCreatedWithContextFunc mocks the WaitUntilAuditReportCreatedWithContext method. + WaitUntilAuditReportCreatedWithContextFunc func(in1 aws.Context, in2 *acmpca.DescribeCertificateAuthorityAuditReportInput, in3 ...aws.WaiterOption) error + + // WaitUntilCertificateAuthorityCSRCreatedFunc mocks the WaitUntilCertificateAuthorityCSRCreated method. + WaitUntilCertificateAuthorityCSRCreatedFunc func(in1 *acmpca.GetCertificateAuthorityCsrInput) error + + // WaitUntilCertificateAuthorityCSRCreatedWithContextFunc mocks the WaitUntilCertificateAuthorityCSRCreatedWithContext method. + WaitUntilCertificateAuthorityCSRCreatedWithContextFunc func(in1 aws.Context, in2 *acmpca.GetCertificateAuthorityCsrInput, in3 ...aws.WaiterOption) error + + // WaitUntilCertificateIssuedFunc mocks the WaitUntilCertificateIssued method. + WaitUntilCertificateIssuedFunc func(in1 *acmpca.GetCertificateInput) error + + // WaitUntilCertificateIssuedWithContextFunc mocks the WaitUntilCertificateIssuedWithContext method. + WaitUntilCertificateIssuedWithContextFunc func(in1 aws.Context, in2 *acmpca.GetCertificateInput, in3 ...aws.WaiterOption) error + + // calls tracks calls to the methods. + calls struct { + // CreateCertificateAuthorityAuditReportRequest holds details about calls to the CreateCertificateAuthorityAuditReportRequest method. + CreateCertificateAuthorityAuditReportRequest []struct { + // In1 is the in1 argument value. + In1 *acmpca.CreateCertificateAuthorityAuditReportInput + } + // CreateCertificateAuthorityRequest holds details about calls to the CreateCertificateAuthorityRequest method. + CreateCertificateAuthorityRequest []struct { + // In1 is the in1 argument value. + In1 *acmpca.CreateCertificateAuthorityInput + } + // DeleteCertificateAuthorityRequest holds details about calls to the DeleteCertificateAuthorityRequest method. + DeleteCertificateAuthorityRequest []struct { + // In1 is the in1 argument value. + In1 *acmpca.DeleteCertificateAuthorityInput + } + // DescribeCertificateAuthorityAuditReportRequest holds details about calls to the DescribeCertificateAuthorityAuditReportRequest method. + DescribeCertificateAuthorityAuditReportRequest []struct { + // In1 is the in1 argument value. + In1 *acmpca.DescribeCertificateAuthorityAuditReportInput + } + // DescribeCertificateAuthorityRequest holds details about calls to the DescribeCertificateAuthorityRequest method. + DescribeCertificateAuthorityRequest []struct { + // In1 is the in1 argument value. + In1 *acmpca.DescribeCertificateAuthorityInput + } + // GetCertificateAuthorityCertificateRequest holds details about calls to the GetCertificateAuthorityCertificateRequest method. + GetCertificateAuthorityCertificateRequest []struct { + // In1 is the in1 argument value. + In1 *acmpca.GetCertificateAuthorityCertificateInput + } + // GetCertificateAuthorityCsrRequest holds details about calls to the GetCertificateAuthorityCsrRequest method. + GetCertificateAuthorityCsrRequest []struct { + // In1 is the in1 argument value. + In1 *acmpca.GetCertificateAuthorityCsrInput + } + // GetCertificateRequest holds details about calls to the GetCertificateRequest method. + GetCertificateRequest []struct { + // In1 is the in1 argument value. + In1 *acmpca.GetCertificateInput + } + // ImportCertificateAuthorityCertificateRequest holds details about calls to the ImportCertificateAuthorityCertificateRequest method. + ImportCertificateAuthorityCertificateRequest []struct { + // In1 is the in1 argument value. + In1 *acmpca.ImportCertificateAuthorityCertificateInput + } + // IssueCertificateRequest holds details about calls to the IssueCertificateRequest method. + IssueCertificateRequest []struct { + // In1 is the in1 argument value. + In1 *acmpca.IssueCertificateInput + } + // ListCertificateAuthoritiesRequest holds details about calls to the ListCertificateAuthoritiesRequest method. + ListCertificateAuthoritiesRequest []struct { + // In1 is the in1 argument value. + In1 *acmpca.ListCertificateAuthoritiesInput + } + // ListTagsRequest holds details about calls to the ListTagsRequest method. + ListTagsRequest []struct { + // In1 is the in1 argument value. + In1 *acmpca.ListTagsInput + } + // RestoreCertificateAuthorityRequest holds details about calls to the RestoreCertificateAuthorityRequest method. + RestoreCertificateAuthorityRequest []struct { + // In1 is the in1 argument value. + In1 *acmpca.RestoreCertificateAuthorityInput + } + // RevokeCertificateRequest holds details about calls to the RevokeCertificateRequest method. + RevokeCertificateRequest []struct { + // In1 is the in1 argument value. + In1 *acmpca.RevokeCertificateInput + } + // TagCertificateAuthorityRequest holds details about calls to the TagCertificateAuthorityRequest method. + TagCertificateAuthorityRequest []struct { + // In1 is the in1 argument value. + In1 *acmpca.TagCertificateAuthorityInput + } + // UntagCertificateAuthorityRequest holds details about calls to the UntagCertificateAuthorityRequest method. + UntagCertificateAuthorityRequest []struct { + // In1 is the in1 argument value. + In1 *acmpca.UntagCertificateAuthorityInput + } + // UpdateCertificateAuthorityRequest holds details about calls to the UpdateCertificateAuthorityRequest method. + UpdateCertificateAuthorityRequest []struct { + // In1 is the in1 argument value. + In1 *acmpca.UpdateCertificateAuthorityInput + } + // WaitUntilAuditReportCreated holds details about calls to the WaitUntilAuditReportCreated method. + WaitUntilAuditReportCreated []struct { + // In1 is the in1 argument value. + In1 *acmpca.DescribeCertificateAuthorityAuditReportInput + } + // WaitUntilAuditReportCreatedWithContext holds details about calls to the WaitUntilAuditReportCreatedWithContext method. + WaitUntilAuditReportCreatedWithContext []struct { + // In1 is the in1 argument value. + In1 aws.Context + // In2 is the in2 argument value. + In2 *acmpca.DescribeCertificateAuthorityAuditReportInput + // In3 is the in3 argument value. + In3 []aws.WaiterOption + } + // WaitUntilCertificateAuthorityCSRCreated holds details about calls to the WaitUntilCertificateAuthorityCSRCreated method. + WaitUntilCertificateAuthorityCSRCreated []struct { + // In1 is the in1 argument value. + In1 *acmpca.GetCertificateAuthorityCsrInput + } + // WaitUntilCertificateAuthorityCSRCreatedWithContext holds details about calls to the WaitUntilCertificateAuthorityCSRCreatedWithContext method. + WaitUntilCertificateAuthorityCSRCreatedWithContext []struct { + // In1 is the in1 argument value. + In1 aws.Context + // In2 is the in2 argument value. + In2 *acmpca.GetCertificateAuthorityCsrInput + // In3 is the in3 argument value. + In3 []aws.WaiterOption + } + // WaitUntilCertificateIssued holds details about calls to the WaitUntilCertificateIssued method. + WaitUntilCertificateIssued []struct { + // In1 is the in1 argument value. + In1 *acmpca.GetCertificateInput + } + // WaitUntilCertificateIssuedWithContext holds details about calls to the WaitUntilCertificateIssuedWithContext method. + WaitUntilCertificateIssuedWithContext []struct { + // In1 is the in1 argument value. + In1 aws.Context + // In2 is the in2 argument value. + In2 *acmpca.GetCertificateInput + // In3 is the in3 argument value. + In3 []aws.WaiterOption + } + } +} + +// CreateCertificateAuthorityAuditReportRequest calls CreateCertificateAuthorityAuditReportRequestFunc. +func (mock *ACMPCAAPIMock) CreateCertificateAuthorityAuditReportRequest(in1 *acmpca.CreateCertificateAuthorityAuditReportInput) acmpca.CreateCertificateAuthorityAuditReportRequest { + if mock.CreateCertificateAuthorityAuditReportRequestFunc == nil { + panic("ACMPCAAPIMock.CreateCertificateAuthorityAuditReportRequestFunc: method is nil but ACMPCAAPI.CreateCertificateAuthorityAuditReportRequest was just called") + } + callInfo := struct { + In1 *acmpca.CreateCertificateAuthorityAuditReportInput + }{ + In1: in1, + } + lockACMPCAAPIMockCreateCertificateAuthorityAuditReportRequest.Lock() + mock.calls.CreateCertificateAuthorityAuditReportRequest = append(mock.calls.CreateCertificateAuthorityAuditReportRequest, callInfo) + lockACMPCAAPIMockCreateCertificateAuthorityAuditReportRequest.Unlock() + return mock.CreateCertificateAuthorityAuditReportRequestFunc(in1) +} + +// CreateCertificateAuthorityAuditReportRequestCalls gets all the calls that were made to CreateCertificateAuthorityAuditReportRequest. +// Check the length with: +// len(mockedACMPCAAPI.CreateCertificateAuthorityAuditReportRequestCalls()) +func (mock *ACMPCAAPIMock) CreateCertificateAuthorityAuditReportRequestCalls() []struct { + In1 *acmpca.CreateCertificateAuthorityAuditReportInput +} { + var calls []struct { + In1 *acmpca.CreateCertificateAuthorityAuditReportInput + } + lockACMPCAAPIMockCreateCertificateAuthorityAuditReportRequest.RLock() + calls = mock.calls.CreateCertificateAuthorityAuditReportRequest + lockACMPCAAPIMockCreateCertificateAuthorityAuditReportRequest.RUnlock() + return calls +} + +// CreateCertificateAuthorityRequest calls CreateCertificateAuthorityRequestFunc. +func (mock *ACMPCAAPIMock) CreateCertificateAuthorityRequest(in1 *acmpca.CreateCertificateAuthorityInput) acmpca.CreateCertificateAuthorityRequest { + if mock.CreateCertificateAuthorityRequestFunc == nil { + panic("ACMPCAAPIMock.CreateCertificateAuthorityRequestFunc: method is nil but ACMPCAAPI.CreateCertificateAuthorityRequest was just called") + } + callInfo := struct { + In1 *acmpca.CreateCertificateAuthorityInput + }{ + In1: in1, + } + lockACMPCAAPIMockCreateCertificateAuthorityRequest.Lock() + mock.calls.CreateCertificateAuthorityRequest = append(mock.calls.CreateCertificateAuthorityRequest, callInfo) + lockACMPCAAPIMockCreateCertificateAuthorityRequest.Unlock() + return mock.CreateCertificateAuthorityRequestFunc(in1) +} + +// CreateCertificateAuthorityRequestCalls gets all the calls that were made to CreateCertificateAuthorityRequest. +// Check the length with: +// len(mockedACMPCAAPI.CreateCertificateAuthorityRequestCalls()) +func (mock *ACMPCAAPIMock) CreateCertificateAuthorityRequestCalls() []struct { + In1 *acmpca.CreateCertificateAuthorityInput +} { + var calls []struct { + In1 *acmpca.CreateCertificateAuthorityInput + } + lockACMPCAAPIMockCreateCertificateAuthorityRequest.RLock() + calls = mock.calls.CreateCertificateAuthorityRequest + lockACMPCAAPIMockCreateCertificateAuthorityRequest.RUnlock() + return calls +} + +// DeleteCertificateAuthorityRequest calls DeleteCertificateAuthorityRequestFunc. +func (mock *ACMPCAAPIMock) DeleteCertificateAuthorityRequest(in1 *acmpca.DeleteCertificateAuthorityInput) acmpca.DeleteCertificateAuthorityRequest { + if mock.DeleteCertificateAuthorityRequestFunc == nil { + panic("ACMPCAAPIMock.DeleteCertificateAuthorityRequestFunc: method is nil but ACMPCAAPI.DeleteCertificateAuthorityRequest was just called") + } + callInfo := struct { + In1 *acmpca.DeleteCertificateAuthorityInput + }{ + In1: in1, + } + lockACMPCAAPIMockDeleteCertificateAuthorityRequest.Lock() + mock.calls.DeleteCertificateAuthorityRequest = append(mock.calls.DeleteCertificateAuthorityRequest, callInfo) + lockACMPCAAPIMockDeleteCertificateAuthorityRequest.Unlock() + return mock.DeleteCertificateAuthorityRequestFunc(in1) +} + +// DeleteCertificateAuthorityRequestCalls gets all the calls that were made to DeleteCertificateAuthorityRequest. +// Check the length with: +// len(mockedACMPCAAPI.DeleteCertificateAuthorityRequestCalls()) +func (mock *ACMPCAAPIMock) DeleteCertificateAuthorityRequestCalls() []struct { + In1 *acmpca.DeleteCertificateAuthorityInput +} { + var calls []struct { + In1 *acmpca.DeleteCertificateAuthorityInput + } + lockACMPCAAPIMockDeleteCertificateAuthorityRequest.RLock() + calls = mock.calls.DeleteCertificateAuthorityRequest + lockACMPCAAPIMockDeleteCertificateAuthorityRequest.RUnlock() + return calls +} + +// DescribeCertificateAuthorityAuditReportRequest calls DescribeCertificateAuthorityAuditReportRequestFunc. +func (mock *ACMPCAAPIMock) DescribeCertificateAuthorityAuditReportRequest(in1 *acmpca.DescribeCertificateAuthorityAuditReportInput) acmpca.DescribeCertificateAuthorityAuditReportRequest { + if mock.DescribeCertificateAuthorityAuditReportRequestFunc == nil { + panic("ACMPCAAPIMock.DescribeCertificateAuthorityAuditReportRequestFunc: method is nil but ACMPCAAPI.DescribeCertificateAuthorityAuditReportRequest was just called") + } + callInfo := struct { + In1 *acmpca.DescribeCertificateAuthorityAuditReportInput + }{ + In1: in1, + } + lockACMPCAAPIMockDescribeCertificateAuthorityAuditReportRequest.Lock() + mock.calls.DescribeCertificateAuthorityAuditReportRequest = append(mock.calls.DescribeCertificateAuthorityAuditReportRequest, callInfo) + lockACMPCAAPIMockDescribeCertificateAuthorityAuditReportRequest.Unlock() + return mock.DescribeCertificateAuthorityAuditReportRequestFunc(in1) +} + +// DescribeCertificateAuthorityAuditReportRequestCalls gets all the calls that were made to DescribeCertificateAuthorityAuditReportRequest. +// Check the length with: +// len(mockedACMPCAAPI.DescribeCertificateAuthorityAuditReportRequestCalls()) +func (mock *ACMPCAAPIMock) DescribeCertificateAuthorityAuditReportRequestCalls() []struct { + In1 *acmpca.DescribeCertificateAuthorityAuditReportInput +} { + var calls []struct { + In1 *acmpca.DescribeCertificateAuthorityAuditReportInput + } + lockACMPCAAPIMockDescribeCertificateAuthorityAuditReportRequest.RLock() + calls = mock.calls.DescribeCertificateAuthorityAuditReportRequest + lockACMPCAAPIMockDescribeCertificateAuthorityAuditReportRequest.RUnlock() + return calls +} + +// DescribeCertificateAuthorityRequest calls DescribeCertificateAuthorityRequestFunc. +func (mock *ACMPCAAPIMock) DescribeCertificateAuthorityRequest(in1 *acmpca.DescribeCertificateAuthorityInput) acmpca.DescribeCertificateAuthorityRequest { + if mock.DescribeCertificateAuthorityRequestFunc == nil { + panic("ACMPCAAPIMock.DescribeCertificateAuthorityRequestFunc: method is nil but ACMPCAAPI.DescribeCertificateAuthorityRequest was just called") + } + callInfo := struct { + In1 *acmpca.DescribeCertificateAuthorityInput + }{ + In1: in1, + } + lockACMPCAAPIMockDescribeCertificateAuthorityRequest.Lock() + mock.calls.DescribeCertificateAuthorityRequest = append(mock.calls.DescribeCertificateAuthorityRequest, callInfo) + lockACMPCAAPIMockDescribeCertificateAuthorityRequest.Unlock() + return mock.DescribeCertificateAuthorityRequestFunc(in1) +} + +// DescribeCertificateAuthorityRequestCalls gets all the calls that were made to DescribeCertificateAuthorityRequest. +// Check the length with: +// len(mockedACMPCAAPI.DescribeCertificateAuthorityRequestCalls()) +func (mock *ACMPCAAPIMock) DescribeCertificateAuthorityRequestCalls() []struct { + In1 *acmpca.DescribeCertificateAuthorityInput +} { + var calls []struct { + In1 *acmpca.DescribeCertificateAuthorityInput + } + lockACMPCAAPIMockDescribeCertificateAuthorityRequest.RLock() + calls = mock.calls.DescribeCertificateAuthorityRequest + lockACMPCAAPIMockDescribeCertificateAuthorityRequest.RUnlock() + return calls +} + +// GetCertificateAuthorityCertificateRequest calls GetCertificateAuthorityCertificateRequestFunc. +func (mock *ACMPCAAPIMock) GetCertificateAuthorityCertificateRequest(in1 *acmpca.GetCertificateAuthorityCertificateInput) acmpca.GetCertificateAuthorityCertificateRequest { + if mock.GetCertificateAuthorityCertificateRequestFunc == nil { + panic("ACMPCAAPIMock.GetCertificateAuthorityCertificateRequestFunc: method is nil but ACMPCAAPI.GetCertificateAuthorityCertificateRequest was just called") + } + callInfo := struct { + In1 *acmpca.GetCertificateAuthorityCertificateInput + }{ + In1: in1, + } + lockACMPCAAPIMockGetCertificateAuthorityCertificateRequest.Lock() + mock.calls.GetCertificateAuthorityCertificateRequest = append(mock.calls.GetCertificateAuthorityCertificateRequest, callInfo) + lockACMPCAAPIMockGetCertificateAuthorityCertificateRequest.Unlock() + return mock.GetCertificateAuthorityCertificateRequestFunc(in1) +} + +// GetCertificateAuthorityCertificateRequestCalls gets all the calls that were made to GetCertificateAuthorityCertificateRequest. +// Check the length with: +// len(mockedACMPCAAPI.GetCertificateAuthorityCertificateRequestCalls()) +func (mock *ACMPCAAPIMock) GetCertificateAuthorityCertificateRequestCalls() []struct { + In1 *acmpca.GetCertificateAuthorityCertificateInput +} { + var calls []struct { + In1 *acmpca.GetCertificateAuthorityCertificateInput + } + lockACMPCAAPIMockGetCertificateAuthorityCertificateRequest.RLock() + calls = mock.calls.GetCertificateAuthorityCertificateRequest + lockACMPCAAPIMockGetCertificateAuthorityCertificateRequest.RUnlock() + return calls +} + +// GetCertificateAuthorityCsrRequest calls GetCertificateAuthorityCsrRequestFunc. +func (mock *ACMPCAAPIMock) GetCertificateAuthorityCsrRequest(in1 *acmpca.GetCertificateAuthorityCsrInput) acmpca.GetCertificateAuthorityCsrRequest { + if mock.GetCertificateAuthorityCsrRequestFunc == nil { + panic("ACMPCAAPIMock.GetCertificateAuthorityCsrRequestFunc: method is nil but ACMPCAAPI.GetCertificateAuthorityCsrRequest was just called") + } + callInfo := struct { + In1 *acmpca.GetCertificateAuthorityCsrInput + }{ + In1: in1, + } + lockACMPCAAPIMockGetCertificateAuthorityCsrRequest.Lock() + mock.calls.GetCertificateAuthorityCsrRequest = append(mock.calls.GetCertificateAuthorityCsrRequest, callInfo) + lockACMPCAAPIMockGetCertificateAuthorityCsrRequest.Unlock() + return mock.GetCertificateAuthorityCsrRequestFunc(in1) +} + +// GetCertificateAuthorityCsrRequestCalls gets all the calls that were made to GetCertificateAuthorityCsrRequest. +// Check the length with: +// len(mockedACMPCAAPI.GetCertificateAuthorityCsrRequestCalls()) +func (mock *ACMPCAAPIMock) GetCertificateAuthorityCsrRequestCalls() []struct { + In1 *acmpca.GetCertificateAuthorityCsrInput +} { + var calls []struct { + In1 *acmpca.GetCertificateAuthorityCsrInput + } + lockACMPCAAPIMockGetCertificateAuthorityCsrRequest.RLock() + calls = mock.calls.GetCertificateAuthorityCsrRequest + lockACMPCAAPIMockGetCertificateAuthorityCsrRequest.RUnlock() + return calls +} + +// GetCertificateRequest calls GetCertificateRequestFunc. +func (mock *ACMPCAAPIMock) GetCertificateRequest(in1 *acmpca.GetCertificateInput) acmpca.GetCertificateRequest { + if mock.GetCertificateRequestFunc == nil { + panic("ACMPCAAPIMock.GetCertificateRequestFunc: method is nil but ACMPCAAPI.GetCertificateRequest was just called") + } + callInfo := struct { + In1 *acmpca.GetCertificateInput + }{ + In1: in1, + } + lockACMPCAAPIMockGetCertificateRequest.Lock() + mock.calls.GetCertificateRequest = append(mock.calls.GetCertificateRequest, callInfo) + lockACMPCAAPIMockGetCertificateRequest.Unlock() + return mock.GetCertificateRequestFunc(in1) +} + +// GetCertificateRequestCalls gets all the calls that were made to GetCertificateRequest. +// Check the length with: +// len(mockedACMPCAAPI.GetCertificateRequestCalls()) +func (mock *ACMPCAAPIMock) GetCertificateRequestCalls() []struct { + In1 *acmpca.GetCertificateInput +} { + var calls []struct { + In1 *acmpca.GetCertificateInput + } + lockACMPCAAPIMockGetCertificateRequest.RLock() + calls = mock.calls.GetCertificateRequest + lockACMPCAAPIMockGetCertificateRequest.RUnlock() + return calls +} + +// ImportCertificateAuthorityCertificateRequest calls ImportCertificateAuthorityCertificateRequestFunc. +func (mock *ACMPCAAPIMock) ImportCertificateAuthorityCertificateRequest(in1 *acmpca.ImportCertificateAuthorityCertificateInput) acmpca.ImportCertificateAuthorityCertificateRequest { + if mock.ImportCertificateAuthorityCertificateRequestFunc == nil { + panic("ACMPCAAPIMock.ImportCertificateAuthorityCertificateRequestFunc: method is nil but ACMPCAAPI.ImportCertificateAuthorityCertificateRequest was just called") + } + callInfo := struct { + In1 *acmpca.ImportCertificateAuthorityCertificateInput + }{ + In1: in1, + } + lockACMPCAAPIMockImportCertificateAuthorityCertificateRequest.Lock() + mock.calls.ImportCertificateAuthorityCertificateRequest = append(mock.calls.ImportCertificateAuthorityCertificateRequest, callInfo) + lockACMPCAAPIMockImportCertificateAuthorityCertificateRequest.Unlock() + return mock.ImportCertificateAuthorityCertificateRequestFunc(in1) +} + +// ImportCertificateAuthorityCertificateRequestCalls gets all the calls that were made to ImportCertificateAuthorityCertificateRequest. +// Check the length with: +// len(mockedACMPCAAPI.ImportCertificateAuthorityCertificateRequestCalls()) +func (mock *ACMPCAAPIMock) ImportCertificateAuthorityCertificateRequestCalls() []struct { + In1 *acmpca.ImportCertificateAuthorityCertificateInput +} { + var calls []struct { + In1 *acmpca.ImportCertificateAuthorityCertificateInput + } + lockACMPCAAPIMockImportCertificateAuthorityCertificateRequest.RLock() + calls = mock.calls.ImportCertificateAuthorityCertificateRequest + lockACMPCAAPIMockImportCertificateAuthorityCertificateRequest.RUnlock() + return calls +} + +// IssueCertificateRequest calls IssueCertificateRequestFunc. +func (mock *ACMPCAAPIMock) IssueCertificateRequest(in1 *acmpca.IssueCertificateInput) acmpca.IssueCertificateRequest { + if mock.IssueCertificateRequestFunc == nil { + panic("ACMPCAAPIMock.IssueCertificateRequestFunc: method is nil but ACMPCAAPI.IssueCertificateRequest was just called") + } + callInfo := struct { + In1 *acmpca.IssueCertificateInput + }{ + In1: in1, + } + lockACMPCAAPIMockIssueCertificateRequest.Lock() + mock.calls.IssueCertificateRequest = append(mock.calls.IssueCertificateRequest, callInfo) + lockACMPCAAPIMockIssueCertificateRequest.Unlock() + return mock.IssueCertificateRequestFunc(in1) +} + +// IssueCertificateRequestCalls gets all the calls that were made to IssueCertificateRequest. +// Check the length with: +// len(mockedACMPCAAPI.IssueCertificateRequestCalls()) +func (mock *ACMPCAAPIMock) IssueCertificateRequestCalls() []struct { + In1 *acmpca.IssueCertificateInput +} { + var calls []struct { + In1 *acmpca.IssueCertificateInput + } + lockACMPCAAPIMockIssueCertificateRequest.RLock() + calls = mock.calls.IssueCertificateRequest + lockACMPCAAPIMockIssueCertificateRequest.RUnlock() + return calls +} + +// ListCertificateAuthoritiesRequest calls ListCertificateAuthoritiesRequestFunc. +func (mock *ACMPCAAPIMock) ListCertificateAuthoritiesRequest(in1 *acmpca.ListCertificateAuthoritiesInput) acmpca.ListCertificateAuthoritiesRequest { + if mock.ListCertificateAuthoritiesRequestFunc == nil { + panic("ACMPCAAPIMock.ListCertificateAuthoritiesRequestFunc: method is nil but ACMPCAAPI.ListCertificateAuthoritiesRequest was just called") + } + callInfo := struct { + In1 *acmpca.ListCertificateAuthoritiesInput + }{ + In1: in1, + } + lockACMPCAAPIMockListCertificateAuthoritiesRequest.Lock() + mock.calls.ListCertificateAuthoritiesRequest = append(mock.calls.ListCertificateAuthoritiesRequest, callInfo) + lockACMPCAAPIMockListCertificateAuthoritiesRequest.Unlock() + return mock.ListCertificateAuthoritiesRequestFunc(in1) +} + +// ListCertificateAuthoritiesRequestCalls gets all the calls that were made to ListCertificateAuthoritiesRequest. +// Check the length with: +// len(mockedACMPCAAPI.ListCertificateAuthoritiesRequestCalls()) +func (mock *ACMPCAAPIMock) ListCertificateAuthoritiesRequestCalls() []struct { + In1 *acmpca.ListCertificateAuthoritiesInput +} { + var calls []struct { + In1 *acmpca.ListCertificateAuthoritiesInput + } + lockACMPCAAPIMockListCertificateAuthoritiesRequest.RLock() + calls = mock.calls.ListCertificateAuthoritiesRequest + lockACMPCAAPIMockListCertificateAuthoritiesRequest.RUnlock() + return calls +} + +// ListTagsRequest calls ListTagsRequestFunc. +func (mock *ACMPCAAPIMock) ListTagsRequest(in1 *acmpca.ListTagsInput) acmpca.ListTagsRequest { + if mock.ListTagsRequestFunc == nil { + panic("ACMPCAAPIMock.ListTagsRequestFunc: method is nil but ACMPCAAPI.ListTagsRequest was just called") + } + callInfo := struct { + In1 *acmpca.ListTagsInput + }{ + In1: in1, + } + lockACMPCAAPIMockListTagsRequest.Lock() + mock.calls.ListTagsRequest = append(mock.calls.ListTagsRequest, callInfo) + lockACMPCAAPIMockListTagsRequest.Unlock() + return mock.ListTagsRequestFunc(in1) +} + +// ListTagsRequestCalls gets all the calls that were made to ListTagsRequest. +// Check the length with: +// len(mockedACMPCAAPI.ListTagsRequestCalls()) +func (mock *ACMPCAAPIMock) ListTagsRequestCalls() []struct { + In1 *acmpca.ListTagsInput +} { + var calls []struct { + In1 *acmpca.ListTagsInput + } + lockACMPCAAPIMockListTagsRequest.RLock() + calls = mock.calls.ListTagsRequest + lockACMPCAAPIMockListTagsRequest.RUnlock() + return calls +} + +// RestoreCertificateAuthorityRequest calls RestoreCertificateAuthorityRequestFunc. +func (mock *ACMPCAAPIMock) RestoreCertificateAuthorityRequest(in1 *acmpca.RestoreCertificateAuthorityInput) acmpca.RestoreCertificateAuthorityRequest { + if mock.RestoreCertificateAuthorityRequestFunc == nil { + panic("ACMPCAAPIMock.RestoreCertificateAuthorityRequestFunc: method is nil but ACMPCAAPI.RestoreCertificateAuthorityRequest was just called") + } + callInfo := struct { + In1 *acmpca.RestoreCertificateAuthorityInput + }{ + In1: in1, + } + lockACMPCAAPIMockRestoreCertificateAuthorityRequest.Lock() + mock.calls.RestoreCertificateAuthorityRequest = append(mock.calls.RestoreCertificateAuthorityRequest, callInfo) + lockACMPCAAPIMockRestoreCertificateAuthorityRequest.Unlock() + return mock.RestoreCertificateAuthorityRequestFunc(in1) +} + +// RestoreCertificateAuthorityRequestCalls gets all the calls that were made to RestoreCertificateAuthorityRequest. +// Check the length with: +// len(mockedACMPCAAPI.RestoreCertificateAuthorityRequestCalls()) +func (mock *ACMPCAAPIMock) RestoreCertificateAuthorityRequestCalls() []struct { + In1 *acmpca.RestoreCertificateAuthorityInput +} { + var calls []struct { + In1 *acmpca.RestoreCertificateAuthorityInput + } + lockACMPCAAPIMockRestoreCertificateAuthorityRequest.RLock() + calls = mock.calls.RestoreCertificateAuthorityRequest + lockACMPCAAPIMockRestoreCertificateAuthorityRequest.RUnlock() + return calls +} + +// RevokeCertificateRequest calls RevokeCertificateRequestFunc. +func (mock *ACMPCAAPIMock) RevokeCertificateRequest(in1 *acmpca.RevokeCertificateInput) acmpca.RevokeCertificateRequest { + if mock.RevokeCertificateRequestFunc == nil { + panic("ACMPCAAPIMock.RevokeCertificateRequestFunc: method is nil but ACMPCAAPI.RevokeCertificateRequest was just called") + } + callInfo := struct { + In1 *acmpca.RevokeCertificateInput + }{ + In1: in1, + } + lockACMPCAAPIMockRevokeCertificateRequest.Lock() + mock.calls.RevokeCertificateRequest = append(mock.calls.RevokeCertificateRequest, callInfo) + lockACMPCAAPIMockRevokeCertificateRequest.Unlock() + return mock.RevokeCertificateRequestFunc(in1) +} + +// RevokeCertificateRequestCalls gets all the calls that were made to RevokeCertificateRequest. +// Check the length with: +// len(mockedACMPCAAPI.RevokeCertificateRequestCalls()) +func (mock *ACMPCAAPIMock) RevokeCertificateRequestCalls() []struct { + In1 *acmpca.RevokeCertificateInput +} { + var calls []struct { + In1 *acmpca.RevokeCertificateInput + } + lockACMPCAAPIMockRevokeCertificateRequest.RLock() + calls = mock.calls.RevokeCertificateRequest + lockACMPCAAPIMockRevokeCertificateRequest.RUnlock() + return calls +} + +// TagCertificateAuthorityRequest calls TagCertificateAuthorityRequestFunc. +func (mock *ACMPCAAPIMock) TagCertificateAuthorityRequest(in1 *acmpca.TagCertificateAuthorityInput) acmpca.TagCertificateAuthorityRequest { + if mock.TagCertificateAuthorityRequestFunc == nil { + panic("ACMPCAAPIMock.TagCertificateAuthorityRequestFunc: method is nil but ACMPCAAPI.TagCertificateAuthorityRequest was just called") + } + callInfo := struct { + In1 *acmpca.TagCertificateAuthorityInput + }{ + In1: in1, + } + lockACMPCAAPIMockTagCertificateAuthorityRequest.Lock() + mock.calls.TagCertificateAuthorityRequest = append(mock.calls.TagCertificateAuthorityRequest, callInfo) + lockACMPCAAPIMockTagCertificateAuthorityRequest.Unlock() + return mock.TagCertificateAuthorityRequestFunc(in1) +} + +// TagCertificateAuthorityRequestCalls gets all the calls that were made to TagCertificateAuthorityRequest. +// Check the length with: +// len(mockedACMPCAAPI.TagCertificateAuthorityRequestCalls()) +func (mock *ACMPCAAPIMock) TagCertificateAuthorityRequestCalls() []struct { + In1 *acmpca.TagCertificateAuthorityInput +} { + var calls []struct { + In1 *acmpca.TagCertificateAuthorityInput + } + lockACMPCAAPIMockTagCertificateAuthorityRequest.RLock() + calls = mock.calls.TagCertificateAuthorityRequest + lockACMPCAAPIMockTagCertificateAuthorityRequest.RUnlock() + return calls +} + +// UntagCertificateAuthorityRequest calls UntagCertificateAuthorityRequestFunc. +func (mock *ACMPCAAPIMock) UntagCertificateAuthorityRequest(in1 *acmpca.UntagCertificateAuthorityInput) acmpca.UntagCertificateAuthorityRequest { + if mock.UntagCertificateAuthorityRequestFunc == nil { + panic("ACMPCAAPIMock.UntagCertificateAuthorityRequestFunc: method is nil but ACMPCAAPI.UntagCertificateAuthorityRequest was just called") + } + callInfo := struct { + In1 *acmpca.UntagCertificateAuthorityInput + }{ + In1: in1, + } + lockACMPCAAPIMockUntagCertificateAuthorityRequest.Lock() + mock.calls.UntagCertificateAuthorityRequest = append(mock.calls.UntagCertificateAuthorityRequest, callInfo) + lockACMPCAAPIMockUntagCertificateAuthorityRequest.Unlock() + return mock.UntagCertificateAuthorityRequestFunc(in1) +} + +// UntagCertificateAuthorityRequestCalls gets all the calls that were made to UntagCertificateAuthorityRequest. +// Check the length with: +// len(mockedACMPCAAPI.UntagCertificateAuthorityRequestCalls()) +func (mock *ACMPCAAPIMock) UntagCertificateAuthorityRequestCalls() []struct { + In1 *acmpca.UntagCertificateAuthorityInput +} { + var calls []struct { + In1 *acmpca.UntagCertificateAuthorityInput + } + lockACMPCAAPIMockUntagCertificateAuthorityRequest.RLock() + calls = mock.calls.UntagCertificateAuthorityRequest + lockACMPCAAPIMockUntagCertificateAuthorityRequest.RUnlock() + return calls +} + +// UpdateCertificateAuthorityRequest calls UpdateCertificateAuthorityRequestFunc. +func (mock *ACMPCAAPIMock) UpdateCertificateAuthorityRequest(in1 *acmpca.UpdateCertificateAuthorityInput) acmpca.UpdateCertificateAuthorityRequest { + if mock.UpdateCertificateAuthorityRequestFunc == nil { + panic("ACMPCAAPIMock.UpdateCertificateAuthorityRequestFunc: method is nil but ACMPCAAPI.UpdateCertificateAuthorityRequest was just called") + } + callInfo := struct { + In1 *acmpca.UpdateCertificateAuthorityInput + }{ + In1: in1, + } + lockACMPCAAPIMockUpdateCertificateAuthorityRequest.Lock() + mock.calls.UpdateCertificateAuthorityRequest = append(mock.calls.UpdateCertificateAuthorityRequest, callInfo) + lockACMPCAAPIMockUpdateCertificateAuthorityRequest.Unlock() + return mock.UpdateCertificateAuthorityRequestFunc(in1) +} + +// UpdateCertificateAuthorityRequestCalls gets all the calls that were made to UpdateCertificateAuthorityRequest. +// Check the length with: +// len(mockedACMPCAAPI.UpdateCertificateAuthorityRequestCalls()) +func (mock *ACMPCAAPIMock) UpdateCertificateAuthorityRequestCalls() []struct { + In1 *acmpca.UpdateCertificateAuthorityInput +} { + var calls []struct { + In1 *acmpca.UpdateCertificateAuthorityInput + } + lockACMPCAAPIMockUpdateCertificateAuthorityRequest.RLock() + calls = mock.calls.UpdateCertificateAuthorityRequest + lockACMPCAAPIMockUpdateCertificateAuthorityRequest.RUnlock() + return calls +} + +// WaitUntilAuditReportCreated calls WaitUntilAuditReportCreatedFunc. +func (mock *ACMPCAAPIMock) WaitUntilAuditReportCreated(in1 *acmpca.DescribeCertificateAuthorityAuditReportInput) error { + if mock.WaitUntilAuditReportCreatedFunc == nil { + panic("ACMPCAAPIMock.WaitUntilAuditReportCreatedFunc: method is nil but ACMPCAAPI.WaitUntilAuditReportCreated was just called") + } + callInfo := struct { + In1 *acmpca.DescribeCertificateAuthorityAuditReportInput + }{ + In1: in1, + } + lockACMPCAAPIMockWaitUntilAuditReportCreated.Lock() + mock.calls.WaitUntilAuditReportCreated = append(mock.calls.WaitUntilAuditReportCreated, callInfo) + lockACMPCAAPIMockWaitUntilAuditReportCreated.Unlock() + return mock.WaitUntilAuditReportCreatedFunc(in1) +} + +// WaitUntilAuditReportCreatedCalls gets all the calls that were made to WaitUntilAuditReportCreated. +// Check the length with: +// len(mockedACMPCAAPI.WaitUntilAuditReportCreatedCalls()) +func (mock *ACMPCAAPIMock) WaitUntilAuditReportCreatedCalls() []struct { + In1 *acmpca.DescribeCertificateAuthorityAuditReportInput +} { + var calls []struct { + In1 *acmpca.DescribeCertificateAuthorityAuditReportInput + } + lockACMPCAAPIMockWaitUntilAuditReportCreated.RLock() + calls = mock.calls.WaitUntilAuditReportCreated + lockACMPCAAPIMockWaitUntilAuditReportCreated.RUnlock() + return calls +} + +// WaitUntilAuditReportCreatedWithContext calls WaitUntilAuditReportCreatedWithContextFunc. +func (mock *ACMPCAAPIMock) WaitUntilAuditReportCreatedWithContext(in1 aws.Context, in2 *acmpca.DescribeCertificateAuthorityAuditReportInput, in3 ...aws.WaiterOption) error { + if mock.WaitUntilAuditReportCreatedWithContextFunc == nil { + panic("ACMPCAAPIMock.WaitUntilAuditReportCreatedWithContextFunc: method is nil but ACMPCAAPI.WaitUntilAuditReportCreatedWithContext was just called") + } + callInfo := struct { + In1 aws.Context + In2 *acmpca.DescribeCertificateAuthorityAuditReportInput + In3 []aws.WaiterOption + }{ + In1: in1, + In2: in2, + In3: in3, + } + lockACMPCAAPIMockWaitUntilAuditReportCreatedWithContext.Lock() + mock.calls.WaitUntilAuditReportCreatedWithContext = append(mock.calls.WaitUntilAuditReportCreatedWithContext, callInfo) + lockACMPCAAPIMockWaitUntilAuditReportCreatedWithContext.Unlock() + return mock.WaitUntilAuditReportCreatedWithContextFunc(in1, in2, in3...) +} + +// WaitUntilAuditReportCreatedWithContextCalls gets all the calls that were made to WaitUntilAuditReportCreatedWithContext. +// Check the length with: +// len(mockedACMPCAAPI.WaitUntilAuditReportCreatedWithContextCalls()) +func (mock *ACMPCAAPIMock) WaitUntilAuditReportCreatedWithContextCalls() []struct { + In1 aws.Context + In2 *acmpca.DescribeCertificateAuthorityAuditReportInput + In3 []aws.WaiterOption +} { + var calls []struct { + In1 aws.Context + In2 *acmpca.DescribeCertificateAuthorityAuditReportInput + In3 []aws.WaiterOption + } + lockACMPCAAPIMockWaitUntilAuditReportCreatedWithContext.RLock() + calls = mock.calls.WaitUntilAuditReportCreatedWithContext + lockACMPCAAPIMockWaitUntilAuditReportCreatedWithContext.RUnlock() + return calls +} + +// WaitUntilCertificateAuthorityCSRCreated calls WaitUntilCertificateAuthorityCSRCreatedFunc. +func (mock *ACMPCAAPIMock) WaitUntilCertificateAuthorityCSRCreated(in1 *acmpca.GetCertificateAuthorityCsrInput) error { + if mock.WaitUntilCertificateAuthorityCSRCreatedFunc == nil { + panic("ACMPCAAPIMock.WaitUntilCertificateAuthorityCSRCreatedFunc: method is nil but ACMPCAAPI.WaitUntilCertificateAuthorityCSRCreated was just called") + } + callInfo := struct { + In1 *acmpca.GetCertificateAuthorityCsrInput + }{ + In1: in1, + } + lockACMPCAAPIMockWaitUntilCertificateAuthorityCSRCreated.Lock() + mock.calls.WaitUntilCertificateAuthorityCSRCreated = append(mock.calls.WaitUntilCertificateAuthorityCSRCreated, callInfo) + lockACMPCAAPIMockWaitUntilCertificateAuthorityCSRCreated.Unlock() + return mock.WaitUntilCertificateAuthorityCSRCreatedFunc(in1) +} + +// WaitUntilCertificateAuthorityCSRCreatedCalls gets all the calls that were made to WaitUntilCertificateAuthorityCSRCreated. +// Check the length with: +// len(mockedACMPCAAPI.WaitUntilCertificateAuthorityCSRCreatedCalls()) +func (mock *ACMPCAAPIMock) WaitUntilCertificateAuthorityCSRCreatedCalls() []struct { + In1 *acmpca.GetCertificateAuthorityCsrInput +} { + var calls []struct { + In1 *acmpca.GetCertificateAuthorityCsrInput + } + lockACMPCAAPIMockWaitUntilCertificateAuthorityCSRCreated.RLock() + calls = mock.calls.WaitUntilCertificateAuthorityCSRCreated + lockACMPCAAPIMockWaitUntilCertificateAuthorityCSRCreated.RUnlock() + return calls +} + +// WaitUntilCertificateAuthorityCSRCreatedWithContext calls WaitUntilCertificateAuthorityCSRCreatedWithContextFunc. +func (mock *ACMPCAAPIMock) WaitUntilCertificateAuthorityCSRCreatedWithContext(in1 aws.Context, in2 *acmpca.GetCertificateAuthorityCsrInput, in3 ...aws.WaiterOption) error { + if mock.WaitUntilCertificateAuthorityCSRCreatedWithContextFunc == nil { + panic("ACMPCAAPIMock.WaitUntilCertificateAuthorityCSRCreatedWithContextFunc: method is nil but ACMPCAAPI.WaitUntilCertificateAuthorityCSRCreatedWithContext was just called") + } + callInfo := struct { + In1 aws.Context + In2 *acmpca.GetCertificateAuthorityCsrInput + In3 []aws.WaiterOption + }{ + In1: in1, + In2: in2, + In3: in3, + } + lockACMPCAAPIMockWaitUntilCertificateAuthorityCSRCreatedWithContext.Lock() + mock.calls.WaitUntilCertificateAuthorityCSRCreatedWithContext = append(mock.calls.WaitUntilCertificateAuthorityCSRCreatedWithContext, callInfo) + lockACMPCAAPIMockWaitUntilCertificateAuthorityCSRCreatedWithContext.Unlock() + return mock.WaitUntilCertificateAuthorityCSRCreatedWithContextFunc(in1, in2, in3...) +} + +// WaitUntilCertificateAuthorityCSRCreatedWithContextCalls gets all the calls that were made to WaitUntilCertificateAuthorityCSRCreatedWithContext. +// Check the length with: +// len(mockedACMPCAAPI.WaitUntilCertificateAuthorityCSRCreatedWithContextCalls()) +func (mock *ACMPCAAPIMock) WaitUntilCertificateAuthorityCSRCreatedWithContextCalls() []struct { + In1 aws.Context + In2 *acmpca.GetCertificateAuthorityCsrInput + In3 []aws.WaiterOption +} { + var calls []struct { + In1 aws.Context + In2 *acmpca.GetCertificateAuthorityCsrInput + In3 []aws.WaiterOption + } + lockACMPCAAPIMockWaitUntilCertificateAuthorityCSRCreatedWithContext.RLock() + calls = mock.calls.WaitUntilCertificateAuthorityCSRCreatedWithContext + lockACMPCAAPIMockWaitUntilCertificateAuthorityCSRCreatedWithContext.RUnlock() + return calls +} + +// WaitUntilCertificateIssued calls WaitUntilCertificateIssuedFunc. +func (mock *ACMPCAAPIMock) WaitUntilCertificateIssued(in1 *acmpca.GetCertificateInput) error { + if mock.WaitUntilCertificateIssuedFunc == nil { + panic("ACMPCAAPIMock.WaitUntilCertificateIssuedFunc: method is nil but ACMPCAAPI.WaitUntilCertificateIssued was just called") + } + callInfo := struct { + In1 *acmpca.GetCertificateInput + }{ + In1: in1, + } + lockACMPCAAPIMockWaitUntilCertificateIssued.Lock() + mock.calls.WaitUntilCertificateIssued = append(mock.calls.WaitUntilCertificateIssued, callInfo) + lockACMPCAAPIMockWaitUntilCertificateIssued.Unlock() + return mock.WaitUntilCertificateIssuedFunc(in1) +} + +// WaitUntilCertificateIssuedCalls gets all the calls that were made to WaitUntilCertificateIssued. +// Check the length with: +// len(mockedACMPCAAPI.WaitUntilCertificateIssuedCalls()) +func (mock *ACMPCAAPIMock) WaitUntilCertificateIssuedCalls() []struct { + In1 *acmpca.GetCertificateInput +} { + var calls []struct { + In1 *acmpca.GetCertificateInput + } + lockACMPCAAPIMockWaitUntilCertificateIssued.RLock() + calls = mock.calls.WaitUntilCertificateIssued + lockACMPCAAPIMockWaitUntilCertificateIssued.RUnlock() + return calls +} + +// WaitUntilCertificateIssuedWithContext calls WaitUntilCertificateIssuedWithContextFunc. +func (mock *ACMPCAAPIMock) WaitUntilCertificateIssuedWithContext(in1 aws.Context, in2 *acmpca.GetCertificateInput, in3 ...aws.WaiterOption) error { + if mock.WaitUntilCertificateIssuedWithContextFunc == nil { + panic("ACMPCAAPIMock.WaitUntilCertificateIssuedWithContextFunc: method is nil but ACMPCAAPI.WaitUntilCertificateIssuedWithContext was just called") + } + callInfo := struct { + In1 aws.Context + In2 *acmpca.GetCertificateInput + In3 []aws.WaiterOption + }{ + In1: in1, + In2: in2, + In3: in3, + } + lockACMPCAAPIMockWaitUntilCertificateIssuedWithContext.Lock() + mock.calls.WaitUntilCertificateIssuedWithContext = append(mock.calls.WaitUntilCertificateIssuedWithContext, callInfo) + lockACMPCAAPIMockWaitUntilCertificateIssuedWithContext.Unlock() + return mock.WaitUntilCertificateIssuedWithContextFunc(in1, in2, in3...) +} + +// WaitUntilCertificateIssuedWithContextCalls gets all the calls that were made to WaitUntilCertificateIssuedWithContext. +// Check the length with: +// len(mockedACMPCAAPI.WaitUntilCertificateIssuedWithContextCalls()) +func (mock *ACMPCAAPIMock) WaitUntilCertificateIssuedWithContextCalls() []struct { + In1 aws.Context + In2 *acmpca.GetCertificateInput + In3 []aws.WaiterOption +} { + var calls []struct { + In1 aws.Context + In2 *acmpca.GetCertificateInput + In3 []aws.WaiterOption + } + lockACMPCAAPIMockWaitUntilCertificateIssuedWithContext.RLock() + calls = mock.calls.WaitUntilCertificateIssuedWithContext + lockACMPCAAPIMockWaitUntilCertificateIssuedWithContext.RUnlock() + return calls +} diff --git a/mocks/issuer.mock.go b/mocks/issuer.mock.go index f9001bb..5c58212 100644 --- a/mocks/issuer.mock.go +++ b/mocks/issuer.mock.go @@ -14,10 +14,6 @@ var ( lockIssuerMockIssue sync.RWMutex ) -// Ensure, that IssuerMock does implement Issuer. -// If this is not the case, regenerate this file with moq. -var _ certify.Issuer = &IssuerMock{} - // IssuerMock is a mock implementation of Issuer. // // func TestSomethingThatUsesIssuer(t *testing.T) { diff --git a/vendor/github.com/aws/aws-sdk-go-v2/LICENSE.txt b/vendor/github.com/aws/aws-sdk-go-v2/LICENSE.txt new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/LICENSE.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/aws/aws-sdk-go-v2/NOTICE.txt b/vendor/github.com/aws/aws-sdk-go-v2/NOTICE.txt new file mode 100644 index 0000000..5f14d11 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/NOTICE.txt @@ -0,0 +1,3 @@ +AWS SDK for Go +Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. +Copyright 2014-2015 Stripe, Inc. diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/awserr/error.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/awserr/error.go new file mode 100644 index 0000000..56fdfc2 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/aws/awserr/error.go @@ -0,0 +1,145 @@ +// Package awserr represents API error interface accessors for the SDK. +package awserr + +// An Error wraps lower level errors with code, message and an original error. +// The underlying concrete error type may also satisfy other interfaces which +// can be to used to obtain more specific information about the error. +// +// Calling Error() or String() will always include the full information about +// an error based on its underlying type. +// +// Example: +// +// output, err := s3manage.Upload(svc, input, opts) +// if err != nil { +// if awsErr, ok := err.(awserr.Error); ok { +// // Get error details +// log.Println("Error:", awsErr.Code(), awsErr.Message()) +// +// // Prints out full error message, including original error if there was one. +// log.Println("Error:", awsErr.Error()) +// +// // Get original error +// if origErr := awsErr.OrigErr(); origErr != nil { +// // operate on original error. +// } +// } else { +// fmt.Println(err.Error()) +// } +// } +// +type Error interface { + // Satisfy the generic error interface. + error + + // Returns the short phrase depicting the classification of the error. + Code() string + + // Returns the error details message. + Message() string + + // Returns the original error if one was set. Nil is returned if not set. + OrigErr() error +} + +// BatchError is a batch of errors which also wraps lower level errors with +// code, message, and original errors. Calling Error() will include all errors +// that occurred in the batch. +// +// Deprecated: Replaced with BatchedErrors. Only defined for backwards +// compatibility. +type BatchError interface { + // Satisfy the generic error interface. + error + + // Returns the short phrase depicting the classification of the error. + Code() string + + // Returns the error details message. + Message() string + + // Returns the original error if one was set. Nil is returned if not set. + OrigErrs() []error +} + +// BatchedErrors is a batch of errors which also wraps lower level errors with +// code, message, and original errors. Calling Error() will include all errors +// that occurred in the batch. +// +// Replaces BatchError +type BatchedErrors interface { + // Satisfy the base Error interface. + Error + + // Returns the original error if one was set. Nil is returned if not set. + OrigErrs() []error +} + +// New returns an Error object described by the code, message, and origErr. +// +// If origErr satisfies the Error interface it will not be wrapped within a new +// Error object and will instead be returned. +func New(code, message string, origErr error) Error { + var errs []error + if origErr != nil { + errs = append(errs, origErr) + } + return newBaseError(code, message, errs) +} + +// NewBatchError returns an BatchedErrors with a collection of errors as an +// array of errors. +func NewBatchError(code, message string, errs []error) BatchedErrors { + return newBaseError(code, message, errs) +} + +// A RequestFailure is an interface to extract request failure information from +// an Error such as the request ID of the failed request returned by a service. +// RequestFailures may not always have a requestID value if the request failed +// prior to reaching the service such as a connection error. +// +// Example: +// +// output, err := s3manage.Upload(svc, input, opts) +// if err != nil { +// if reqerr, ok := err.(RequestFailure); ok { +// log.Println("Request failed", reqerr.Code(), reqerr.Message(), reqerr.RequestID()) +// } else { +// log.Println("Error:", err.Error()) +// } +// } +// +// Combined with awserr.Error: +// +// output, err := s3manage.Upload(svc, input, opts) +// if err != nil { +// if awsErr, ok := err.(awserr.Error); ok { +// // Generic AWS Error with Code, Message, and original error (if any) +// fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) +// +// if reqErr, ok := err.(awserr.RequestFailure); ok { +// // A service error occurred +// fmt.Println(reqErr.StatusCode(), reqErr.RequestID()) +// } +// } else { +// fmt.Println(err.Error()) +// } +// } +// +type RequestFailure interface { + Error + + // The status code of the HTTP response. + StatusCode() int + + // The request ID returned by the service for a request failure. This will + // be empty if no request ID is available such as the request failed due + // to a connection error. + RequestID() string +} + +// NewRequestFailure returns a new request error wrapper for the given Error +// provided. +func NewRequestFailure(err Error, statusCode int, reqID string) RequestFailure { + return newRequestError(err, statusCode, reqID) +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/awserr/types.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/awserr/types.go new file mode 100644 index 0000000..0202a00 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/aws/awserr/types.go @@ -0,0 +1,194 @@ +package awserr + +import "fmt" + +// SprintError returns a string of the formatted error code. +// +// Both extra and origErr are optional. If they are included their lines +// will be added, but if they are not included their lines will be ignored. +func SprintError(code, message, extra string, origErr error) string { + msg := fmt.Sprintf("%s: %s", code, message) + if extra != "" { + msg = fmt.Sprintf("%s\n\t%s", msg, extra) + } + if origErr != nil { + msg = fmt.Sprintf("%s\ncaused by: %s", msg, origErr.Error()) + } + return msg +} + +// A baseError wraps the code and message which defines an error. It also +// can be used to wrap an original error object. +// +// Should be used as the root for errors satisfying the awserr.Error. Also +// for any error which does not fit into a specific error wrapper type. +type baseError struct { + // Classification of error + code string + + // Detailed information about error + message string + + // Optional original error this error is based off of. Allows building + // chained errors. + errs []error +} + +// newBaseError returns an error object for the code, message, and errors. +// +// code is a short no whitespace phrase depicting the classification of +// the error that is being created. +// +// message is the free flow string containing detailed information about the +// error. +// +// origErrs is the error objects which will be nested under the new errors to +// be returned. +func newBaseError(code, message string, origErrs []error) *baseError { + b := &baseError{ + code: code, + message: message, + errs: origErrs, + } + + return b +} + +// Error returns the string representation of the error. +// +// See ErrorWithExtra for formatting. +// +// Satisfies the error interface. +func (b baseError) Error() string { + size := len(b.errs) + if size > 0 { + return SprintError(b.code, b.message, "", errorList(b.errs)) + } + + return SprintError(b.code, b.message, "", nil) +} + +// String returns the string representation of the error. +// Alias for Error to satisfy the stringer interface. +func (b baseError) String() string { + return b.Error() +} + +// Code returns the short phrase depicting the classification of the error. +func (b baseError) Code() string { + return b.code +} + +// Message returns the error details message. +func (b baseError) Message() string { + return b.message +} + +// OrigErr returns the original error if one was set. Nil is returned if no +// error was set. This only returns the first element in the list. If the full +// list is needed, use BatchedErrors. +func (b baseError) OrigErr() error { + switch len(b.errs) { + case 0: + return nil + case 1: + return b.errs[0] + default: + if err, ok := b.errs[0].(Error); ok { + return NewBatchError(err.Code(), err.Message(), b.errs[1:]) + } + return NewBatchError("BatchedErrors", + "multiple errors occurred", b.errs) + } +} + +// OrigErrs returns the original errors if one was set. An empty slice is +// returned if no error was set. +func (b baseError) OrigErrs() []error { + return b.errs +} + +// So that the Error interface type can be included as an anonymous field +// in the requestError struct and not conflict with the error.Error() method. +type awsError Error + +// A requestError wraps a request or service error. +// +// Composed of baseError for code, message, and original error. +type requestError struct { + awsError + statusCode int + requestID string +} + +// newRequestError returns a wrapped error with additional information for +// request status code, and service requestID. +// +// Should be used to wrap all request which involve service requests. Even if +// the request failed without a service response, but had an HTTP status code +// that may be meaningful. +// +// Also wraps original errors via the baseError. +func newRequestError(err Error, statusCode int, requestID string) *requestError { + return &requestError{ + awsError: err, + statusCode: statusCode, + requestID: requestID, + } +} + +// Error returns the string representation of the error. +// Satisfies the error interface. +func (r requestError) Error() string { + extra := fmt.Sprintf("status code: %d, request id: %s", + r.statusCode, r.requestID) + return SprintError(r.Code(), r.Message(), extra, r.OrigErr()) +} + +// String returns the string representation of the error. +// Alias for Error to satisfy the stringer interface. +func (r requestError) String() string { + return r.Error() +} + +// StatusCode returns the wrapped status code for the error +func (r requestError) StatusCode() int { + return r.statusCode +} + +// RequestID returns the wrapped requestID +func (r requestError) RequestID() string { + return r.requestID +} + +// OrigErrs returns the original errors if one was set. An empty slice is +// returned if no error was set. +func (r requestError) OrigErrs() []error { + if b, ok := r.awsError.(BatchedErrors); ok { + return b.OrigErrs() + } + return []error{r.OrigErr()} +} + +// An error list that satisfies the golang interface +type errorList []error + +// Error returns the string representation of the error. +// +// Satisfies the error interface. +func (e errorList) Error() string { + msg := "" + // How do we want to handle the array size being zero + if size := len(e); size > 0 { + for i := 0; i < size; i++ { + msg += fmt.Sprintf("%s", e[i].Error()) + // We check the next index to see if it is within the slice. + // If it is, then we append a newline. We do this, because unit tests + // could be broken with the additional '\n' + if i+1 < size { + msg += "\n" + } + } + } + return msg +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/chain_provider.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/chain_provider.go new file mode 100644 index 0000000..c78dfac --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/aws/chain_provider.go @@ -0,0 +1,75 @@ +package aws + +import ( + "github.com/aws/aws-sdk-go-v2/aws/awserr" +) + +// A ChainProvider will search for a provider which returns credentials +// and cache that provider until Retrieve is called again. +// +// The ChainProvider provides a way of chaining multiple providers together +// which will pick the first available using priority order of the Providers +// in the list. +// +// If none of the Providers retrieve valid credentials Credentials, ChainProvider's +// Retrieve() will return the error ErrNoValidProvidersFoundInChain. +// +// If a CredentialsProvider is found which returns valid credentials Credentials ChainProvider +// will cache that CredentialsProvider for all calls to IsExpired(), until Retrieve is +// called again. +// +// Example of ChainProvider to be used with an EnvProvider and EC2RoleProvider. +// In this example EnvProvider will first check if any credentials are available +// via the environment variables. If there are none ChainProvider will check +// the next CredentialsProvider in the list, EC2RoleProvider in this case. If EC2RoleProvider +// does not return any credentials ChainProvider will return the error +// ErrNoValidProvidersFoundInChain +// +// creds := aws.NewChainCredentials( +// []aws.CredentialsProvider{ +// &credentials.EnvProvider{}, +// &ec2rolecreds.EC2RoleProvider{ +// Client: ec2metadata.New(cfg), +// }, +// }) +// +// // Usage of ChainCredentials with aws.Config +// cfg := cfg.Copy() +// cfg.Credentials = creds +// svc := ec2.New(cfg) +// +type ChainProvider struct { + SafeCredentialsProvider + + Providers []CredentialsProvider +} + +// NewChainProvider returns a pointer to a new ChainProvider value wrapping +// a chain of credentials providers. +func NewChainProvider(providers []CredentialsProvider) *ChainProvider { + p := &ChainProvider{ + Providers: append([]CredentialsProvider{}, providers...), + } + p.RetrieveFn = p.retrieveFn + + return p +} + +// Retrieve returns the credentials value or error if no provider returned +// without error. +// +// If a provider is found it will be cached and any calls to IsExpired() +// will return the expired state of the cached provider. +func (c *ChainProvider) retrieveFn() (Credentials, error) { + var errs []error + for _, p := range c.Providers { + creds, err := p.Retrieve() + if err == nil { + return creds, nil + } + errs = append(errs, err) + } + + return Credentials{}, + awserr.NewBatchError("NoCredentialProviders", "no valid providers in chain", errs) +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/client.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/client.go new file mode 100644 index 0000000..f5b63bd --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/aws/client.go @@ -0,0 +1,85 @@ +package aws + +import ( + "net/http" +) + +// Metadata wraps immutable data from the Client structure. +type Metadata struct { + ServiceName string + APIVersion string + + Endpoint string + SigningName string + SigningRegion string + + JSONVersion string + TargetPrefix string +} + +// A Client implements the base client request and response handling +// used by all service clients. +type Client struct { + Metadata Metadata + + Config Config + + Region string + Credentials CredentialsProvider + EndpointResolver EndpointResolver + Handlers Handlers + Retryer Retryer + + // TODO replace with value not pointer + LogLevel LogLevel + Logger Logger + + HTTPClient *http.Client +} + +// NewClient will return a pointer to a new initialized service client. +func NewClient(cfg Config, metadata Metadata) *Client { + svc := &Client{ + Metadata: metadata, + + // TODO remove config when request reqfactored + Config: cfg, + + Region: cfg.Region, + Credentials: cfg.Credentials, + EndpointResolver: cfg.EndpointResolver, + Handlers: cfg.Handlers.Copy(), + Retryer: cfg.Retryer, + + LogLevel: cfg.LogLevel, + Logger: cfg.Logger, + } + + retryer := cfg.Retryer + if retryer == nil { + // TODO need better way of specifing default num retries + retryer = DefaultRetryer{NumMaxRetries: 3} + } + svc.Retryer = retryer + + svc.AddDebugHandlers() + + return svc +} + +// NewRequest returns a new Request pointer for the service API +// operation and parameters. +func (c *Client) NewRequest(operation *Operation, params interface{}, data interface{}) *Request { + return New(c.Config, c.Metadata, c.Handlers, c.Retryer, operation, params, data) +} + +// AddDebugHandlers injects debug logging handlers into the service to log request +// debug information. +func (c *Client) AddDebugHandlers() { + if !c.Config.LogLevel.AtLeast(LogDebug) { + return + } + + c.Handlers.Send.PushFrontNamed(NamedHandler{Name: "awssdk.client.LogRequest", Fn: logRequest}) + c.Handlers.Send.PushBackNamed(NamedHandler{Name: "awssdk.client.LogResponse", Fn: logResponse}) +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/client_logger.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/client_logger.go new file mode 100644 index 0000000..f3e2e86 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/aws/client_logger.go @@ -0,0 +1,105 @@ +package aws + +import ( + "bytes" + "fmt" + "io" + "io/ioutil" + "net/http/httputil" +) + +const logReqMsg = `DEBUG: Request %s/%s Details: +---[ REQUEST POST-SIGN ]----------------------------- +%s +-----------------------------------------------------` + +const logReqErrMsg = `DEBUG ERROR: Request %s/%s: +---[ REQUEST DUMP ERROR ]----------------------------- +%s +------------------------------------------------------` + +type logWriter struct { + // Logger is what we will use to log the payload of a response. + Logger Logger + // buf stores the contents of what has been read + buf *bytes.Buffer +} + +func (logger *logWriter) Write(b []byte) (int, error) { + return logger.buf.Write(b) +} + +type teeReaderCloser struct { + // io.Reader will be a tee reader that is used during logging. + // This structure will read from a body and write the contents to a logger. + io.Reader + // Source is used just to close when we are done reading. + Source io.ReadCloser +} + +func (reader *teeReaderCloser) Close() error { + return reader.Source.Close() +} + +func logRequest(r *Request) { + logBody := r.Config.LogLevel.Matches(LogDebugWithHTTPBody) + dumpedBody, err := httputil.DumpRequestOut(r.HTTPRequest, logBody) + if err != nil { + r.Config.Logger.Log(fmt.Sprintf(logReqErrMsg, r.Metadata.ServiceName, r.Operation.Name, err)) + return + } + + if logBody { + // Reset the request body because dumpRequest will re-wrap the r.HTTPRequest's + // Body as a NoOpCloser and will not be reset after read by the HTTP + // client reader. + r.ResetBody() + } + + r.Config.Logger.Log(fmt.Sprintf(logReqMsg, r.Metadata.ServiceName, r.Operation.Name, string(dumpedBody))) +} + +const logRespMsg = `DEBUG: Response %s/%s Details: +---[ RESPONSE ]-------------------------------------- +%s +-----------------------------------------------------` + +const logRespErrMsg = `DEBUG ERROR: Response %s/%s: +---[ RESPONSE DUMP ERROR ]----------------------------- +%s +-----------------------------------------------------` + +func logResponse(r *Request) { + lw := &logWriter{r.Config.Logger, bytes.NewBuffer(nil)} + r.HTTPResponse.Body = &teeReaderCloser{ + Reader: io.TeeReader(r.HTTPResponse.Body, lw), + Source: r.HTTPResponse.Body, + } + + handlerFn := func(req *Request) { + body, err := httputil.DumpResponse(req.HTTPResponse, false) + if err != nil { + lw.Logger.Log(fmt.Sprintf(logRespErrMsg, req.Metadata.ServiceName, req.Operation.Name, err)) + return + } + + b, err := ioutil.ReadAll(lw.buf) + if err != nil { + lw.Logger.Log(fmt.Sprintf(logRespErrMsg, req.Metadata.ServiceName, req.Operation.Name, err)) + return + } + lw.Logger.Log(fmt.Sprintf(logRespMsg, req.Metadata.ServiceName, req.Operation.Name, string(body))) + if req.Config.LogLevel.Matches(LogDebugWithHTTPBody) { + lw.Logger.Log(string(b)) + } + } + + const handlerName = "awsdk.client.LogResponse.ResponseBody" + + r.Handlers.Unmarshal.SetBackNamed(NamedHandler{ + Name: handlerName, Fn: handlerFn, + }) + r.Handlers.UnmarshalError.SetBackNamed(NamedHandler{ + Name: handlerName, Fn: handlerFn, + }) +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/config.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/config.go new file mode 100644 index 0000000..501e8ce --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/aws/config.go @@ -0,0 +1,105 @@ +package aws + +import ( + "net/http" +) + +// A Config provides service configuration for service clients. +type Config struct { + // The region to send requests to. This parameter is required and must + // be configured globally or on a per-client basis unless otherwise + // noted. A full list of regions is found in the "Regions and Endpoints" + // document. + // + // See http://docs.aws.amazon.com/general/latest/gr/rande.html for + // information on AWS regions. + Region string + + // The credentials object to use when signing requests. Defaults to a + // chain of credential providers to search for credentials in environment + // variables, shared credential file, and EC2 Instance Roles. + Credentials CredentialsProvider + + // The resolver to use for looking up endpoints for AWS service clients + // to use based on region. + EndpointResolver EndpointResolver + + // The HTTP client to use when sending requests. Defaults to + // `http.DefaultClient`. + HTTPClient *http.Client + + // TODO document + Handlers Handlers + + // Retryer guides how HTTP requests should be retried in case of + // recoverable failures. + // + // When nil or the value does not implement the request.Retryer interface, + // the client.DefaultRetryer will be used. + // + // When both Retryer and MaxRetries are non-nil, the former is used and + // the latter ignored. + // + // To set the Retryer field in a type-safe manner and with chaining, use + // the request.WithRetryer helper function: + // + // cfg := request.WithRetryer(aws.NewConfig(), myRetryer) + Retryer Retryer + + // An integer value representing the logging level. The default log level + // is zero (LogOff), which represents no logging. To enable logging set + // to a LogLevel Value. + LogLevel LogLevel + + // The logger writer interface to write logging messages to. Defaults to + // standard out. + Logger Logger + + // EnforceShouldRetryCheck is used in the AfterRetryHandler to always call + // ShouldRetry regardless of whether or not if request.Retryable is set. + // This will utilize ShouldRetry method of custom retryers. If EnforceShouldRetryCheck + // is not set, then ShouldRetry will only be called if request.Retryable is nil. + // Proper handling of the request.Retryable field is important when setting this field. + // + // TODO this config field is depercated and needs removed. + EnforceShouldRetryCheck bool + + // DisableRestProtocolURICleaning will not clean the URL path when making + // rest protocol requests. Will default to false. This would only be used + // for empty directory names in s3 requests. + // + // Example: + // cfg, err := external.LoadDefaultAWSConfig() + // cfg.DisableRestProtocolURICleaning = true + // + // svc := s3.New(cfg) + // out, err := svc.GetObject(&s3.GetObjectInput { + // Bucket: aws.String("bucketname"), + // Key: aws.String("//foo//bar//moo"), + // }) + // + // TODO need better way of representing support for this concept. Not on Config. + DisableRestProtocolURICleaning bool + + // DisableEndpointHostPrefix will disable the SDK's behavior of prefixing + // request endpoint hosts with modeled information. + // + // Disabling this feature is useful when you want to use local endpoints + // for testing that do not support the modeled host prefix pattern. + DisableEndpointHostPrefix bool +} + +// NewConfig returns a new Config pointer that can be chained with builder +// methods to set multiple configuration values inline without using pointers. +func NewConfig() *Config { + return &Config{} +} + +// Copy will return a shallow copy of the Config object. If any additional +// configurations are provided they will be merged into the new config returned. +func (c Config) Copy() Config { + cp := c + cp.Handlers = cp.Handlers.Copy() + + return cp +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/connection_reset_error.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/connection_reset_error.go new file mode 100644 index 0000000..5fe8be6 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/aws/connection_reset_error.go @@ -0,0 +1,19 @@ +// +build !appengine,!plan9 + +package aws + +import ( + "net" + "os" + "syscall" +) + +func isErrConnectionReset(err error) bool { + if opErr, ok := err.(*net.OpError); ok { + if sysErr, ok := opErr.Err.(*os.SyscallError); ok { + return sysErr.Err == syscall.ECONNRESET + } + } + + return false +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/connection_reset_error_other.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/connection_reset_error_other.go new file mode 100644 index 0000000..ca8422e --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/aws/connection_reset_error_other.go @@ -0,0 +1,11 @@ +// +build appengine plan9 + +package aws + +import ( + "strings" +) + +func isErrConnectionReset(err error) bool { + return strings.Contains(err.Error(), "connection reset") +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/context.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/context.go new file mode 100644 index 0000000..79f4268 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/aws/context.go @@ -0,0 +1,71 @@ +package aws + +import ( + "time" +) + +// Context is an copy of the Go v1.7 stdlib's context.Context interface. +// It is represented as a SDK interface to enable you to use the "WithContext" +// API methods with Go v1.6 and a Context type such as golang.org/x/net/context. +// +// See https://golang.org/pkg/context on how to use contexts. +type Context interface { + // Deadline returns the time when work done on behalf of this context + // should be canceled. Deadline returns ok==false when no deadline is + // set. Successive calls to Deadline return the same results. + Deadline() (deadline time.Time, ok bool) + + // Done returns a channel that's closed when work done on behalf of this + // context should be canceled. Done may return nil if this context can + // never be canceled. Successive calls to Done return the same value. + Done() <-chan struct{} + + // Err returns a non-nil error value after Done is closed. Err returns + // Canceled if the context was canceled or DeadlineExceeded if the + // context's deadline passed. No other values for Err are defined. + // After Done is closed, successive calls to Err return the same value. + Err() error + + // Value returns the value associated with this context for key, or nil + // if no value is associated with key. Successive calls to Value with + // the same key returns the same result. + // + // Use context values only for request-scoped data that transits + // processes and API boundaries, not for passing optional parameters to + // functions. + Value(key interface{}) interface{} +} + +// BackgroundContext returns a context that will never be canceled, has no +// values, and no deadline. This context is used by the SDK to provide +// backwards compatibility with non-context API operations and functionality. +// +// Go 1.6 and before: +// This context function is equivalent to context.Background in the Go stdlib. +// +// Go 1.7 and later: +// The context returned will be the value returned by context.Background() +// +// See https://golang.org/pkg/context for more information on Contexts. +func BackgroundContext() Context { + return backgroundCtx +} + +// SleepWithContext will wait for the timer duration to expire, or the context +// is canceled. Which ever happens first. If the context is canceled the Context's +// error will be returned. +// +// Expects Context to always return a non-nil error if the Done channel is closed. +func SleepWithContext(ctx Context, dur time.Duration) error { + t := time.NewTimer(dur) + defer t.Stop() + + select { + case <-t.C: + break + case <-ctx.Done(): + return ctx.Err() + } + + return nil +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/context_1_6.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/context_1_6.go new file mode 100644 index 0000000..8fdda53 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/aws/context_1_6.go @@ -0,0 +1,41 @@ +// +build !go1.7 + +package aws + +import "time" + +// An emptyCtx is a copy of the Go 1.7 context.emptyCtx type. This is copied to +// provide a 1.6 and 1.5 safe version of context that is compatible with Go +// 1.7's Context. +// +// An emptyCtx is never canceled, has no values, and has no deadline. It is not +// struct{}, since vars of this type must have distinct addresses. +type emptyCtx int + +func (*emptyCtx) Deadline() (deadline time.Time, ok bool) { + return +} + +func (*emptyCtx) Done() <-chan struct{} { + return nil +} + +func (*emptyCtx) Err() error { + return nil +} + +func (*emptyCtx) Value(key interface{}) interface{} { + return nil +} + +func (e *emptyCtx) String() string { + switch e { + case backgroundCtx: + return "aws.BackgroundContext" + } + return "unknown empty Context" +} + +var ( + backgroundCtx = new(emptyCtx) +) diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/context_1_7.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/context_1_7.go new file mode 100644 index 0000000..064f75c --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/aws/context_1_7.go @@ -0,0 +1,9 @@ +// +build go1.7 + +package aws + +import "context" + +var ( + backgroundCtx = context.Background() +) diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/convert_types.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/convert_types.go new file mode 100644 index 0000000..ff5d58e --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/aws/convert_types.go @@ -0,0 +1,387 @@ +package aws + +import "time" + +// String returns a pointer to the string value passed in. +func String(v string) *string { + return &v +} + +// StringValue returns the value of the string pointer passed in or +// "" if the pointer is nil. +func StringValue(v *string) string { + if v != nil { + return *v + } + return "" +} + +// StringSlice converts a slice of string values into a slice of +// string pointers +func StringSlice(src []string) []*string { + dst := make([]*string, len(src)) + for i := 0; i < len(src); i++ { + dst[i] = &(src[i]) + } + return dst +} + +// StringValueSlice converts a slice of string pointers into a slice of +// string values +func StringValueSlice(src []*string) []string { + dst := make([]string, len(src)) + for i := 0; i < len(src); i++ { + if src[i] != nil { + dst[i] = *(src[i]) + } + } + return dst +} + +// StringMap converts a string map of string values into a string +// map of string pointers +func StringMap(src map[string]string) map[string]*string { + dst := make(map[string]*string) + for k, val := range src { + v := val + dst[k] = &v + } + return dst +} + +// StringValueMap converts a string map of string pointers into a string +// map of string values +func StringValueMap(src map[string]*string) map[string]string { + dst := make(map[string]string) + for k, val := range src { + if val != nil { + dst[k] = *val + } + } + return dst +} + +// Bool returns a pointer to the bool value passed in. +func Bool(v bool) *bool { + return &v +} + +// BoolValue returns the value of the bool pointer passed in or +// false if the pointer is nil. +func BoolValue(v *bool) bool { + if v != nil { + return *v + } + return false +} + +// BoolSlice converts a slice of bool values into a slice of +// bool pointers +func BoolSlice(src []bool) []*bool { + dst := make([]*bool, len(src)) + for i := 0; i < len(src); i++ { + dst[i] = &(src[i]) + } + return dst +} + +// BoolValueSlice converts a slice of bool pointers into a slice of +// bool values +func BoolValueSlice(src []*bool) []bool { + dst := make([]bool, len(src)) + for i := 0; i < len(src); i++ { + if src[i] != nil { + dst[i] = *(src[i]) + } + } + return dst +} + +// BoolMap converts a string map of bool values into a string +// map of bool pointers +func BoolMap(src map[string]bool) map[string]*bool { + dst := make(map[string]*bool) + for k, val := range src { + v := val + dst[k] = &v + } + return dst +} + +// BoolValueMap converts a string map of bool pointers into a string +// map of bool values +func BoolValueMap(src map[string]*bool) map[string]bool { + dst := make(map[string]bool) + for k, val := range src { + if val != nil { + dst[k] = *val + } + } + return dst +} + +// Int returns a pointer to the int value passed in. +func Int(v int) *int { + return &v +} + +// IntValue returns the value of the int pointer passed in or +// 0 if the pointer is nil. +func IntValue(v *int) int { + if v != nil { + return *v + } + return 0 +} + +// IntSlice converts a slice of int values into a slice of +// int pointers +func IntSlice(src []int) []*int { + dst := make([]*int, len(src)) + for i := 0; i < len(src); i++ { + dst[i] = &(src[i]) + } + return dst +} + +// IntValueSlice converts a slice of int pointers into a slice of +// int values +func IntValueSlice(src []*int) []int { + dst := make([]int, len(src)) + for i := 0; i < len(src); i++ { + if src[i] != nil { + dst[i] = *(src[i]) + } + } + return dst +} + +// IntMap converts a string map of int values into a string +// map of int pointers +func IntMap(src map[string]int) map[string]*int { + dst := make(map[string]*int) + for k, val := range src { + v := val + dst[k] = &v + } + return dst +} + +// IntValueMap converts a string map of int pointers into a string +// map of int values +func IntValueMap(src map[string]*int) map[string]int { + dst := make(map[string]int) + for k, val := range src { + if val != nil { + dst[k] = *val + } + } + return dst +} + +// Int64 returns a pointer to the int64 value passed in. +func Int64(v int64) *int64 { + return &v +} + +// Int64Value returns the value of the int64 pointer passed in or +// 0 if the pointer is nil. +func Int64Value(v *int64) int64 { + if v != nil { + return *v + } + return 0 +} + +// Int64Slice converts a slice of int64 values into a slice of +// int64 pointers +func Int64Slice(src []int64) []*int64 { + dst := make([]*int64, len(src)) + for i := 0; i < len(src); i++ { + dst[i] = &(src[i]) + } + return dst +} + +// Int64ValueSlice converts a slice of int64 pointers into a slice of +// int64 values +func Int64ValueSlice(src []*int64) []int64 { + dst := make([]int64, len(src)) + for i := 0; i < len(src); i++ { + if src[i] != nil { + dst[i] = *(src[i]) + } + } + return dst +} + +// Int64Map converts a string map of int64 values into a string +// map of int64 pointers +func Int64Map(src map[string]int64) map[string]*int64 { + dst := make(map[string]*int64) + for k, val := range src { + v := val + dst[k] = &v + } + return dst +} + +// Int64ValueMap converts a string map of int64 pointers into a string +// map of int64 values +func Int64ValueMap(src map[string]*int64) map[string]int64 { + dst := make(map[string]int64) + for k, val := range src { + if val != nil { + dst[k] = *val + } + } + return dst +} + +// Float64 returns a pointer to the float64 value passed in. +func Float64(v float64) *float64 { + return &v +} + +// Float64Value returns the value of the float64 pointer passed in or +// 0 if the pointer is nil. +func Float64Value(v *float64) float64 { + if v != nil { + return *v + } + return 0 +} + +// Float64Slice converts a slice of float64 values into a slice of +// float64 pointers +func Float64Slice(src []float64) []*float64 { + dst := make([]*float64, len(src)) + for i := 0; i < len(src); i++ { + dst[i] = &(src[i]) + } + return dst +} + +// Float64ValueSlice converts a slice of float64 pointers into a slice of +// float64 values +func Float64ValueSlice(src []*float64) []float64 { + dst := make([]float64, len(src)) + for i := 0; i < len(src); i++ { + if src[i] != nil { + dst[i] = *(src[i]) + } + } + return dst +} + +// Float64Map converts a string map of float64 values into a string +// map of float64 pointers +func Float64Map(src map[string]float64) map[string]*float64 { + dst := make(map[string]*float64) + for k, val := range src { + v := val + dst[k] = &v + } + return dst +} + +// Float64ValueMap converts a string map of float64 pointers into a string +// map of float64 values +func Float64ValueMap(src map[string]*float64) map[string]float64 { + dst := make(map[string]float64) + for k, val := range src { + if val != nil { + dst[k] = *val + } + } + return dst +} + +// Time returns a pointer to the time.Time value passed in. +func Time(v time.Time) *time.Time { + return &v +} + +// TimeValue returns the value of the time.Time pointer passed in or +// time.Time{} if the pointer is nil. +func TimeValue(v *time.Time) time.Time { + if v != nil { + return *v + } + return time.Time{} +} + +// SecondsTimeValue converts an int64 pointer to a time.Time value +// representing seconds since Epoch or time.Time{} if the pointer is nil. +func SecondsTimeValue(v *int64) time.Time { + if v != nil { + return time.Unix((*v / 1000), 0) + } + return time.Time{} +} + +// MillisecondsTimeValue converts an int64 pointer to a time.Time value +// representing milliseconds sinch Epoch or time.Time{} if the pointer is nil. +func MillisecondsTimeValue(v *int64) time.Time { + if v != nil { + return time.Unix(0, (*v * 1000000)) + } + return time.Time{} +} + +// TimeUnixMilli returns a Unix timestamp in milliseconds from "January 1, 1970 UTC". +// The result is undefined if the Unix time cannot be represented by an int64. +// Which includes calling TimeUnixMilli on a zero Time is undefined. +// +// This utility is useful for service API's such as CloudWatch Logs which require +// their unix time values to be in milliseconds. +// +// See Go stdlib https://golang.org/pkg/time/#Time.UnixNano for more information. +func TimeUnixMilli(t time.Time) int64 { + return t.UnixNano() / int64(time.Millisecond/time.Nanosecond) +} + +// TimeSlice converts a slice of time.Time values into a slice of +// time.Time pointers +func TimeSlice(src []time.Time) []*time.Time { + dst := make([]*time.Time, len(src)) + for i := 0; i < len(src); i++ { + dst[i] = &(src[i]) + } + return dst +} + +// TimeValueSlice converts a slice of time.Time pointers into a slice of +// time.Time values +func TimeValueSlice(src []*time.Time) []time.Time { + dst := make([]time.Time, len(src)) + for i := 0; i < len(src); i++ { + if src[i] != nil { + dst[i] = *(src[i]) + } + } + return dst +} + +// TimeMap converts a string map of time.Time values into a string +// map of time.Time pointers +func TimeMap(src map[string]time.Time) map[string]*time.Time { + dst := make(map[string]*time.Time) + for k, val := range src { + v := val + dst[k] = &v + } + return dst +} + +// TimeValueMap converts a string map of time.Time pointers into a string +// map of time.Time values +func TimeValueMap(src map[string]*time.Time) map[string]time.Time { + dst := make(map[string]time.Time) + for k, val := range src { + if val != nil { + dst[k] = *val + } + } + return dst +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/credentials.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/credentials.go new file mode 100644 index 0000000..db93f59 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/aws/credentials.go @@ -0,0 +1,138 @@ +package aws + +import ( + "math" + "sync" + "sync/atomic" + "time" + + "github.com/aws/aws-sdk-go-v2/internal/sdk" +) + +// NeverExpire is the time identifier used when a credential provider's +// credentials will not expire. This is used in cases where a non-expiring +// provider type cannot be used. +var NeverExpire = time.Unix(math.MaxInt64, 0) + +// AnonymousCredentials is an empty CredentialProvider that can be used as +// dummy placeholder credentials for requests that do not need signed. +// +// This credentials can be used to configure a service to not sign requests +// when making service API calls. For example, when accessing public +// s3 buckets. +// +// s3Cfg := cfg.Copy() +// s3cfg.Credentials = AnonymousCredentials +// +// svc := s3.New(s3Cfg) +var AnonymousCredentials = StaticCredentialsProvider{ + Value: Credentials{Source: "AnonymousCredentials"}, +} + +// An Expiration provides wrapper around time with expiration related methods. +type Expiration time.Time + +// Expired returns if the time has expired. + +// A Credentials is the AWS credentials value for individual credential fields. +type Credentials struct { + // AWS Access key ID + AccessKeyID string + + // AWS Secret Access Key + SecretAccessKey string + + // AWS Session Token + SessionToken string + + // Source of the credentials + Source string + + // Time the credentials will expire. + CanExpire bool + Expires time.Time +} + +// Expired returns if the credetials have expired. +func (v Credentials) Expired() bool { + if v.CanExpire { + return !v.Expires.After(sdk.NowTime()) + } + + return false +} + +// HasKeys returns if the credentials keys are set. +func (v Credentials) HasKeys() bool { + return len(v.AccessKeyID) > 0 && len(v.SecretAccessKey) > 0 +} + +// A CredentialsProvider is the interface for any component which will provide credentials +// Credentials. A CredentialsProvider is required to manage its own Expired state, and what to +// be expired means. +// +// The CredentialsProvider should not need to implement its own mutexes, because +// that will be managed by CredentialsLoader. +type CredentialsProvider interface { + // Retrieve returns nil if it successfully retrieved the value. + // Error is returned if the value were not obtainable, or empty. + Retrieve() (Credentials, error) + + // TODO should Retrieve take a context? +} + +// SafeCredentialsProvider provides caching and concurrency safe credentials +// retrieval via the RetrieveFn. +type SafeCredentialsProvider struct { + RetrieveFn func() (Credentials, error) + + creds atomic.Value + m sync.Mutex +} + +// Retrieve returns the credentials. If the credentials have already been +// retrieved, and not expired the cached credentials will be returned. If the +// credentails have not been retrieved yet, or expired RetrieveFn will be called. +// +// Retruns and error if RetrieveFn returns an error. +func (p *SafeCredentialsProvider) Retrieve() (Credentials, error) { + if creds := p.getCreds(); creds != nil { + return *creds, nil + } + + p.m.Lock() + defer p.m.Unlock() + + // Make sure another goroutine didn't already update the credentials. + if creds := p.getCreds(); creds != nil { + return *creds, nil + } + + creds, err := p.RetrieveFn() + if err != nil { + return Credentials{}, err + } + p.creds.Store(&creds) + + return creds, nil +} + +func (p *SafeCredentialsProvider) getCreds() *Credentials { + v := p.creds.Load() + if v == nil { + return nil + } + + c := v.(*Credentials) + if c != nil && c.HasKeys() && !c.Expired() { + return c + } + + return nil +} + +// Invalidate will invalidate the cached credentials. The next call to Retrieve +// will cause RetrieveFn to be called. +func (p *SafeCredentialsProvider) Invalidate() { + p.creds.Store((*Credentials)(nil)) +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/default_retryer.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/default_retryer.go new file mode 100644 index 0000000..a08af80 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/aws/default_retryer.go @@ -0,0 +1,136 @@ +package aws + +import ( + "math/rand" + "strconv" + "sync" + "time" +) + +// DefaultRetryer implements basic retry logic using exponential backoff for +// most services. If you want to implement custom retry logic, implement the +// Retryer interface or create a structure type that composes this +// struct and override the specific methods. For example, to override only +// the MaxRetries method: +// +// type retryer struct { +// client.DefaultRetryer +// } +// +// // This implementation always has 100 max retries +// func (d retryer) MaxRetries() int { return 100 } +type DefaultRetryer struct { + NumMaxRetries int +} + +// MaxRetries returns the number of maximum returns the service will use to make +// an individual API +func (d DefaultRetryer) MaxRetries() int { + return d.NumMaxRetries +} + +var seededRand = rand.New(&lockedSource{src: rand.NewSource(time.Now().UnixNano())}) + +// RetryRules returns the delay duration before retrying this request again +func (d DefaultRetryer) RetryRules(r *Request) time.Duration { + // Set the upper limit of delay in retrying at ~five minutes + minTime := 30 + throttle := d.shouldThrottle(r) + if throttle { + if delay, ok := getRetryDelay(r); ok { + return delay + } + + minTime = 500 + } + + retryCount := r.RetryCount + if retryCount > 13 { + retryCount = 13 + } else if throttle && retryCount > 8 { + retryCount = 8 + } + + delay := (1 << uint(retryCount)) * (seededRand.Intn(minTime) + minTime) + return time.Duration(delay) * time.Millisecond +} + +// ShouldRetry returns true if the request should be retried. +func (d DefaultRetryer) ShouldRetry(r *Request) bool { + // If one of the other handlers already set the retry state + // we don't want to override it based on the service's state + if r.Retryable != nil { + return *r.Retryable + } + + if r.HTTPResponse.StatusCode >= 500 { + return true + } + return r.IsErrorRetryable() || d.shouldThrottle(r) +} + +// ShouldThrottle returns true if the request should be throttled. +func (d DefaultRetryer) shouldThrottle(r *Request) bool { + switch r.HTTPResponse.StatusCode { + case 429: + case 502: + case 503: + case 504: + default: + return r.IsErrorThrottle() + } + + return true +} + +// This will look in the Retry-After header, RFC 7231, for how long +// it will wait before attempting another request +func getRetryDelay(r *Request) (time.Duration, bool) { + if !canUseRetryAfterHeader(r) { + return 0, false + } + + delayStr := r.HTTPResponse.Header.Get("Retry-After") + if len(delayStr) == 0 { + return 0, false + } + + delay, err := strconv.Atoi(delayStr) + if err != nil { + return 0, false + } + + return time.Duration(delay) * time.Second, true +} + +// Will look at the status code to see if the retry header pertains to +// the status code. +func canUseRetryAfterHeader(r *Request) bool { + switch r.HTTPResponse.StatusCode { + case 429: + case 503: + default: + return false + } + + return true +} + +// lockedSource is a thread-safe implementation of rand.Source +type lockedSource struct { + lk sync.Mutex + src rand.Source +} + +func (r *lockedSource) Int63() (n int64) { + r.lk.Lock() + n = r.src.Int63() + r.lk.Unlock() + return +} + +func (r *lockedSource) Seed(seed int64) { + r.lk.Lock() + r.src.Seed(seed) + r.lk.Unlock() +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/doc.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/doc.go new file mode 100644 index 0000000..4fcb616 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/aws/doc.go @@ -0,0 +1,56 @@ +// Package aws provides the core SDK's utilities and shared types. Use this package's +// utilities to simplify setting and reading API operations parameters. +// +// Value and Pointer Conversion Utilities +// +// This package includes a helper conversion utility for each scalar type the SDK's +// API use. These utilities make getting a pointer of the scalar, and dereferencing +// a pointer easier. +// +// Each conversion utility comes in two forms. Value to Pointer and Pointer to Value. +// The Pointer to value will safely dereference the pointer and return its value. +// If the pointer was nil, the scalar's zero value will be returned. +// +// The value to pointer functions will be named after the scalar type. So get a +// *string from a string value use the "String" function. This makes it easy to +// to get pointer of a literal string value, because getting the address of a +// literal requires assigning the value to a variable first. +// +// var strPtr *string +// +// // Without the SDK's conversion functions +// str := "my string" +// strPtr = &str +// +// // With the SDK's conversion functions +// strPtr = aws.String("my string") +// +// // Convert *string to string value +// str = aws.StringValue(strPtr) +// +// In addition to scalars the aws package also includes conversion utilities for +// map and slice for commonly types used in API parameters. The map and slice +// conversion functions use similar naming pattern as the scalar conversion +// functions. +// +// var strPtrs []*string +// var strs []string = []string{"Go", "Gophers", "Go"} +// +// // Convert []string to []*string +// strPtrs = aws.StringSlice(strs) +// +// // Convert []*string to []string +// strs = aws.StringValueSlice(strPtrs) +// +// SDK Default HTTP Client +// +// The SDK will use the http.DefaultClient if a HTTP client is not provided to +// the SDK's Session, or service client constructor. This means that if the +// http.DefaultClient is modified by other components of your application the +// modifications will be picked up by the SDK as well. +// +// In some cases this might be intended, but it is a better practice to create +// a custom HTTP Client to share explicitly through your application. You can +// configure the SDK to use the custom HTTP Client by setting the HTTPClient +// value of the SDK's Config type when creating a Session or service client. +package aws diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/endpoints.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/endpoints.go new file mode 100644 index 0000000..3dad528 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/aws/endpoints.go @@ -0,0 +1,52 @@ +package aws + +// EndpointResolver resolves an endpoint for a service endpoint id and region. +type EndpointResolver interface { + ResolveEndpoint(service, region string) (Endpoint, error) +} + +// EndpointResolverFunc is a helper utility that wraps a function so it satisfies the +// Resolver interface. This is useful when you want to add additional endpoint +// resolving logic, or stub out specific endpoints with custom values. +type EndpointResolverFunc func(service, region string) (Endpoint, error) + +// ResolveEndpoint calls EndpointResolverFunc returning the endpoint, or error. +func (fn EndpointResolverFunc) ResolveEndpoint(service, region string) (Endpoint, error) { + return fn(service, region) +} + +// ResolveWithEndpoint allows a static Resolved Endpoint to be used as an endpoint resolver +type ResolveWithEndpoint Endpoint + +// ResolveWithEndpointURL allows a static URL to be used as a endpoint resolver. +func ResolveWithEndpointURL(url string) ResolveWithEndpoint { + return ResolveWithEndpoint(Endpoint{URL: url}) +} + +// ResolveEndpoint returns the static endpoint. +func (v ResolveWithEndpoint) ResolveEndpoint(service, region string) (Endpoint, error) { + e := Endpoint(v) + e.SigningRegion = region + return e, nil +} + +// Endpoint represents the endpoint a service client should make requests to. +type Endpoint struct { + // The URL of the endpoint. + URL string + + // The service name that should be used for signing the requests to the + // endpoint. + SigningName string + + // The region that should be used for signing the request to the endpoint. + SigningRegion string + + // States that the signing name for this endpoint was derived from metadata + // passed in, but was not explicitly modeled. + SigningNameDerived bool + + // The signing method that should be used for signign the requests to the + // endpoint. + SigningMethod string +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/errors.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/errors.go new file mode 100644 index 0000000..c567137 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/aws/errors.go @@ -0,0 +1,17 @@ +package aws + +import "github.com/aws/aws-sdk-go-v2/aws/awserr" + +var ( + // ErrMissingRegion is an error that is returned if region configuration is + // not found. + // + // @readonly + ErrMissingRegion = awserr.New("MissingRegion", "could not find region configuration", nil) + + // ErrMissingEndpoint is an error that is returned if an endpoint cannot be + // resolved for a service. + // + // @readonly + ErrMissingEndpoint = awserr.New("MissingEndpoint", "'Endpoint' configuration is required for this service", nil) +) diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/handlers.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/handlers.go new file mode 100644 index 0000000..be2b453 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/aws/handlers.go @@ -0,0 +1,256 @@ +package aws + +import ( + "fmt" + "strings" +) + +// A Handlers provides a collection of request handlers for various +// stages of handling requests. +type Handlers struct { + Validate HandlerList + Build HandlerList + Sign HandlerList + Send HandlerList + ValidateResponse HandlerList + Unmarshal HandlerList + UnmarshalMeta HandlerList + UnmarshalError HandlerList + Retry HandlerList + AfterRetry HandlerList + Complete HandlerList +} + +// Copy returns of this handler's lists. +func (h *Handlers) Copy() Handlers { + return Handlers{ + Validate: h.Validate.copy(), + Build: h.Build.copy(), + Sign: h.Sign.copy(), + Send: h.Send.copy(), + ValidateResponse: h.ValidateResponse.copy(), + Unmarshal: h.Unmarshal.copy(), + UnmarshalError: h.UnmarshalError.copy(), + UnmarshalMeta: h.UnmarshalMeta.copy(), + Retry: h.Retry.copy(), + AfterRetry: h.AfterRetry.copy(), + Complete: h.Complete.copy(), + } +} + +// Clear removes callback functions for all handlers +func (h *Handlers) Clear() { + h.Validate.Clear() + h.Build.Clear() + h.Send.Clear() + h.Sign.Clear() + h.Unmarshal.Clear() + h.UnmarshalMeta.Clear() + h.UnmarshalError.Clear() + h.ValidateResponse.Clear() + h.Retry.Clear() + h.AfterRetry.Clear() + h.Complete.Clear() +} + +// A HandlerListRunItem represents an entry in the HandlerList which +// is being run. +type HandlerListRunItem struct { + Index int + Handler NamedHandler + Request *Request +} + +// A HandlerList manages zero or more handlers in a list. +type HandlerList struct { + list []NamedHandler + + // Called after each request handler in the list is called. If set + // and the func returns true the HandlerList will continue to iterate + // over the request handlers. If false is returned the HandlerList + // will stop iterating. + // + // Should be used if extra logic to be performed between each handler + // in the list. This can be used to terminate a list's iteration + // based on a condition such as error like, HandlerListStopOnError. + // Or for logging like HandlerListLogItem. + AfterEachFn func(item HandlerListRunItem) bool +} + +// A NamedHandler is a struct that contains a name and function callback. +type NamedHandler struct { + Name string + Fn func(*Request) +} + +// copy creates a copy of the handler list. +func (l *HandlerList) copy() HandlerList { + n := HandlerList{ + AfterEachFn: l.AfterEachFn, + } + if len(l.list) == 0 { + return n + } + + n.list = append(make([]NamedHandler, 0, len(l.list)), l.list...) + return n +} + +// Clear clears the handler list. +func (l *HandlerList) Clear() { + l.list = l.list[0:0] +} + +// Len returns the number of handlers in the list. +func (l *HandlerList) Len() int { + return len(l.list) +} + +// PushBack pushes handler f to the back of the handler list. +func (l *HandlerList) PushBack(f func(*Request)) { + l.PushBackNamed(NamedHandler{"__anonymous", f}) +} + +// PushBackNamed pushes named handler f to the back of the handler list. +func (l *HandlerList) PushBackNamed(n NamedHandler) { + if cap(l.list) == 0 { + l.list = make([]NamedHandler, 0, 5) + } + l.list = append(l.list, n) +} + +// PushFront pushes handler f to the front of the handler list. +func (l *HandlerList) PushFront(f func(*Request)) { + l.PushFrontNamed(NamedHandler{"__anonymous", f}) +} + +// PushFrontNamed pushes named handler f to the front of the handler list. +func (l *HandlerList) PushFrontNamed(n NamedHandler) { + if cap(l.list) == len(l.list) { + // Allocating new list required + l.list = append([]NamedHandler{n}, l.list...) + } else { + // Enough room to prepend into list. + l.list = append(l.list, NamedHandler{}) + copy(l.list[1:], l.list) + l.list[0] = n + } +} + +// Remove removes a NamedHandler n +func (l *HandlerList) Remove(n NamedHandler) { + l.RemoveByName(n.Name) +} + +// RemoveByName removes a NamedHandler by name. +func (l *HandlerList) RemoveByName(name string) { + for i := 0; i < len(l.list); i++ { + m := l.list[i] + if m.Name == name { + // Shift array preventing creating new arrays + copy(l.list[i:], l.list[i+1:]) + l.list[len(l.list)-1] = NamedHandler{} + l.list = l.list[:len(l.list)-1] + + // decrement list so next check to length is correct + i-- + } + } +} + +// SwapNamed will swap out any existing handlers with the same name as the +// passed in NamedHandler returning true if handlers were swapped. False is +// returned otherwise. +func (l *HandlerList) SwapNamed(n NamedHandler) (swapped bool) { + for i := 0; i < len(l.list); i++ { + if l.list[i].Name == n.Name { + l.list[i].Fn = n.Fn + swapped = true + } + } + + return swapped +} + +// SetBackNamed will replace the named handler if it exists in the handler list. +// If the handler does not exist the handler will be added to the end of the list. +func (l *HandlerList) SetBackNamed(n NamedHandler) { + if !l.SwapNamed(n) { + l.PushBackNamed(n) + } +} + +// SetFrontNamed will replace the named handler if it exists in the handler list. +// If the handler does not exist the handler will be added to the beginning of +// the list. +func (l *HandlerList) SetFrontNamed(n NamedHandler) { + if !l.SwapNamed(n) { + l.PushFrontNamed(n) + } +} + +// Run executes all handlers in the list with a given request object. +func (l *HandlerList) Run(r *Request) { + for i, h := range l.list { + h.Fn(r) + item := HandlerListRunItem{ + Index: i, Handler: h, Request: r, + } + if l.AfterEachFn != nil && !l.AfterEachFn(item) { + return + } + } +} + +// HandlerListLogItem logs the request handler and the state of the +// request's Error value. Always returns true to continue iterating +// request handlers in a HandlerList. +func HandlerListLogItem(item HandlerListRunItem) bool { + if item.Request.Config.Logger == nil { + return true + } + item.Request.Config.Logger.Log("DEBUG: RequestHandler", + item.Index, item.Handler.Name, item.Request.Error) + + return true +} + +// HandlerListStopOnError returns false to stop the HandlerList iterating +// over request handlers if Request.Error is not nil. True otherwise +// to continue iterating. +func HandlerListStopOnError(item HandlerListRunItem) bool { + return item.Request.Error == nil +} + +// WithAppendUserAgent will add a string to the user agent prefixed with a +// single white space. +func WithAppendUserAgent(s string) Option { + return func(r *Request) { + r.Handlers.Build.PushBack(func(r2 *Request) { + AddToUserAgent(r, s) + }) + } +} + +// MakeAddToUserAgentHandler will add the name/version pair to the User-Agent request +// header. If the extra parameters are provided they will be added as metadata to the +// name/version pair resulting in the following format. +// "name/version (extra0; extra1; ...)" +// The user agent part will be concatenated with this current request's user agent string. +func MakeAddToUserAgentHandler(name, version string, extra ...string) func(*Request) { + ua := fmt.Sprintf("%s/%s", name, version) + if len(extra) > 0 { + ua += fmt.Sprintf(" (%s)", strings.Join(extra, "; ")) + } + return func(r *Request) { + AddToUserAgent(r, ua) + } +} + +// MakeAddToUserAgentFreeFormHandler adds the input to the User-Agent request header. +// The input string will be concatenated with the current request's user agent string. +func MakeAddToUserAgentFreeFormHandler(s string) func(*Request) { + return func(r *Request) { + AddToUserAgent(r, s) + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/http_request.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/http_request.go new file mode 100644 index 0000000..40dfe40 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/aws/http_request.go @@ -0,0 +1,24 @@ +package aws + +import ( + "io" + "net/http" + "net/url" +) + +func copyHTTPRequest(r *http.Request, body io.ReadCloser) *http.Request { + req := new(http.Request) + *req = *r + req.URL = &url.URL{} + *req.URL = *r.URL + req.Body = body + + req.Header = http.Header{} + for k, v := range r.Header { + for _, vv := range v { + req.Header.Add(k, vv) + } + } + + return req +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/jsonvalue.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/jsonvalue.go new file mode 100644 index 0000000..91a6f27 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/aws/jsonvalue.go @@ -0,0 +1,12 @@ +package aws + +// JSONValue is a representation of a grab bag type that will be marshaled +// into a json string. This type can be used just like any other map. +// +// Example: +// +// values := aws.JSONValue{ +// "Foo": "Bar", +// } +// values["Baz"] = "Qux" +type JSONValue map[string]interface{} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/logger.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/logger.go new file mode 100644 index 0000000..189e520 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/aws/logger.go @@ -0,0 +1,97 @@ +package aws + +import ( + "log" + "os" +) + +// A LogLevel defines the level logging should be performed at. Used to instruct +// the SDK which statements should be logged. +type LogLevel uint + +// Matches returns true if the v LogLevel is enabled by this LogLevel. Should be +// used with logging sub levels. Is safe to use on nil value LogLevelTypes. If +// LogLevel is nil, will default to LogOff comparison. +func (l LogLevel) Matches(v LogLevel) bool { + return l&v == v +} + +// AtLeast returns true if this LogLevel is at least high enough to satisfies v. +// Is safe to use on nil value LogLevelTypes. If LogLevel is nil, will default +// to LogOff comparison. +func (l LogLevel) AtLeast(v LogLevel) bool { + return l >= v +} + +const ( + // LogOff states that no logging should be performed by the SDK. This is the + // default state of the SDK, and should be use to disable all logging. + LogOff LogLevel = iota * 0x1000 + + // LogDebug state that debug output should be logged by the SDK. This should + // be used to inspect request made and responses received. + LogDebug +) + +// Debug Logging Sub Levels +const ( + // LogDebugWithSigning states that the SDK should log request signing and + // presigning events. This should be used to log the signing details of + // requests for debugging. Will also enable LogDebug. + LogDebugWithSigning LogLevel = LogDebug | (1 << iota) + + // LogDebugWithHTTPBody states the SDK should log HTTP request and response + // HTTP bodys in addition to the headers and path. This should be used to + // see the body content of requests and responses made while using the SDK + // Will also enable LogDebug. + LogDebugWithHTTPBody + + // LogDebugWithRequestRetries states the SDK should log when service requests will + // be retried. This should be used to log when you want to log when service + // requests are being retried. Will also enable LogDebug. + LogDebugWithRequestRetries + + // LogDebugWithRequestErrors states the SDK should log when service requests fail + // to build, send, validate, or unmarshal. + LogDebugWithRequestErrors +) + +// A Logger is a minimalistic interface for the SDK to log messages to. Should +// be used to provide custom logging writers for the SDK to use. +type Logger interface { + Log(...interface{}) +} + +// A LoggerFunc is a convenience type to convert a function taking a variadic +// list of arguments and wrap it so the Logger interface can be used. +// +// Example: +// s3.New(sess, &aws.Config{Logger: aws.LoggerFunc(func(args ...interface{}) { +// fmt.Fprintln(os.Stdout, args...) +// })}) +type LoggerFunc func(...interface{}) + +// Log calls the wrapped function with the arguments provided +func (f LoggerFunc) Log(args ...interface{}) { + f(args...) +} + +// NewDefaultLogger returns a Logger which will write log messages to stdout, and +// use same formatting runes as the stdlib log.Logger +// +// TODO remove, moved to default pkg +func NewDefaultLogger() Logger { + return &defaultLogger{ + logger: log.New(os.Stdout, "", log.LstdFlags), + } +} + +// A defaultLogger provides a minimalistic logger satisfying the Logger interface. +type defaultLogger struct { + logger *log.Logger +} + +// Log logs the parameters to the stdlib logger. See log.Println. +func (l defaultLogger) Log(args ...interface{}) { + l.logger.Println(args...) +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/offset_reader.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/offset_reader.go new file mode 100644 index 0000000..cb4614c --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/aws/offset_reader.go @@ -0,0 +1,58 @@ +package aws + +import ( + "io" + "sync" +) + +// offsetReader is a thread-safe io.ReadCloser to prevent racing +// with retrying requests +type offsetReader struct { + buf io.ReadSeeker + lock sync.Mutex + closed bool +} + +func newOffsetReader(buf io.ReadSeeker, offset int64) *offsetReader { + reader := &offsetReader{} + buf.Seek(offset, 0) + + reader.buf = buf + return reader +} + +// Close will close the instance of the offset reader's access to +// the underlying io.ReadSeeker. +func (o *offsetReader) Close() error { + o.lock.Lock() + defer o.lock.Unlock() + o.closed = true + return nil +} + +// Read is a thread-safe read of the underlying io.ReadSeeker +func (o *offsetReader) Read(p []byte) (int, error) { + o.lock.Lock() + defer o.lock.Unlock() + + if o.closed { + return 0, io.EOF + } + + return o.buf.Read(p) +} + +// Seek is a thread-safe seeking operation. +func (o *offsetReader) Seek(offset int64, whence int) (int64, error) { + o.lock.Lock() + defer o.lock.Unlock() + + return o.buf.Seek(offset, whence) +} + +// CloseAndCopy will return a new offsetReader with a copy of the old buffer +// and close the old buffer. +func (o *offsetReader) CloseAndCopy(offset int64) *offsetReader { + o.Close() + return newOffsetReader(o.buf, offset) +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/request.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/request.go new file mode 100644 index 0000000..b180eb3 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/aws/request.go @@ -0,0 +1,587 @@ +package aws + +import ( + "bytes" + "fmt" + "io" + "net" + "net/http" + "net/url" + "reflect" + "strings" + "time" + + "github.com/aws/aws-sdk-go-v2/aws/awserr" +) + +const ( + // ErrCodeSerialization is the serialization error code that is received + // during protocol unmarshaling. + ErrCodeSerialization = "SerializationError" + + // ErrCodeRead is an error that is returned during HTTP reads. + ErrCodeRead = "ReadError" + + // ErrCodeResponseTimeout is the connection timeout error that is received + // during body reads. + ErrCodeResponseTimeout = "ResponseTimeout" + + // ErrCodeRequestCanceled is the error code that will be returned by an + // API request that was canceled. Requests given a Context may + // return this error when canceled. + ErrCodeRequestCanceled = "RequestCanceled" +) + +// A Request is the service request to be made. +type Request struct { + Config Config + Metadata Metadata + Handlers Handlers + + Retryer + Time time.Time + ExpireTime time.Duration + Operation *Operation + HTTPRequest *http.Request + HTTPResponse *http.Response + Body io.ReadSeeker + BodyStart int64 // offset from beginning of Body that the request body starts + Params interface{} + Error error + Data interface{} + RequestID string + RetryCount int + Retryable *bool + RetryDelay time.Duration + NotHoist bool + SignedHeaderVals http.Header + LastSignedAt time.Time + DisableFollowRedirects bool + + context Context + + built bool + + // Need to persist an intermediate body between the input Body and HTTP + // request body because the HTTP Client's transport can maintain a reference + // to the HTTP request's body after the client has returned. This value is + // safe to use concurrently and wrap the input Body for each HTTP request. + safeBody *offsetReader +} + +// An Operation is the service API operation to be made. +type Operation struct { + Name string + HTTPMethod string + HTTPPath string + *Paginator + + BeforePresignFn func(r *Request) error +} + +// New returns a new Request pointer for the service API +// operation and parameters. +// +// Params is any value of input parameters to be the request payload. +// Data is pointer value to an object which the request's response +// payload will be deserialized to. +func New(cfg Config, metadata Metadata, handlers Handlers, + retryer Retryer, operation *Operation, params interface{}, data interface{}) *Request { + + // TODO improve this experiance for config copy? + cfg = cfg.Copy() + + method := operation.HTTPMethod + if method == "" { + method = "POST" + } + + httpReq, _ := http.NewRequest(method, "", nil) + + // TODO need better way of handling this error... NewRequest should return error. + endpoint, err := cfg.EndpointResolver.ResolveEndpoint(metadata.ServiceName, cfg.Region) + if err == nil { + // TODO so ugly + metadata.Endpoint = endpoint.URL + if len(endpoint.SigningName) > 0 && !endpoint.SigningNameDerived { + metadata.SigningName = endpoint.SigningName + } + if len(endpoint.SigningRegion) > 0 { + metadata.SigningRegion = endpoint.SigningRegion + } + + httpReq.URL, err = url.Parse(endpoint.URL + operation.HTTPPath) + if err != nil { + httpReq.URL = &url.URL{} + err = awserr.New("InvalidEndpointURL", "invalid endpoint uri", err) + } + } + + r := &Request{ + Config: cfg, + Metadata: metadata, + Handlers: handlers.Copy(), + + Retryer: retryer, + Time: time.Now(), + ExpireTime: 0, + Operation: operation, + HTTPRequest: httpReq, + Body: nil, + Params: params, + Error: err, + Data: data, + } + r.SetBufferBody([]byte{}) + + return r +} + +// A Option is a functional option that can augment or modify a request when +// using a WithContext API operation method. +type Option func(*Request) + +// WithGetResponseHeader builds a request Option which will retrieve a single +// header value from the HTTP Response. If there are multiple values for the +// header key use WithGetResponseHeaders instead to access the http.Header +// map directly. The passed in val pointer must be non-nil. +// +// This Option can be used multiple times with a single API operation. +// +// var id2, versionID string +// svc.PutObjectWithContext(ctx, params, +// request.WithGetResponseHeader("x-amz-id-2", &id2), +// request.WithGetResponseHeader("x-amz-version-id", &versionID), +// ) +func WithGetResponseHeader(key string, val *string) Option { + return func(r *Request) { + r.Handlers.Complete.PushBack(func(req *Request) { + *val = req.HTTPResponse.Header.Get(key) + }) + } +} + +// WithGetResponseHeaders builds a request Option which will retrieve the +// headers from the HTTP response and assign them to the passed in headers +// variable. The passed in headers pointer must be non-nil. +// +// var headers http.Header +// svc.PutObjectWithContext(ctx, params, request.WithGetResponseHeaders(&headers)) +func WithGetResponseHeaders(headers *http.Header) Option { + return func(r *Request) { + r.Handlers.Complete.PushBack(func(req *Request) { + *headers = req.HTTPResponse.Header + }) + } +} + +// WithLogLevel is a request option that will set the request to use a specific +// log level when the request is made. +// +// svc.PutObjectWithContext(ctx, params, request.WithLogLevel(LogDebugWithHTTPBody) +func WithLogLevel(l LogLevel) Option { + return func(r *Request) { + r.Config.LogLevel = l + } +} + +// ApplyOptions will apply each option to the request calling them in the order +// the were provided. +func (r *Request) ApplyOptions(opts ...Option) { + for _, opt := range opts { + opt(r) + } +} + +// Context will always returns a non-nil context. If Request does not have a +// context BackgroundContext will be returned. +func (r *Request) Context() Context { + if r.context != nil { + return r.context + } + return BackgroundContext() +} + +// SetContext adds a Context to the current request that can be used to cancel +// a in-flight request. The Context value must not be nil, or this method will +// panic. +// +// Unlike http.Request.WithContext, SetContext does not return a copy of the +// Request. It is not safe to use use a single Request value for multiple +// requests. A new Request should be created for each API operation request. +// +// Go 1.6 and below: +// The http.Request's Cancel field will be set to the Done() value of +// the context. This will overwrite the Cancel field's value. +// +// Go 1.7 and above: +// The http.Request.WithContext will be used to set the context on the underlying +// http.Request. This will create a shallow copy of the http.Request. The SDK +// may create sub contexts in the future for nested requests such as retries. +func (r *Request) SetContext(ctx Context) { + if ctx == nil { + panic("context cannot be nil") + } + setRequestContext(r, ctx) +} + +// WillRetry returns if the request's can be retried. +func (r *Request) WillRetry() bool { + return r.Error != nil && BoolValue(r.Retryable) && r.RetryCount < r.MaxRetries() +} + +// ParamsFilled returns if the request's parameters have been populated +// and the parameters are valid. False is returned if no parameters are +// provided or invalid. +func (r *Request) ParamsFilled() bool { + return r.Params != nil && reflect.ValueOf(r.Params).Elem().IsValid() +} + +// SetBufferBody will set the request's body bytes that will be sent to +// the service API. +func (r *Request) SetBufferBody(buf []byte) { + r.SetReaderBody(bytes.NewReader(buf)) +} + +// SetStringBody sets the body of the request to be backed by a string. +func (r *Request) SetStringBody(s string) { + r.SetReaderBody(strings.NewReader(s)) +} + +// SetReaderBody will set the request's body reader. +func (r *Request) SetReaderBody(reader io.ReadSeeker) { + r.Body = reader + r.ResetBody() +} + +// Presign returns the request's signed URL. Error will be returned +// if the signing fails. +func (r *Request) Presign(expireTime time.Duration) (string, error) { + r.ExpireTime = expireTime + r.NotHoist = false + + if r.Operation.BeforePresignFn != nil { + r = r.copy() + err := r.Operation.BeforePresignFn(r) + if err != nil { + return "", err + } + } + + r.Sign() + if r.Error != nil { + return "", r.Error + } + return r.HTTPRequest.URL.String(), nil +} + +// PresignRequest behaves just like presign, with the addition of returning a +// set of headers that were signed. +// +// Returns the URL string for the API operation with signature in the query string, +// and the HTTP headers that were included in the signature. These headers must +// be included in any HTTP request made with the presigned URL. +// +// To prevent hoisting any headers to the query string set NotHoist to true on +// this Request value prior to calling PresignRequest. +func (r *Request) PresignRequest(expireTime time.Duration) (string, http.Header, error) { + r.ExpireTime = expireTime + r.Sign() + if r.Error != nil { + return "", nil, r.Error + } + return r.HTTPRequest.URL.String(), r.SignedHeaderVals, nil +} + +func debugLogReqError(r *Request, stage string, retrying bool, err error) { + if !r.Config.LogLevel.Matches(LogDebugWithRequestErrors) { + return + } + + retryStr := "not retrying" + if retrying { + retryStr = "will retry" + } + + r.Config.Logger.Log(fmt.Sprintf("DEBUG: %s %s/%s failed, %s, error %v", + stage, r.Metadata.ServiceName, r.Operation.Name, retryStr, err)) +} + +// Build will build the request's object so it can be signed and sent +// to the service. Build will also validate all the request's parameters. +// Anny additional build Handlers set on this request will be run +// in the order they were set. +// +// The request will only be built once. Multiple calls to build will have +// no effect. +// +// If any Validate or Build errors occur the build will stop and the error +// which occurred will be returned. +func (r *Request) Build() error { + if !r.built { + r.Handlers.Validate.Run(r) + if r.Error != nil { + debugLogReqError(r, "Validate Request", false, r.Error) + return r.Error + } + r.Handlers.Build.Run(r) + if r.Error != nil { + debugLogReqError(r, "Build Request", false, r.Error) + return r.Error + } + r.built = true + } + + return r.Error +} + +// Sign will sign the request returning error if errors are encountered. +// +// Send will build the request prior to signing. All Sign Handlers will +// be executed in the order they were set. +func (r *Request) Sign() error { + r.Build() + if r.Error != nil { + debugLogReqError(r, "Build Request", false, r.Error) + return r.Error + } + + r.Handlers.Sign.Run(r) + return r.Error +} + +func (r *Request) getNextRequestBody() (io.ReadCloser, error) { + if r.safeBody != nil { + r.safeBody.Close() + } + + r.safeBody = newOffsetReader(r.Body, r.BodyStart) + + // Go 1.8 tightened and clarified the rules code needs to use when building + // requests with the http package. Go 1.8 removed the automatic detection + // of if the Request.Body was empty, or actually had bytes in it. The SDK + // always sets the Request.Body even if it is empty and should not actually + // be sent. This is incorrect. + // + // Go 1.8 did add a http.NoBody value that the SDK can use to tell the http + // client that the request really should be sent without a body. The + // Request.Body cannot be set to nil, which is preferable, because the + // field is exported and could introduce nil pointer dereferences for users + // of the SDK if they used that field. + // + // Related golang/go#18257 + l, err := computeBodyLength(r.Body) + if err != nil { + return nil, awserr.New(ErrCodeSerialization, "failed to compute request body size", err) + } + + var body io.ReadCloser + if l == 0 { + body = NoBody + } else if l > 0 { + body = r.safeBody + } else { + // Hack to prevent sending bodies for methods where the body + // should be ignored by the server. Sending bodies on these + // methods without an associated ContentLength will cause the + // request to socket timeout because the server does not handle + // Transfer-Encoding: chunked bodies for these methods. + // + // This would only happen if a ReaderSeekerCloser was used with + // a io.Reader that was not also an io.Seeker. + switch r.Operation.HTTPMethod { + case "GET", "HEAD", "DELETE": + body = NoBody + default: + body = r.safeBody + } + } + + return body, nil +} + +// Attempts to compute the length of the body of the reader using the +// io.Seeker interface. If the value is not seekable because of being +// a ReaderSeekerCloser without an unerlying Seeker -1 will be returned. +// If no error occurs the length of the body will be returned. +func computeBodyLength(r io.ReadSeeker) (int64, error) { + seekable := true + // Determine if the seeker is actually seekable. ReaderSeekerCloser + // hides the fact that a io.Readers might not actually be seekable. + switch v := r.(type) { + case ReaderSeekerCloser: + seekable = v.IsSeeker() + case *ReaderSeekerCloser: + seekable = v.IsSeeker() + } + if !seekable { + return -1, nil + } + + curOffset, err := r.Seek(0, 1) + if err != nil { + return 0, err + } + + endOffset, err := r.Seek(0, 2) + if err != nil { + return 0, err + } + + _, err = r.Seek(curOffset, 0) + if err != nil { + return 0, err + } + + return endOffset - curOffset, nil +} + +// GetBody will return an io.ReadSeeker of the Request's underlying +// input body with a concurrency safe wrapper. +func (r *Request) GetBody() io.ReadSeeker { + return r.safeBody +} + +// Send will send the request returning error if errors are encountered. +// +// Send will sign the request prior to sending. All Send Handlers will +// be executed in the order they were set. +// +// Canceling a request is non-deterministic. If a request has been canceled, +// then the transport will choose, randomly, one of the state channels during +// reads or getting the connection. +// +// readLoop() and getConn(req *Request, cm connectMethod) +// https://github.com/golang/go/blob/master/src/net/http/transport.go +// +// Send will not close the request.Request's body. +func (r *Request) Send() error { + defer func() { + // Regardless of success or failure of the request trigger the Complete + // request handlers. + r.Handlers.Complete.Run(r) + }() + + for { + if BoolValue(r.Retryable) { + if r.Config.LogLevel.Matches(LogDebugWithRequestRetries) { + r.Config.Logger.Log(fmt.Sprintf("DEBUG: Retrying Request %s/%s, attempt %d", + r.Metadata.ServiceName, r.Operation.Name, r.RetryCount)) + } + + // The previous http.Request will have a reference to the r.Body + // and the HTTP Client's Transport may still be reading from + // the request's body even though the Client's Do returned. + r.HTTPRequest = copyHTTPRequest(r.HTTPRequest, nil) + r.ResetBody() + + // Closing response body to ensure that no response body is leaked + // between retry attempts. + if r.HTTPResponse != nil && r.HTTPResponse.Body != nil { + r.HTTPResponse.Body.Close() + } + } + + r.Sign() + if r.Error != nil { + return r.Error + } + + r.Retryable = nil + + r.Handlers.Send.Run(r) + if r.Error != nil { + if !shouldRetryCancel(r) { + return r.Error + } + + err := r.Error + r.Handlers.Retry.Run(r) + r.Handlers.AfterRetry.Run(r) + if r.Error != nil { + debugLogReqError(r, "Send Request", false, err) + return r.Error + } + debugLogReqError(r, "Send Request", true, err) + continue + } + r.Handlers.UnmarshalMeta.Run(r) + r.Handlers.ValidateResponse.Run(r) + if r.Error != nil { + r.Handlers.UnmarshalError.Run(r) + err := r.Error + + r.Handlers.Retry.Run(r) + r.Handlers.AfterRetry.Run(r) + if r.Error != nil { + debugLogReqError(r, "Validate Response", false, err) + return r.Error + } + debugLogReqError(r, "Validate Response", true, err) + continue + } + + r.Handlers.Unmarshal.Run(r) + if r.Error != nil { + err := r.Error + r.Handlers.Retry.Run(r) + r.Handlers.AfterRetry.Run(r) + if r.Error != nil { + debugLogReqError(r, "Unmarshal Response", false, err) + return r.Error + } + debugLogReqError(r, "Unmarshal Response", true, err) + continue + } + + break + } + + return nil +} + +// copy will copy a request which will allow for local manipulation of the +// request. +func (r *Request) copy() *Request { + req := &Request{} + *req = *r + req.Handlers = r.Handlers.Copy() + op := *r.Operation + req.Operation = &op + return req +} + +// AddToUserAgent adds the string to the end of the request's current user agent. +func AddToUserAgent(r *Request, s string) { + curUA := r.HTTPRequest.Header.Get("User-Agent") + if len(curUA) > 0 { + s = curUA + " " + s + } + r.HTTPRequest.Header.Set("User-Agent", s) +} + +func shouldRetryCancel(r *Request) bool { + awsErr, ok := r.Error.(awserr.Error) + timeoutErr := false + errStr := r.Error.Error() + if ok { + if awsErr.Code() == ErrCodeRequestCanceled { + return false + } + err := awsErr.OrigErr() + netErr, netOK := err.(net.Error) + timeoutErr = netOK && netErr.Temporary() + if urlErr, ok := err.(*url.Error); !timeoutErr && ok { + errStr = urlErr.Err.Error() + } + } + + // There can be two types of canceled errors here. + // The first being a net.Error and the other being an error. + // If the request was timed out, we want to continue the retry + // process. Otherwise, return the canceled error. + return timeoutErr || + (errStr != "net/http: request canceled" && + errStr != "net/http: request canceled while waiting for connection") + +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/request_1_7.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/request_1_7.go new file mode 100644 index 0000000..6db88c8 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/aws/request_1_7.go @@ -0,0 +1,39 @@ +// +build !go1.8 + +package aws + +import "io" + +// NoBody is an io.ReadCloser with no bytes. Read always returns EOF +// and Close always returns nil. It can be used in an outgoing client +// request to explicitly signal that a request has zero bytes. +// An alternative, however, is to simply set Request.Body to nil. +// +// Copy of Go 1.8 NoBody type from net/http/http.go +type noBody struct{} + +func (noBody) Read([]byte) (int, error) { return 0, io.EOF } +func (noBody) Close() error { return nil } +func (noBody) WriteTo(io.Writer) (int64, error) { return 0, nil } + +// NoBody is an empty reader that will trigger the Go HTTP client to not include +// and body in the HTTP request. +var NoBody = noBody{} + +// ResetBody rewinds the request body back to its starting position, and +// set's the HTTP Request body reference. When the body is read prior +// to being sent in the HTTP request it will need to be rewound. +// +// ResetBody will automatically be called by the SDK's build handler, but if +// the request is being used directly ResetBody must be called before the request +// is Sent. SetStringBody, SetBufferBody, and SetReaderBody will automatically +// call ResetBody. +func (r *Request) ResetBody() { + body, err := r.getNextRequestBody() + if err != nil { + r.Error = err + return + } + + r.HTTPRequest.Body = body +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/request_1_8.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/request_1_8.go new file mode 100644 index 0000000..ad81c3d --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/aws/request_1_8.go @@ -0,0 +1,33 @@ +// +build go1.8 + +package aws + +import ( + "net/http" +) + +// NoBody is a http.NoBody reader instructing Go HTTP client to not include +// and body in the HTTP request. +var NoBody = http.NoBody + +// ResetBody rewinds the request body back to its starting position, and +// set's the HTTP Request body reference. When the body is read prior +// to being sent in the HTTP request it will need to be rewound. +// +// ResetBody will automatically be called by the SDK's build handler, but if +// the request is being used directly ResetBody must be called before the request +// is Sent. SetStringBody, SetBufferBody, and SetReaderBody will automatically +// call ResetBody. +// +// Will also set the Go 1.8's http.Request.GetBody member to allow retrying +// PUT/POST redirects. +func (r *Request) ResetBody() { + body, err := r.getNextRequestBody() + if err != nil { + r.Error = err + return + } + + r.HTTPRequest.Body = body + r.HTTPRequest.GetBody = r.getNextRequestBody +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/request_context.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/request_context.go new file mode 100644 index 0000000..19fa4fb --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/aws/request_context.go @@ -0,0 +1,12 @@ +// +build go1.7 + +package aws + +// setContext updates the Request to use the passed in context for cancellation. +// Context will also be used for request retry delay. +// +// Creates shallow copy of the http.Request with the WithContext method. +func setRequestContext(r *Request, ctx Context) { + r.context = ctx + r.HTTPRequest = r.HTTPRequest.WithContext(ctx) +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/request_context_1_6.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/request_context_1_6.go new file mode 100644 index 0000000..0b333d2 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/aws/request_context_1_6.go @@ -0,0 +1,12 @@ +// +build !go1.7 + +package aws + +// setContext updates the Request to use the passed in context for cancellation. +// Context will also be used for request retry delay. +// +// Creates shallow copy of the http.Request with the WithContext method. +func setRequestContext(r *Request, ctx Context) { + r.context = ctx + r.HTTPRequest.Cancel = ctx.Done() +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/request_pagination.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/request_pagination.go new file mode 100644 index 0000000..15594c9 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/aws/request_pagination.go @@ -0,0 +1,187 @@ +package aws + +import ( + "sync/atomic" + + "github.com/aws/aws-sdk-go-v2/internal/awsutil" +) + +// A Pager provides paginating of SDK API operations which are paginatable. +// Generally you should not use this type directly, but use the "Pages" API +// operations method to automatically perform pagination for you. Such as, +// "S3.ListObjectsPages", and "S3.ListObjectsPagesWithContext" methods. +// +// Pagier differs from a Paginator type in that pagination is the type that +// does the pagination between API operations, and Paginator defines the +// configuration that will be used per page request. +// +// for p.Next() { +// data := p.CurrentPage().(*s3.ListObjectsOutput) +// // process the page's data +// } +// return p.Err() +// +// See service client API operation Pages methods for examples how the SDK will +// use the Pager type. +type Pager struct { + // Function to return a Request value for each pagination request. + // Any configuration or handlers that need to be applied to the request + // prior to getting the next page should be done here before the request + // returned. + // + // NewRequest should always be built from the same API operations. It is + // undefined if different API operations are returned on subsequent calls. + NewRequest func() (*Request, error) + + started bool + nextTokens []interface{} + + err error + curPage interface{} +} + +// hasNextPage will return true if Pager is able to determine that the API +// operation has additional pages. False will be returned if there are no more +// pages remaining. +// +// Will always return true if Next has not been called yet. +func (p *Pager) hasNextPage() bool { + return !(p.started && len(p.nextTokens) == 0) +} + +// Err returns the error Pager encountered when retrieving the next page. +func (p *Pager) Err() error { + return p.err +} + +// CurrentPage returns the current page. Page should only be called after a successful +// call to Next. It is undefined what Page will return if Page is called after +// Next returns false. +func (p *Pager) CurrentPage() interface{} { + return p.curPage +} + +// Next will attempt to retrieve the next page for the API operation. When a page +// is retrieved true will be returned. If the page cannot be retrieved, or there +// are no more pages false will be returned. +// +// Use the Page method to retrieve the current page data. The data will need +// to be cast to the API operation's output type. +// +// Use the Err method to determine if an error occurred if Page returns false. +func (p *Pager) Next() bool { + if !p.hasNextPage() { + return false + } + + req, err := p.NewRequest() + if err != nil { + p.err = err + return false + } + + if p.started { + for i, intok := range req.Operation.InputTokens { + awsutil.SetValueAtPath(req.Params, intok, p.nextTokens[i]) + } + } + p.started = true + + err = req.Send() + if err != nil { + p.err = err + return false + } + + p.nextTokens = req.nextPageTokens() + p.curPage = req.Data + + return true +} + +// A Paginator is the configuration data that defines how an API operation +// should be paginated. This type is used by the API service models to define +// the generated pagination config for service APIs. +// +// The Pager type is what provides iterating between pages of an API. It +// is only used to store the token metadata the SDK should use for performing +// pagination. +type Paginator struct { + InputTokens []string + OutputTokens []string + LimitToken string + TruncationToken string +} + +// nextPageTokens returns the tokens to use when asking for the next page of data. +func (r *Request) nextPageTokens() []interface{} { + if r.Operation.Paginator == nil { + return nil + } + if r.Operation.TruncationToken != "" { + tr, _ := awsutil.ValuesAtPath(r.Data, r.Operation.TruncationToken) + if len(tr) == 0 { + return nil + } + + switch v := tr[0].(type) { + case *bool: + if !BoolValue(v) { + return nil + } + case bool: + if v == false { + return nil + } + } + } + + tokens := []interface{}{} + tokenAdded := false + for _, outToken := range r.Operation.OutputTokens { + vs, _ := awsutil.ValuesAtPath(r.Data, outToken) + + if len(vs) == 0 { + tokens = append(tokens, nil) + continue + } + v := vs[0] + + switch tv := v.(type) { + case *string: + if len(StringValue(tv)) == 0 { + tokens = append(tokens, nil) + continue + } + case string: + if len(tv) == 0 { + tokens = append(tokens, nil) + continue + } + } + + tokenAdded = true + tokens = append(tokens, v) + } + if !tokenAdded { + return nil + } + + return tokens +} + +// Ensure a deprecated item is only logged once instead of each time its used. +func logDeprecatedf(logger Logger, flag *int32, msg string) { + if logger == nil { + return + } + if atomic.CompareAndSwapInt32(flag, 0, 1) { + logger.Log(msg) + } +} + +var ( + logDeprecatedHasNextPage int32 + logDeprecatedNextPage int32 + logDeprecatedEachPage int32 +) diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/response.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/response.go new file mode 100644 index 0000000..ea7717b --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/aws/response.go @@ -0,0 +1,8 @@ +package aws + +// Response provides the response meta data for a SDK API request's response. +type Response struct { + // TODO these fields should be focused on response, not just embedded request value. + // Need refactor of request for this to be better. + Request *Request +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/retryer.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/retryer.go new file mode 100644 index 0000000..a71b969 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/aws/retryer.go @@ -0,0 +1,160 @@ +package aws + +import ( + "time" + + "github.com/aws/aws-sdk-go-v2/aws/awserr" +) + +// Retryer is an interface to control retry logic for a given service. +// The default implementation used by most services is the client.DefaultRetryer +// structure, which contains basic retry logic using exponential backoff. +type Retryer interface { + RetryRules(*Request) time.Duration + ShouldRetry(*Request) bool + MaxRetries() int +} + +// WithRetryer sets a config Retryer value to the given Config returning it +// for chaining. +func WithRetryer(cfg *Config, retryer Retryer) *Config { + cfg.Retryer = retryer + return cfg +} + +// retryableCodes is a collection of service response codes which are retry-able +// without any further action. +var retryableCodes = map[string]struct{}{ + "RequestError": {}, + "RequestTimeout": {}, + ErrCodeResponseTimeout: {}, + "RequestTimeoutException": {}, // Glacier's flavor of RequestTimeout +} + +var throttleCodes = map[string]struct{}{ + "ProvisionedThroughputExceededException": {}, + "Throttling": {}, + "ThrottlingException": {}, + "RequestLimitExceeded": {}, + "RequestThrottled": {}, + "TooManyRequestsException": {}, // Lambda functions + "PriorRequestNotComplete": {}, // Route53 +} + +// credsExpiredCodes is a collection of error codes which signify the credentials +// need to be refreshed. Expired tokens require refreshing of credentials, and +// resigning before the request can be retried. +var credsExpiredCodes = map[string]struct{}{ + "ExpiredToken": {}, + "ExpiredTokenException": {}, + "RequestExpired": {}, // EC2 Only +} + +func isCodeThrottle(code string) bool { + _, ok := throttleCodes[code] + return ok +} + +func isCodeRetryable(code string) bool { + if _, ok := retryableCodes[code]; ok { + return true + } + + return isCodeExpiredCreds(code) +} + +func isCodeExpiredCreds(code string) bool { + _, ok := credsExpiredCodes[code] + return ok +} + +var validParentCodes = map[string]struct{}{ + ErrCodeSerialization: {}, + ErrCodeRead: {}, +} + +type temporaryError interface { + Temporary() bool +} + +func isNestedErrorRetryable(parentErr awserr.Error) bool { + if parentErr == nil { + return false + } + + if _, ok := validParentCodes[parentErr.Code()]; !ok { + return false + } + + err := parentErr.OrigErr() + if err == nil { + return false + } + + if aerr, ok := err.(awserr.Error); ok { + return isCodeRetryable(aerr.Code()) + } + + if t, ok := err.(temporaryError); ok { + return t.Temporary() || isErrConnectionReset(err) + } + + return isErrConnectionReset(err) +} + +// IsErrorRetryable returns whether the error is retryable, based on its Code. +// Returns false if error is nil. +func IsErrorRetryable(err error) bool { + if err != nil { + if aerr, ok := err.(awserr.Error); ok { + return isCodeRetryable(aerr.Code()) || isNestedErrorRetryable(aerr) + } + } + return false +} + +// IsErrorThrottle returns whether the error is to be throttled based on its code. +// Returns false if error is nil. +func IsErrorThrottle(err error) bool { + if err != nil { + if aerr, ok := err.(awserr.Error); ok { + return isCodeThrottle(aerr.Code()) + } + } + return false +} + +// IsErrorExpiredCreds returns whether the error code is a credential expiry error. +// Returns false if error is nil. +func IsErrorExpiredCreds(err error) bool { + if err != nil { + if aerr, ok := err.(awserr.Error); ok { + return isCodeExpiredCreds(aerr.Code()) + } + } + return false +} + +// IsErrorRetryable returns whether the error is retryable, based on its Code. +// Returns false if the request has no Error set. +// +// Alias for the utility function IsErrorRetryable +func (r *Request) IsErrorRetryable() bool { + return IsErrorRetryable(r.Error) +} + +// IsErrorThrottle returns whether the error is to be throttled based on its code. +// Returns false if the request has no Error set +// +// Alias for the utility function IsErrorThrottle +func (r *Request) IsErrorThrottle() bool { + return IsErrorThrottle(r.Error) +} + +// IsErrorExpired returns whether the error code is a credential expiry error. +// Returns false if the request has no Error set. +// +// Alias for the utility function IsErrorExpiredCreds +func (r *Request) IsErrorExpired() bool { + return IsErrorExpiredCreds(r.Error) +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/v4/header_rules.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/v4/header_rules.go new file mode 100644 index 0000000..244c86d --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/v4/header_rules.go @@ -0,0 +1,82 @@ +package v4 + +import ( + "net/http" + "strings" +) + +// validator houses a set of rule needed for validation of a +// string value +type rules []rule + +// rule interface allows for more flexible rules and just simply +// checks whether or not a value adheres to that rule +type rule interface { + IsValid(value string) bool +} + +// IsValid will iterate through all rules and see if any rules +// apply to the value and supports nested rules +func (r rules) IsValid(value string) bool { + for _, rule := range r { + if rule.IsValid(value) { + return true + } + } + return false +} + +// mapRule generic rule for maps +type mapRule map[string]struct{} + +// IsValid for the map rule satisfies whether it exists in the map +func (m mapRule) IsValid(value string) bool { + _, ok := m[value] + return ok +} + +// whitelist is a generic rule for whitelisting +type whitelist struct { + rule +} + +// IsValid for whitelist checks if the value is within the whitelist +func (w whitelist) IsValid(value string) bool { + return w.rule.IsValid(value) +} + +// blacklist is a generic rule for blacklisting +type blacklist struct { + rule +} + +// IsValid for whitelist checks if the value is within the whitelist +func (b blacklist) IsValid(value string) bool { + return !b.rule.IsValid(value) +} + +type patterns []string + +// IsValid for patterns checks each pattern and returns if a match has +// been found +func (p patterns) IsValid(value string) bool { + for _, pattern := range p { + if strings.HasPrefix(http.CanonicalHeaderKey(value), pattern) { + return true + } + } + return false +} + +// inclusiveRules rules allow for rules to depend on one another +type inclusiveRules []rule + +// IsValid will return true if all rules are true +func (r inclusiveRules) IsValid(value string) bool { + for _, rule := range r { + if !rule.IsValid(value) { + return false + } + } + return true +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/v4/options.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/v4/options.go new file mode 100644 index 0000000..6aa2ed2 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/v4/options.go @@ -0,0 +1,7 @@ +package v4 + +// WithUnsignedPayload will enable and set the UnsignedPayload field to +// true of the signer. +func WithUnsignedPayload(v4 *Signer) { + v4.UnsignedPayload = true +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/v4/uri_path.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/v4/uri_path.go new file mode 100644 index 0000000..bd082e9 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/v4/uri_path.go @@ -0,0 +1,24 @@ +// +build go1.5 + +package v4 + +import ( + "net/url" + "strings" +) + +func getURIPath(u *url.URL) string { + var uri string + + if len(u.Opaque) > 0 { + uri = "/" + strings.Join(strings.Split(u.Opaque, "/")[3:], "/") + } else { + uri = u.EscapedPath() + } + + if len(uri) == 0 { + uri = "/" + } + + return uri +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/v4/v4.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/v4/v4.go new file mode 100644 index 0000000..ddbade6 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/v4/v4.go @@ -0,0 +1,755 @@ +// Package v4 implements signing for AWS V4 signer +// +// Provides request signing for request that need to be signed with +// AWS V4 Signatures. +// +// Standalone Signer +// +// Generally using the signer outside of the SDK should not require any additional +// logic when using Go v1.5 or higher. The signer does this by taking advantage +// of the URL.EscapedPath method. If your request URI requires additional escaping +// you many need to use the URL.Opaque to define what the raw URI should be sent +// to the service as. +// +// The signer will first check the URL.Opaque field, and use its value if set. +// The signer does require the URL.Opaque field to be set in the form of: +// +// "///" +// +// // e.g. +// "//example.com/some/path" +// +// The leading "//" and hostname are required or the URL.Opaque escaping will +// not work correctly. +// +// If URL.Opaque is not set the signer will fallback to the URL.EscapedPath() +// method and using the returned value. If you're using Go v1.4 you must set +// URL.Opaque if the URI path needs escaping. If URL.Opaque is not set with +// Go v1.5 the signer will fallback to URL.Path. +// +// AWS v4 signature validation requires that the canonical string's URI path +// element must be the URI escaped form of the HTTP request's path. +// http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html +// +// The Go HTTP client will perform escaping automatically on the request. Some +// of these escaping may cause signature validation errors because the HTTP +// request differs from the URI path or query that the signature was generated. +// https://golang.org/pkg/net/url/#URL.EscapedPath +// +// Because of this, it is recommended that when using the signer outside of the +// SDK that explicitly escaping the request prior to being signed is preferable, +// and will help prevent signature validation errors. This can be done by setting +// the URL.Opaque or URL.RawPath. The SDK will use URL.Opaque first and then +// call URL.EscapedPath() if Opaque is not set. +// +// If signing a request intended for HTTP2 server, and you're using Go 1.6.2 +// through 1.7.4 you should use the URL.RawPath as the pre-escaped form of the +// request URL. https://github.com/golang/go/issues/16847 points to a bug in +// Go pre 1.8 that fails to make HTTP2 requests using absolute URL in the HTTP +// message. URL.Opaque generally will force Go to make requests with absolute URL. +// URL.RawPath does not do this, but RawPath must be a valid escaping of Path +// or url.EscapedPath will ignore the RawPath escaping. +// +// Test `TestStandaloneSign` provides a complete example of using the signer +// outside of the SDK and pre-escaping the URI path. +package v4 + +import ( + "crypto/hmac" + "crypto/sha256" + "encoding/hex" + "fmt" + "io" + "io/ioutil" + "net/http" + "net/url" + "sort" + "strconv" + "strings" + "time" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/internal/sdk" + "github.com/aws/aws-sdk-go-v2/private/protocol/rest" +) + +const ( + authHeaderPrefix = "AWS4-HMAC-SHA256" + timeFormat = "20060102T150405Z" + shortTimeFormat = "20060102" + + // emptyStringSHA256 is a SHA256 of an empty string + emptyStringSHA256 = `e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855` +) + +var ignoredHeaders = rules{ + blacklist{ + mapRule{ + "Authorization": struct{}{}, + "User-Agent": struct{}{}, + "X-Amzn-Trace-Id": struct{}{}, + }, + }, +} + +// requiredSignedHeaders is a whitelist for build canonical headers. +var requiredSignedHeaders = rules{ + whitelist{ + mapRule{ + "Cache-Control": struct{}{}, + "Content-Disposition": struct{}{}, + "Content-Encoding": struct{}{}, + "Content-Language": struct{}{}, + "Content-Md5": struct{}{}, + "Content-Type": struct{}{}, + "Expires": struct{}{}, + "If-Match": struct{}{}, + "If-Modified-Since": struct{}{}, + "If-None-Match": struct{}{}, + "If-Unmodified-Since": struct{}{}, + "Range": struct{}{}, + "X-Amz-Acl": struct{}{}, + "X-Amz-Copy-Source": struct{}{}, + "X-Amz-Copy-Source-If-Match": struct{}{}, + "X-Amz-Copy-Source-If-Modified-Since": struct{}{}, + "X-Amz-Copy-Source-If-None-Match": struct{}{}, + "X-Amz-Copy-Source-If-Unmodified-Since": struct{}{}, + "X-Amz-Copy-Source-Range": struct{}{}, + "X-Amz-Copy-Source-Server-Side-Encryption-Customer-Algorithm": struct{}{}, + "X-Amz-Copy-Source-Server-Side-Encryption-Customer-Key": struct{}{}, + "X-Amz-Copy-Source-Server-Side-Encryption-Customer-Key-Md5": struct{}{}, + "X-Amz-Grant-Full-control": struct{}{}, + "X-Amz-Grant-Read": struct{}{}, + "X-Amz-Grant-Read-Acp": struct{}{}, + "X-Amz-Grant-Write": struct{}{}, + "X-Amz-Grant-Write-Acp": struct{}{}, + "X-Amz-Metadata-Directive": struct{}{}, + "X-Amz-Mfa": struct{}{}, + "X-Amz-Request-Payer": struct{}{}, + "X-Amz-Server-Side-Encryption": struct{}{}, + "X-Amz-Server-Side-Encryption-Aws-Kms-Key-Id": struct{}{}, + "X-Amz-Server-Side-Encryption-Customer-Algorithm": struct{}{}, + "X-Amz-Server-Side-Encryption-Customer-Key": struct{}{}, + "X-Amz-Server-Side-Encryption-Customer-Key-Md5": struct{}{}, + "X-Amz-Storage-Class": struct{}{}, + "X-Amz-Website-Redirect-Location": struct{}{}, + "X-Amz-Content-Sha256": struct{}{}, + }, + }, + patterns{"X-Amz-Meta-"}, +} + +// allowedHoisting is a whitelist for build query headers. The boolean value +// represents whether or not it is a pattern. +var allowedQueryHoisting = inclusiveRules{ + blacklist{requiredSignedHeaders}, + patterns{"X-Amz-"}, +} + +// Signer applies AWS v4 signing to given request. Use this to sign requests +// that need to be signed with AWS V4 Signatures. +type Signer struct { + // The authentication credentials the request will be signed against. + // This value must be set to sign requests. + Credentials aws.CredentialsProvider + + // Sets the log level the signer should use when reporting information to + // the logger. If the logger is nil nothing will be logged. See + // aws.LogLevel for more information on available logging levels + // + // By default nothing will be logged. + Debug aws.LogLevel + + // The logger loging information will be written to. If there the logger + // is nil, nothing will be logged. + Logger aws.Logger + + // Disables the Signer's moving HTTP header key/value pairs from the HTTP + // request header to the request's query string. This is most commonly used + // with pre-signed requests preventing headers from being added to the + // request's query string. + DisableHeaderHoisting bool + + // Disables the automatic escaping of the URI path of the request for the + // siganture's canonical string's path. For services that do not need additional + // escaping then use this to disable the signer escaping the path. + // + // S3 is an example of a service that does not need additional escaping. + // + // http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html + DisableURIPathEscaping bool + + // Disales the automatical setting of the HTTP request's Body field with the + // io.ReadSeeker passed in to the signer. This is useful if you're using a + // custom wrapper around the body for the io.ReadSeeker and want to preserve + // the Body value on the Request.Body. + // + // This does run the risk of signing a request with a body that will not be + // sent in the request. Need to ensure that the underlying data of the Body + // values are the same. + DisableRequestBodyOverwrite bool + + // UnsignedPayload will prevent signing of the payload. This will only + // work for services that have support for this. + UnsignedPayload bool +} + +// NewSigner returns a Signer pointer configured with the credentials and optional +// option values provided. If not options are provided the Signer will use its +// default configuration. +func NewSigner(credsProvider aws.CredentialsProvider, options ...func(*Signer)) *Signer { + v4 := &Signer{ + Credentials: credsProvider, + } + + for _, option := range options { + option(v4) + } + + return v4 +} + +type signingCtx struct { + ServiceName string + Region string + Request *http.Request + Body io.ReadSeeker + Query url.Values + Time time.Time + ExpireTime time.Duration + SignedHeaderVals http.Header + + DisableURIPathEscaping bool + + credValues aws.Credentials + isPresign bool + formattedTime string + formattedShortTime string + unsignedPayload bool + + bodyDigest string + signedHeaders string + canonicalHeaders string + canonicalString string + credentialString string + stringToSign string + signature string + authorization string +} + +// Sign signs AWS v4 requests with the provided body, service name, region the +// request is made to, and time the request is signed at. The signTime allows +// you to specify that a request is signed for the future, and cannot be +// used until then. +// +// Returns a list of HTTP headers that were included in the signature or an +// error if signing the request failed. Generally for signed requests this value +// is not needed as the full request context will be captured by the http.Request +// value. It is included for reference though. +// +// Sign will set the request's Body to be the `body` parameter passed in. If +// the body is not already an io.ReadCloser, it will be wrapped within one. If +// a `nil` body parameter passed to Sign, the request's Body field will be +// also set to nil. Its important to note that this functionality will not +// change the request's ContentLength of the request. +// +// Sign differs from Presign in that it will sign the request using HTTP +// header values. This type of signing is intended for http.Request values that +// will not be shared, or are shared in a way the header values on the request +// will not be lost. +// +// The requests body is an io.ReadSeeker so the SHA256 of the body can be +// generated. To bypass the signer computing the hash you can set the +// "X-Amz-Content-Sha256" header with a precomputed value. The signer will +// only compute the hash if the request header value is empty. +func (v4 Signer) Sign(r *http.Request, body io.ReadSeeker, service, region string, signTime time.Time) (http.Header, error) { + return v4.signWithBody(r, body, service, region, 0, signTime) +} + +// Presign signs AWS v4 requests with the provided body, service name, region +// the request is made to, and time the request is signed at. The signTime +// allows you to specify that a request is signed for the future, and cannot +// be used until then. +// +// Returns a list of HTTP headers that were included in the signature or an +// error if signing the request failed. For presigned requests these headers +// and their values must be included on the HTTP request when it is made. This +// is helpful to know what header values need to be shared with the party the +// presigned request will be distributed to. +// +// Presign differs from Sign in that it will sign the request using query string +// instead of header values. This allows you to share the Presigned Request's +// URL with third parties, or distribute it throughout your system with minimal +// dependencies. +// +// Presign also takes an exp value which is the duration the +// signed request will be valid after the signing time. This is allows you to +// set when the request will expire. +// +// The requests body is an io.ReadSeeker so the SHA256 of the body can be +// generated. To bypass the signer computing the hash you can set the +// "X-Amz-Content-Sha256" header with a precomputed value. The signer will +// only compute the hash if the request header value is empty. +// +// Presigning a S3 request will not compute the body's SHA256 hash by default. +// This is done due to the general use case for S3 presigned URLs is to share +// PUT/GET capabilities. If you would like to include the body's SHA256 in the +// presigned request's signature you can set the "X-Amz-Content-Sha256" +// HTTP header and that will be included in the request's signature. +func (v4 Signer) Presign(r *http.Request, body io.ReadSeeker, service, region string, exp time.Duration, signTime time.Time) (http.Header, error) { + return v4.signWithBody(r, body, service, region, exp, signTime) +} + +func (v4 Signer) signWithBody(r *http.Request, body io.ReadSeeker, service, region string, exp time.Duration, signTime time.Time) (http.Header, error) { + ctx := &signingCtx{ + Request: r, + Body: body, + Query: r.URL.Query(), + Time: signTime, + ExpireTime: exp, + isPresign: exp != 0, + ServiceName: service, + Region: region, + DisableURIPathEscaping: v4.DisableURIPathEscaping, + unsignedPayload: v4.UnsignedPayload, + } + + for key := range ctx.Query { + sort.Strings(ctx.Query[key]) + } + + if ctx.isRequestSigned() { + ctx.Time = sdk.NowTime() + ctx.handlePresignRemoval() + } + + var err error + ctx.credValues, err = v4.Credentials.Retrieve() + if err != nil { + return http.Header{}, err + } + + ctx.assignAmzQueryValues() + ctx.build(v4.DisableHeaderHoisting) + + // If the request is not presigned the body should be attached to it. This + // prevents the confusion of wanting to send a signed request without + // the body the request was signed for attached. + if !(v4.DisableRequestBodyOverwrite || ctx.isPresign) { + var reader io.ReadCloser + if body != nil { + var ok bool + if reader, ok = body.(io.ReadCloser); !ok { + reader = ioutil.NopCloser(body) + } + } + r.Body = reader + } + + if v4.Debug.Matches(aws.LogDebugWithSigning) { + v4.logSigningInfo(ctx) + } + + return ctx.SignedHeaderVals, nil +} + +func (ctx *signingCtx) handlePresignRemoval() { + if !ctx.isPresign { + return + } + + // The credentials have expired for this request. The current signing + // is invalid, and needs to be request because the request will fail. + ctx.removePresign() + + // Update the request's query string to ensure the values stays in + // sync in the case retrieving the new credentials fails. + ctx.Request.URL.RawQuery = ctx.Query.Encode() +} + +func (ctx *signingCtx) assignAmzQueryValues() { + if ctx.isPresign { + ctx.Query.Set("X-Amz-Algorithm", authHeaderPrefix) + if ctx.credValues.SessionToken != "" { + ctx.Query.Set("X-Amz-Security-Token", ctx.credValues.SessionToken) + } else { + ctx.Query.Del("X-Amz-Security-Token") + } + + return + } + + if ctx.credValues.SessionToken != "" { + ctx.Request.Header.Set("X-Amz-Security-Token", ctx.credValues.SessionToken) + } +} + +// SignRequestHandler is a named request handler the SDK will use to sign +// service client request with using the V4 signature. +var SignRequestHandler = aws.NamedHandler{ + Name: "v4.SignRequestHandler", Fn: func(r *aws.Request) { SignSDKRequest(r) }, +} + +// BuildNamedHandler will build a generic handler for signing. +func BuildNamedHandler(name string, opts ...func(*Signer)) aws.NamedHandler { + return aws.NamedHandler{ + Name: name, + Fn: func(req *aws.Request) { + SignSDKRequest(req, opts...) + }, + } +} + +// SignSDKRequest signs an AWS request with the V4 signature. This +// 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 +// 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. +// +// If the credentials of the request's config are set to +// aws.AnonymousCredentials the request will not be signed. +func SignSDKRequest(req *aws.Request, opts ...func(*Signer)) { + // If the request does not need to be signed ignore the signing of the + // request if the AnonymousCredentials object is used. + if req.Config.Credentials == aws.AnonymousCredentials { + return + } + + region := req.Metadata.SigningRegion + if region == "" { + region = req.Config.Region + } + + name := req.Metadata.SigningName + if name == "" { + name = req.Metadata.ServiceName + } + + v4 := NewSigner(req.Config.Credentials, func(v4 *Signer) { + v4.Debug = req.Config.LogLevel + v4.Logger = req.Config.Logger + v4.DisableHeaderHoisting = req.NotHoist + if name == "s3" { + // S3 service should not have any escaping applied + v4.DisableURIPathEscaping = true + } + // Prevents setting the HTTPRequest's Body. Since the Body could be + // wrapped in a custom io.Closer that we do not want to be stompped + // on top of by the signer. + v4.DisableRequestBodyOverwrite = true + }) + + for _, opt := range opts { + opt(v4) + } + + signingTime := req.Time + if !req.LastSignedAt.IsZero() { + signingTime = req.LastSignedAt + } + + signedHeaders, err := v4.signWithBody(req.HTTPRequest, req.GetBody(), + name, region, req.ExpireTime, signingTime, + ) + if err != nil { + req.Error = err + req.SignedHeaderVals = nil + return + } + + req.SignedHeaderVals = signedHeaders + req.LastSignedAt = sdk.NowTime() +} + +const logSignInfoMsg = `DEBUG: Request Signature: +---[ CANONICAL STRING ]----------------------------- +%s +---[ STRING TO SIGN ]-------------------------------- +%s%s +-----------------------------------------------------` +const logSignedURLMsg = ` +---[ SIGNED URL ]------------------------------------ +%s` + +func (v4 *Signer) logSigningInfo(ctx *signingCtx) { + signedURLMsg := "" + if ctx.isPresign { + signedURLMsg = fmt.Sprintf(logSignedURLMsg, ctx.Request.URL.String()) + } + msg := fmt.Sprintf(logSignInfoMsg, ctx.canonicalString, ctx.stringToSign, signedURLMsg) + v4.Logger.Log(msg) +} + +func (ctx *signingCtx) build(disableHeaderHoisting bool) { + ctx.buildTime() // no depends + ctx.buildCredentialString() // no depends + + ctx.buildBodyDigest() + + unsignedHeaders := ctx.Request.Header + if ctx.isPresign { + if !disableHeaderHoisting { + urlValues := url.Values{} + urlValues, unsignedHeaders = buildQuery(allowedQueryHoisting, unsignedHeaders) // no depends + for k := range urlValues { + ctx.Query[k] = urlValues[k] + } + } + } + + ctx.buildCanonicalHeaders(ignoredHeaders, unsignedHeaders) + ctx.buildCanonicalString() // depends on canon headers / signed headers + ctx.buildStringToSign() // depends on canon string + ctx.buildSignature() // depends on string to sign + + if ctx.isPresign { + ctx.Request.URL.RawQuery += "&X-Amz-Signature=" + ctx.signature + } else { + parts := []string{ + authHeaderPrefix + " Credential=" + ctx.credValues.AccessKeyID + "/" + ctx.credentialString, + "SignedHeaders=" + ctx.signedHeaders, + "Signature=" + ctx.signature, + } + ctx.Request.Header.Set("Authorization", strings.Join(parts, ", ")) + } +} + +func (ctx *signingCtx) buildTime() { + ctx.formattedTime = ctx.Time.UTC().Format(timeFormat) + ctx.formattedShortTime = ctx.Time.UTC().Format(shortTimeFormat) + + if ctx.isPresign { + duration := int64(ctx.ExpireTime / time.Second) + ctx.Query.Set("X-Amz-Date", ctx.formattedTime) + ctx.Query.Set("X-Amz-Expires", strconv.FormatInt(duration, 10)) + } else { + ctx.Request.Header.Set("X-Amz-Date", ctx.formattedTime) + } +} + +func (ctx *signingCtx) buildCredentialString() { + ctx.credentialString = strings.Join([]string{ + ctx.formattedShortTime, + ctx.Region, + ctx.ServiceName, + "aws4_request", + }, "/") + + if ctx.isPresign { + ctx.Query.Set("X-Amz-Credential", ctx.credValues.AccessKeyID+"/"+ctx.credentialString) + } +} + +func buildQuery(r rule, header http.Header) (url.Values, http.Header) { + query := url.Values{} + unsignedHeaders := http.Header{} + for k, h := range header { + if r.IsValid(k) { + query[k] = h + } else { + unsignedHeaders[k] = h + } + } + + return query, unsignedHeaders +} +func (ctx *signingCtx) buildCanonicalHeaders(r rule, header http.Header) { + var headers []string + headers = append(headers, "host") + for k, v := range header { + canonicalKey := http.CanonicalHeaderKey(k) + if !r.IsValid(canonicalKey) { + continue // ignored header + } + if ctx.SignedHeaderVals == nil { + ctx.SignedHeaderVals = make(http.Header) + } + + lowerCaseKey := strings.ToLower(k) + if _, ok := ctx.SignedHeaderVals[lowerCaseKey]; ok { + // include additional values + ctx.SignedHeaderVals[lowerCaseKey] = append(ctx.SignedHeaderVals[lowerCaseKey], v...) + continue + } + + headers = append(headers, lowerCaseKey) + ctx.SignedHeaderVals[lowerCaseKey] = v + } + sort.Strings(headers) + + ctx.signedHeaders = strings.Join(headers, ";") + + if ctx.isPresign { + ctx.Query.Set("X-Amz-SignedHeaders", ctx.signedHeaders) + } + + headerValues := make([]string, len(headers)) + for i, k := range headers { + if k == "host" { + if ctx.Request.Host != "" { + headerValues[i] = "host:" + ctx.Request.Host + } else { + headerValues[i] = "host:" + ctx.Request.URL.Host + } + } else { + headerValues[i] = k + ":" + + strings.Join(ctx.SignedHeaderVals[k], ",") + } + } + stripExcessSpaces(headerValues) + ctx.canonicalHeaders = strings.Join(headerValues, "\n") +} + +func (ctx *signingCtx) buildCanonicalString() { + ctx.Request.URL.RawQuery = strings.Replace(ctx.Query.Encode(), "+", "%20", -1) + + uri := getURIPath(ctx.Request.URL) + + if !ctx.DisableURIPathEscaping { + uri = rest.EscapePath(uri, false) + } + + ctx.canonicalString = strings.Join([]string{ + ctx.Request.Method, + uri, + ctx.Request.URL.RawQuery, + ctx.canonicalHeaders + "\n", + ctx.signedHeaders, + ctx.bodyDigest, + }, "\n") +} + +func (ctx *signingCtx) buildStringToSign() { + ctx.stringToSign = strings.Join([]string{ + authHeaderPrefix, + ctx.formattedTime, + ctx.credentialString, + hex.EncodeToString(makeSha256([]byte(ctx.canonicalString))), + }, "\n") +} + +func (ctx *signingCtx) buildSignature() { + secret := ctx.credValues.SecretAccessKey + date := makeHmac([]byte("AWS4"+secret), []byte(ctx.formattedShortTime)) + region := makeHmac(date, []byte(ctx.Region)) + service := makeHmac(region, []byte(ctx.ServiceName)) + credentials := makeHmac(service, []byte("aws4_request")) + signature := makeHmac(credentials, []byte(ctx.stringToSign)) + ctx.signature = hex.EncodeToString(signature) +} + +func (ctx *signingCtx) buildBodyDigest() { + hash := ctx.Request.Header.Get("X-Amz-Content-Sha256") + if hash == "" { + includeSHA256Header := ctx.unsignedPayload || + ctx.ServiceName == "s3" || + ctx.ServiceName == "glacier" + + s3Presign := ctx.isPresign && ctx.ServiceName == "s3" + + if ctx.unsignedPayload || s3Presign { + hash = "UNSIGNED-PAYLOAD" + includeSHA256Header = !s3Presign + } else if ctx.Body == nil { + hash = emptyStringSHA256 + } else { + hash = hex.EncodeToString(makeSha256Reader(ctx.Body)) + } + + if includeSHA256Header { + ctx.Request.Header.Set("X-Amz-Content-Sha256", hash) + } + } + ctx.bodyDigest = hash +} + +// isRequestSigned returns if the request is currently signed or presigned +func (ctx *signingCtx) isRequestSigned() bool { + if ctx.isPresign && ctx.Query.Get("X-Amz-Signature") != "" { + return true + } + if ctx.Request.Header.Get("Authorization") != "" { + return true + } + + return false +} + +// unsign removes signing flags for both signed and presigned requests. +func (ctx *signingCtx) removePresign() { + ctx.Query.Del("X-Amz-Algorithm") + ctx.Query.Del("X-Amz-Signature") + ctx.Query.Del("X-Amz-Security-Token") + ctx.Query.Del("X-Amz-Date") + ctx.Query.Del("X-Amz-Expires") + ctx.Query.Del("X-Amz-Credential") + ctx.Query.Del("X-Amz-SignedHeaders") +} + +func makeHmac(key []byte, data []byte) []byte { + hash := hmac.New(sha256.New, key) + hash.Write(data) + return hash.Sum(nil) +} + +func makeSha256(data []byte) []byte { + hash := sha256.New() + hash.Write(data) + return hash.Sum(nil) +} + +func makeSha256Reader(reader io.ReadSeeker) []byte { + hash := sha256.New() + start, _ := reader.Seek(0, 1) + defer reader.Seek(start, 0) + + io.Copy(hash, reader) + return hash.Sum(nil) +} + +const doubleSpace = " " + +// stripExcessSpaces will rewrite the passed in slice's string values to not +// contain muliple side-by-side spaces. +func stripExcessSpaces(vals []string) { + var j, k, l, m, spaces int + for i, str := range vals { + // Trim trailing spaces + for j = len(str) - 1; j >= 0 && str[j] == ' '; j-- { + } + + // Trim leading spaces + for k = 0; k < j && str[k] == ' '; k++ { + } + str = str[k : j+1] + + // Strip multiple spaces. + j = strings.Index(str, doubleSpace) + if j < 0 { + vals[i] = str + continue + } + + buf := []byte(str) + for k, m, l = j, j, len(buf); k < l; k++ { + if buf[k] == ' ' { + if spaces == 0 { + // First space. + buf[m] = buf[k] + m++ + } + spaces++ + } else { + // End of multiple spaces. + spaces = 0 + buf[m] = buf[k] + m++ + } + } + + vals[i] = string(buf[:m]) + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/static_provider.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/static_provider.go new file mode 100644 index 0000000..0870016 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/aws/static_provider.go @@ -0,0 +1,52 @@ +package aws + +import ( + "github.com/aws/aws-sdk-go-v2/aws/awserr" +) + +// StaticCredentialsProviderName provides a name of Static provider +const StaticCredentialsProviderName = "StaticCredentialsProvider" + +var ( + // ErrStaticCredentialsEmpty is emitted when static credentials are empty. + ErrStaticCredentialsEmpty = awserr.New("EmptyStaticCreds", "static credentials are empty", nil) +) + +// A StaticCredentialsProvider is a set of credentials which are set programmatically, +// and will never expire. +type StaticCredentialsProvider struct { + Value Credentials +} + +// NewStaticCredentialsProvider return a StaticCredentialsProvider initialized with the AWS credentials +// passed in. +func NewStaticCredentialsProvider(key, secret, session string) StaticCredentialsProvider { + return StaticCredentialsProvider{ + Value: Credentials{ + AccessKeyID: key, + SecretAccessKey: secret, + SessionToken: session, + }, + } +} + +// Retrieve returns the credentials or error if the credentials are invalid. +func (s StaticCredentialsProvider) Retrieve() (Credentials, error) { + v := s.Value + if v.AccessKeyID == "" || v.SecretAccessKey == "" { + return Credentials{Source: StaticCredentialsProviderName}, ErrStaticCredentialsEmpty + } + + if len(v.Source) == 0 { + v.Source = StaticCredentialsProviderName + } + + return v, nil +} + +// IsExpired returns if the credentials are expired. +// +// For StaticCredentialsProvider, the credentials never expired. +func (s StaticCredentialsProvider) IsExpired() bool { + return false +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/timeout_read_closer.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/timeout_read_closer.go new file mode 100644 index 0000000..d8b5124 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/aws/timeout_read_closer.go @@ -0,0 +1,94 @@ +package aws + +import ( + "io" + "time" + + "github.com/aws/aws-sdk-go-v2/aws/awserr" +) + +var timeoutErr = awserr.New( + ErrCodeResponseTimeout, + "read on body has reached the timeout limit", + nil, +) + +type readResult struct { + n int + err error +} + +// timeoutReadCloser will handle body reads that take too long. +// We will return a ErrReadTimeout error if a timeout occurs. +type timeoutReadCloser struct { + reader io.ReadCloser + duration time.Duration +} + +// Read will spin off a goroutine to call the reader's Read method. We will +// select on the timer's channel or the read's channel. Whoever completes first +// will be returned. +func (r *timeoutReadCloser) Read(b []byte) (int, error) { + timer := time.NewTimer(r.duration) + c := make(chan readResult, 1) + + go func() { + n, err := r.reader.Read(b) + timer.Stop() + c <- readResult{n: n, err: err} + }() + + select { + case data := <-c: + return data.n, data.err + case <-timer.C: + return 0, timeoutErr + } +} + +func (r *timeoutReadCloser) Close() error { + return r.reader.Close() +} + +const ( + // HandlerResponseTimeout is what we use to signify the name of the + // response timeout handler. + HandlerResponseTimeout = "ResponseTimeoutHandler" +) + +// adaptToResponseTimeoutError is a handler that will replace any top level error +// to a ErrCodeResponseTimeout, if its child is that. +func adaptToResponseTimeoutError(req *Request) { + if err, ok := req.Error.(awserr.Error); ok { + aerr, ok := err.OrigErr().(awserr.Error) + if ok && aerr.Code() == ErrCodeResponseTimeout { + req.Error = aerr + } + } +} + +// WithResponseReadTimeout is a request option that will wrap the body in a timeout read closer. +// This will allow for per read timeouts. If a timeout occurred, we will return the +// ErrCodeResponseTimeout. +// +// svc.PutObjectWithContext(ctx, params, request.WithTimeoutReadCloser(30 * time.Second) +func WithResponseReadTimeout(duration time.Duration) Option { + return func(r *Request) { + + var timeoutHandler = NamedHandler{ + HandlerResponseTimeout, + func(req *Request) { + req.HTTPResponse.Body = &timeoutReadCloser{ + reader: req.HTTPResponse.Body, + duration: duration, + } + }} + + // remove the handler so we are not stomping over any new durations. + r.Handlers.Send.RemoveByName(HandlerResponseTimeout) + r.Handlers.Send.PushBackNamed(timeoutHandler) + + r.Handlers.Unmarshal.PushBack(adaptToResponseTimeoutError) + r.Handlers.UnmarshalError.PushBack(adaptToResponseTimeoutError) + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/types.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/types.go new file mode 100644 index 0000000..0e2d864 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/aws/types.go @@ -0,0 +1,118 @@ +package aws + +import ( + "io" + "sync" +) + +// ReadSeekCloser wraps a io.Reader returning a ReaderSeekerCloser. Should +// only be used with an io.Reader that is also an io.Seeker. Doing so may +// cause request signature errors, or request body's not sent for GET, HEAD +// and DELETE HTTP methods. +// +// Deprecated: Should only be used with io.ReadSeeker. If using for +// S3 PutObject to stream content use s3manager.Uploader instead. +func ReadSeekCloser(r io.Reader) ReaderSeekerCloser { + return ReaderSeekerCloser{r} +} + +// ReaderSeekerCloser represents a reader that can also delegate io.Seeker and +// io.Closer interfaces to the underlying object if they are available. +type ReaderSeekerCloser struct { + r io.Reader +} + +// Read reads from the reader up to size of p. The number of bytes read, and +// error if it occurred will be returned. +// +// If the reader is not an io.Reader zero bytes read, and nil error will be returned. +// +// Performs the same functionality as io.Reader Read +func (r ReaderSeekerCloser) Read(p []byte) (int, error) { + switch t := r.r.(type) { + case io.Reader: + return t.Read(p) + } + return 0, nil +} + +// Seek sets the offset for the next Read to offset, interpreted according to +// whence: 0 means relative to the origin of the file, 1 means relative to the +// current offset, and 2 means relative to the end. Seek returns the new offset +// and an error, if any. +// +// If the ReaderSeekerCloser is not an io.Seeker nothing will be done. +func (r ReaderSeekerCloser) Seek(offset int64, whence int) (int64, error) { + switch t := r.r.(type) { + case io.Seeker: + return t.Seek(offset, whence) + } + return int64(0), nil +} + +// IsSeeker returns if the underlying reader is also a seeker. +func (r ReaderSeekerCloser) IsSeeker() bool { + _, ok := r.r.(io.Seeker) + return ok +} + +// Close closes the ReaderSeekerCloser. +// +// If the ReaderSeekerCloser is not an io.Closer nothing will be done. +func (r ReaderSeekerCloser) Close() error { + switch t := r.r.(type) { + case io.Closer: + return t.Close() + } + return nil +} + +// A WriteAtBuffer provides a in memory buffer supporting the io.WriterAt interface +// Can be used with the s3manager.Downloader to download content to a buffer +// in memory. Safe to use concurrently. +type WriteAtBuffer struct { + buf []byte + m sync.Mutex + + // GrowthCoeff defines the growth rate of the internal buffer. By + // default, the growth rate is 1, where expanding the internal + // buffer will allocate only enough capacity to fit the new expected + // length. + GrowthCoeff float64 +} + +// NewWriteAtBuffer creates a WriteAtBuffer with an internal buffer +// provided by buf. +func NewWriteAtBuffer(buf []byte) *WriteAtBuffer { + return &WriteAtBuffer{buf: buf} +} + +// WriteAt writes a slice of bytes to a buffer starting at the position provided +// The number of bytes written will be returned, or error. Can overwrite previous +// written slices if the write ats overlap. +func (b *WriteAtBuffer) WriteAt(p []byte, pos int64) (n int, err error) { + pLen := len(p) + expLen := pos + int64(pLen) + b.m.Lock() + defer b.m.Unlock() + if int64(len(b.buf)) < expLen { + if int64(cap(b.buf)) < expLen { + if b.GrowthCoeff < 1 { + b.GrowthCoeff = 1 + } + newBuf := make([]byte, expLen, int64(b.GrowthCoeff*float64(expLen))) + copy(newBuf, b.buf) + b.buf = newBuf + } + b.buf = b.buf[:expLen] + } + copy(b.buf[pos:], p) + return pLen, nil +} + +// Bytes returns a slice of bytes written to the buffer. +func (b *WriteAtBuffer) Bytes() []byte { + b.m.Lock() + defer b.m.Unlock() + return b.buf +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/url.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/url.go new file mode 100644 index 0000000..6192b24 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/aws/url.go @@ -0,0 +1,12 @@ +// +build go1.8 + +package aws + +import "net/url" + +// URLHostname will extract the Hostname without port from the URL value. +// +// Wrapper of net/url#URL.Hostname for backwards Go version compatibility. +func URLHostname(url *url.URL) string { + return url.Hostname() +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/url_1_7.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/url_1_7.go new file mode 100644 index 0000000..0210d27 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/aws/url_1_7.go @@ -0,0 +1,29 @@ +// +build !go1.8 + +package aws + +import ( + "net/url" + "strings" +) + +// URLHostname will extract the Hostname without port from the URL value. +// +// Copy of Go 1.8's net/url#URL.Hostname functionality. +func URLHostname(url *url.URL) string { + return stripPort(url.Host) + +} + +// stripPort is copy of Go 1.8 url#URL.Hostname functionality. +// https://golang.org/src/net/url/url.go +func stripPort(hostport string) string { + colon := strings.IndexByte(hostport, ':') + if colon == -1 { + return hostport + } + if i := strings.IndexByte(hostport, ']'); i != -1 { + return strings.TrimPrefix(hostport[:i], "[") + } + return hostport[:colon] +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/validation.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/validation.go new file mode 100644 index 0000000..1f11aa2 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/aws/validation.go @@ -0,0 +1,286 @@ +package aws + +import ( + "bytes" + "fmt" + + "github.com/aws/aws-sdk-go-v2/aws/awserr" +) + +const ( + // InvalidParameterErrCode is the error code for invalid parameters errors + InvalidParameterErrCode = "InvalidParameter" + // ParamRequiredErrCode is the error code for required parameter errors + ParamRequiredErrCode = "ParamRequiredError" + // ParamMinValueErrCode is the error code for fields with too low of a + // number value. + ParamMinValueErrCode = "ParamMinValueError" + // ParamMinLenErrCode is the error code for fields without enough elements. + ParamMinLenErrCode = "ParamMinLenError" + // ParamMaxLenErrCode is the error code for value being too long. + ParamMaxLenErrCode = "ParamMaxLenError" + + // ParamFormatErrCode is the error code for a field with invalid + // format or characters. + ParamFormatErrCode = "ParamFormatInvalidError" +) + +// Validator provides a way for types to perform validation logic on their +// input values that external code can use to determine if a type's values +// are valid. +type Validator interface { + Validate() error +} + +// An ErrInvalidParams provides wrapping of invalid parameter errors found when +// validating API operation input parameters. +type ErrInvalidParams struct { + // Context is the base context of the invalid parameter group. + Context string + errs []ErrInvalidParam +} + +// Add adds a new invalid parameter error to the collection of invalid +// parameters. The context of the invalid parameter will be updated to reflect +// this collection. +func (e *ErrInvalidParams) Add(err ErrInvalidParam) { + err.SetContext(e.Context) + e.errs = append(e.errs, err) +} + +// AddNested adds the invalid parameter errors from another ErrInvalidParams +// value into this collection. The nested errors will have their nested context +// updated and base context to reflect the merging. +// +// Use for nested validations errors. +func (e *ErrInvalidParams) AddNested(nestedCtx string, nested ErrInvalidParams) { + for _, err := range nested.errs { + err.SetContext(e.Context) + err.AddNestedContext(nestedCtx) + e.errs = append(e.errs, err) + } +} + +// Len returns the number of invalid parameter errors +func (e ErrInvalidParams) Len() int { + return len(e.errs) +} + +// Code returns the code of the error +func (e ErrInvalidParams) Code() string { + return InvalidParameterErrCode +} + +// Message returns the message of the error +func (e ErrInvalidParams) Message() string { + return fmt.Sprintf("%d validation error(s) found.", len(e.errs)) +} + +// Error returns the string formatted form of the invalid parameters. +func (e ErrInvalidParams) Error() string { + w := &bytes.Buffer{} + fmt.Fprintf(w, "%s: %s\n", e.Code(), e.Message()) + + for _, err := range e.errs { + fmt.Fprintf(w, "- %s\n", err.Message()) + } + + return w.String() +} + +// OrigErr returns the invalid parameters as a awserr.BatchedErrors value +func (e ErrInvalidParams) OrigErr() error { + return awserr.NewBatchError( + InvalidParameterErrCode, e.Message(), e.OrigErrs()) +} + +// OrigErrs returns a slice of the invalid parameters +func (e ErrInvalidParams) OrigErrs() []error { + errs := make([]error, len(e.errs)) + for i := 0; i < len(errs); i++ { + errs[i] = e.errs[i] + } + + return errs +} + +// An ErrInvalidParam represents an invalid parameter error type. +type ErrInvalidParam interface { + awserr.Error + + // Field name the error occurred on. + Field() string + + // SetContext updates the context of the error. + SetContext(string) + + // AddNestedContext updates the error's context to include a nested level. + AddNestedContext(string) +} + +type errInvalidParam struct { + context string + nestedContext string + field string + code string + msg string +} + +// Code returns the error code for the type of invalid parameter. +func (e *errInvalidParam) Code() string { + return e.code +} + +// Message returns the reason the parameter was invalid, and its context. +func (e *errInvalidParam) Message() string { + return fmt.Sprintf("%s, %s.", e.msg, e.Field()) +} + +// Error returns the string version of the invalid parameter error. +func (e *errInvalidParam) Error() string { + return fmt.Sprintf("%s: %s", e.code, e.Message()) +} + +// OrigErr returns nil, Implemented for awserr.Error interface. +func (e *errInvalidParam) OrigErr() error { + return nil +} + +// Field Returns the field and context the error occurred. +func (e *errInvalidParam) Field() string { + field := e.context + if len(field) > 0 { + field += "." + } + if len(e.nestedContext) > 0 { + field += fmt.Sprintf("%s.", e.nestedContext) + } + field += e.field + + return field +} + +// SetContext updates the base context of the error. +func (e *errInvalidParam) SetContext(ctx string) { + e.context = ctx +} + +// AddNestedContext prepends a context to the field's path. +func (e *errInvalidParam) AddNestedContext(ctx string) { + if len(e.nestedContext) == 0 { + e.nestedContext = ctx + } else { + e.nestedContext = fmt.Sprintf("%s.%s", ctx, e.nestedContext) + } + +} + +// An ErrParamRequired represents an required parameter error. +type ErrParamRequired struct { + errInvalidParam +} + +// NewErrParamRequired creates a new required parameter error. +func NewErrParamRequired(field string) *ErrParamRequired { + return &ErrParamRequired{ + errInvalidParam{ + code: ParamRequiredErrCode, + field: field, + msg: fmt.Sprintf("missing required field"), + }, + } +} + +// An ErrParamMinValue represents a minimum value parameter error. +type ErrParamMinValue struct { + errInvalidParam + min float64 +} + +// NewErrParamMinValue creates a new minimum value parameter error. +func NewErrParamMinValue(field string, min float64) *ErrParamMinValue { + return &ErrParamMinValue{ + errInvalidParam: errInvalidParam{ + code: ParamMinValueErrCode, + field: field, + msg: fmt.Sprintf("minimum field value of %v", min), + }, + min: min, + } +} + +// MinValue returns the field's require minimum value. +// +// float64 is returned for both int and float min values. +func (e *ErrParamMinValue) MinValue() float64 { + return e.min +} + +// An ErrParamMinLen represents a minimum length parameter error. +type ErrParamMinLen struct { + errInvalidParam + min int +} + +// NewErrParamMinLen creates a new minimum length parameter error. +func NewErrParamMinLen(field string, min int) *ErrParamMinLen { + return &ErrParamMinLen{ + errInvalidParam: errInvalidParam{ + code: ParamMinLenErrCode, + field: field, + msg: fmt.Sprintf("minimum field size of %v", min), + }, + min: min, + } +} + +// MinLen returns the field's required minimum length. +func (e *ErrParamMinLen) MinLen() int { + return e.min +} + +// An ErrParamMaxLen represents a maximum length parameter error. +type ErrParamMaxLen struct { + errInvalidParam + max int +} + +// NewErrParamMaxLen creates a new maximum length parameter error. +func NewErrParamMaxLen(field string, max int, value string) *ErrParamMaxLen { + return &ErrParamMaxLen{ + errInvalidParam: errInvalidParam{ + code: ParamMaxLenErrCode, + field: field, + msg: fmt.Sprintf("maximum size of %v, %v", max, value), + }, + max: max, + } +} + +// MaxLen returns the field's required minimum length. +func (e *ErrParamMaxLen) MaxLen() int { + return e.max +} + +// An ErrParamFormat represents a invalid format parameter error. +type ErrParamFormat struct { + errInvalidParam + format string +} + +// NewErrParamFormat creates a new invalid format parameter error. +func NewErrParamFormat(field string, format, value string) *ErrParamFormat { + return &ErrParamFormat{ + errInvalidParam: errInvalidParam{ + code: ParamFormatErrCode, + field: field, + msg: fmt.Sprintf("format %v, %v", format, value), + }, + format: format, + } +} + +// Format returns the field's required format. +func (e *ErrParamFormat) Format() string { + return e.format +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/version.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/version.go new file mode 100644 index 0000000..abd858c --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/aws/version.go @@ -0,0 +1,8 @@ +// Package aws provides core functionality for making requests to AWS services. +package aws + +// SDKName is the name of this AWS SDK +const SDKName = "aws-sdk-go" + +// SDKVersion is the version of this SDK +const SDKVersion = "0.7.0" diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/waiter.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/waiter.go new file mode 100644 index 0000000..6e3f7e7 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/aws/waiter.go @@ -0,0 +1,284 @@ +package aws + +import ( + "fmt" + "time" + + "github.com/aws/aws-sdk-go-v2/aws/awserr" + "github.com/aws/aws-sdk-go-v2/internal/awsutil" + "github.com/aws/aws-sdk-go-v2/internal/sdk" +) + +// WaiterResourceNotReadyErrorCode is the error code returned by a waiter when +// the waiter's max attempts have been exhausted. +const WaiterResourceNotReadyErrorCode = "ResourceNotReady" + +// A WaiterOption is a function that will update the Waiter value's fields to +// configure the waiter. +type WaiterOption func(*Waiter) + +// WithWaiterMaxAttempts returns the maximum number of times the waiter should +// attempt to check the resource for the target state. +func WithWaiterMaxAttempts(max int) WaiterOption { + return func(w *Waiter) { + w.MaxAttempts = max + } +} + +// WaiterDelay will return a delay the waiter should pause between attempts to +// check the resource state. The passed in attempt is the number of times the +// Waiter has checked the resource state. +// +// Attempt is the number of attempts the Waiter has made checking the resource +// state. +type WaiterDelay func(attempt int) time.Duration + +// ConstantWaiterDelay returns a WaiterDelay that will always return a constant +// delay the waiter should use between attempts. It ignores the number of +// attempts made. +func ConstantWaiterDelay(delay time.Duration) WaiterDelay { + return func(attempt int) time.Duration { + return delay + } +} + +// WithWaiterDelay will set the Waiter to use the WaiterDelay passed in. +func WithWaiterDelay(delayer WaiterDelay) WaiterOption { + return func(w *Waiter) { + w.Delay = delayer + } +} + +// WithWaiterLogger returns a waiter option to set the logger a waiter +// should use to log warnings and errors to. +func WithWaiterLogger(logger Logger) WaiterOption { + return func(w *Waiter) { + w.Logger = logger + } +} + +// WithWaiterRequestOptions returns a waiter option setting the request +// options for each request the waiter makes. Appends to waiter's request +// options already set. +func WithWaiterRequestOptions(opts ...Option) WaiterOption { + return func(w *Waiter) { + w.RequestOptions = append(w.RequestOptions, opts...) + } +} + +// A Waiter provides the functionality to perform a blocking call which will +// wait for a resource state to be satisfied by a service. +// +// This type should not be used directly. The API operations provided in the +// service packages prefixed with "WaitUntil" should be used instead. +type Waiter struct { + Name string + Acceptors []WaiterAcceptor + Logger Logger + + MaxAttempts int + Delay WaiterDelay + + RequestOptions []Option + NewRequest func([]Option) (*Request, error) + SleepWithContext func(Context, time.Duration) error +} + +// ApplyOptions updates the waiter with the list of waiter options provided. +func (w *Waiter) ApplyOptions(opts ...WaiterOption) { + for _, fn := range opts { + fn(w) + } +} + +// WaiterState are states the waiter uses based on WaiterAcceptor definitions +// to identify if the resource state the waiter is waiting on has occurred. +type WaiterState int + +// String returns the string representation of the waiter state. +func (s WaiterState) String() string { + switch s { + case SuccessWaiterState: + return "success" + case FailureWaiterState: + return "failure" + case RetryWaiterState: + return "retry" + default: + return "unknown waiter state" + } +} + +// States the waiter acceptors will use to identify target resource states. +const ( + SuccessWaiterState WaiterState = iota // waiter successful + FailureWaiterState // waiter failed + RetryWaiterState // waiter needs to be retried +) + +// WaiterMatchMode is the mode that the waiter will use to match the WaiterAcceptor +// definition's Expected attribute. +type WaiterMatchMode int + +// Modes the waiter will use when inspecting API response to identify target +// resource states. +const ( + PathAllWaiterMatch WaiterMatchMode = iota // match on all paths + PathWaiterMatch // match on specific path + PathAnyWaiterMatch // match on any path + PathListWaiterMatch // match on list of paths + StatusWaiterMatch // match on status code + ErrorWaiterMatch // match on error +) + +// String returns the string representation of the waiter match mode. +func (m WaiterMatchMode) String() string { + switch m { + case PathAllWaiterMatch: + return "pathAll" + case PathWaiterMatch: + return "path" + case PathAnyWaiterMatch: + return "pathAny" + case PathListWaiterMatch: + return "pathList" + case StatusWaiterMatch: + return "status" + case ErrorWaiterMatch: + return "error" + default: + return "unknown waiter match mode" + } +} + +// WaitWithContext will make requests for the API operation using NewRequest to +// build API requests. The request's response will be compared against the +// Waiter's Acceptors to determine the successful state of the resource the +// waiter is inspecting. +// +// The passed in context must not be nil. If it is nil a panic will occur. The +// Context will be used to cancel the waiter's pending requests and retry delays. +// Use BackgroundContext if no context is available. +// +// The waiter will continue until the target state defined by the Acceptors, +// or the max attempts expires. +// +// Will return the WaiterResourceNotReadyErrorCode error code if the waiter's +// retryer ShouldRetry returns false. This normally will happen when the max +// wait attempts expires. +func (w Waiter) WaitWithContext(ctx Context) error { + + for attempt := 1; ; attempt++ { + req, err := w.NewRequest(w.RequestOptions) + if err != nil { + waiterLogf(w.Logger, "unable to create request %v", err) + return err + } + req.Handlers.Build.PushBack(MakeAddToUserAgentFreeFormHandler("Waiter")) + err = req.Send() + + // See if any of the acceptors match the request's response, or error + for _, a := range w.Acceptors { + if matched, matchErr := a.match(w.Name, w.Logger, req, err); matched { + return matchErr + } + } + + // The Waiter should only check the resource state MaxAttempts times + // This is here instead of in the for loop above to prevent delaying + // unnecessary when the waiter will not retry. + if attempt == w.MaxAttempts { + break + } + + // Delay to wait before inspecting the resource again + if err := sdk.SleepWithContext(ctx, w.Delay(attempt)); err != nil { + return awserr.New(ErrCodeRequestCanceled, "waiter context canceled", err) + } + } + + return awserr.New(WaiterResourceNotReadyErrorCode, "exceeded wait attempts", nil) +} + +// A WaiterAcceptor provides the information needed to wait for an API operation +// to complete. +type WaiterAcceptor struct { + State WaiterState + Matcher WaiterMatchMode + Argument string + Expected interface{} +} + +// match returns if the acceptor found a match with the passed in request +// or error. True is returned if the acceptor made a match, error is returned +// if there was an error attempting to perform the match. +func (a *WaiterAcceptor) match(name string, l Logger, req *Request, err error) (bool, error) { + result := false + var vals []interface{} + + switch a.Matcher { + case PathAllWaiterMatch, PathWaiterMatch: + // Require all matches to be equal for result to match + vals, _ = awsutil.ValuesAtPath(req.Data, a.Argument) + if len(vals) == 0 { + break + } + result = true + for _, val := range vals { + if !awsutil.DeepEqual(val, a.Expected) { + result = false + break + } + } + case PathAnyWaiterMatch: + // Only a single match needs to equal for the result to match + vals, _ = awsutil.ValuesAtPath(req.Data, a.Argument) + for _, val := range vals { + if awsutil.DeepEqual(val, a.Expected) { + result = true + break + } + } + case PathListWaiterMatch: + // ignored matcher + case StatusWaiterMatch: + s := a.Expected.(int) + result = s == req.HTTPResponse.StatusCode + case ErrorWaiterMatch: + if aerr, ok := err.(awserr.Error); ok { + result = aerr.Code() == a.Expected.(string) + } + default: + waiterLogf(l, "WARNING: Waiter %s encountered unexpected matcher: %s", + name, a.Matcher) + } + + if !result { + // If there was no matching result found there is nothing more to do + // for this response, retry the request. + return false, nil + } + + switch a.State { + case SuccessWaiterState: + // waiter completed + return true, nil + case FailureWaiterState: + // Waiter failure state triggered + return true, awserr.New(WaiterResourceNotReadyErrorCode, + "failed waiting for successful resource state", err) + case RetryWaiterState: + // clear the error and retry the operation + return false, nil + default: + waiterLogf(l, "WARNING: Waiter %s encountered unexpected state: %s", + name, a.State) + return false, nil + } +} + +func waiterLogf(logger Logger, msg string, args ...interface{}) { + if logger != nil { + logger.Log(fmt.Sprintf(msg, args...)) + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/awsutil/copy.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/awsutil/copy.go new file mode 100644 index 0000000..938cd14 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/internal/awsutil/copy.go @@ -0,0 +1,112 @@ +package awsutil + +import ( + "io" + "reflect" + "time" +) + +// Copy deeply copies a src structure to dst. Useful for copying request and +// response structures. +// +// Can copy between structs of different type, but will only copy fields which +// are assignable, and exist in both structs. Fields which are not assignable, +// or do not exist in both structs are ignored. +func Copy(dst, src interface{}) { + dstval := reflect.ValueOf(dst) + if !dstval.IsValid() { + panic("Copy dst cannot be nil") + } + + rcopy(dstval, reflect.ValueOf(src), true) +} + +// CopyOf returns a copy of src while also allocating the memory for dst. +// src must be a pointer type or this operation will fail. +func CopyOf(src interface{}) (dst interface{}) { + dsti := reflect.New(reflect.TypeOf(src).Elem()) + dst = dsti.Interface() + rcopy(dsti, reflect.ValueOf(src), true) + return +} + +// rcopy performs a recursive copy of values from the source to destination. +// +// root is used to skip certain aspects of the copy which are not valid +// for the root node of a object. +func rcopy(dst, src reflect.Value, root bool) { + if !src.IsValid() { + return + } + + switch src.Kind() { + case reflect.Ptr: + if _, ok := src.Interface().(io.Reader); ok { + if dst.Kind() == reflect.Ptr && dst.Elem().CanSet() { + dst.Elem().Set(src) + } else if dst.CanSet() { + dst.Set(src) + } + } else { + e := src.Type().Elem() + if dst.CanSet() && !src.IsNil() { + if _, ok := src.Interface().(*time.Time); !ok { + if dst.Kind() == reflect.String { + dst.SetString(e.String()) + } else { + dst.Set(reflect.New(e)) + } + } else { + tempValue := reflect.New(e) + tempValue.Elem().Set(src.Elem()) + // Sets time.Time's unexported values + dst.Set(tempValue) + } + } + if dst.Kind() != reflect.String && src.Elem().IsValid() { + // Keep the current root state since the depth hasn't changed + rcopy(dst.Elem(), src.Elem(), root) + } + } + case reflect.Struct: + t := dst.Type() + for i := 0; i < t.NumField(); i++ { + name := t.Field(i).Name + srcVal := src.FieldByName(name) + dstVal := dst.FieldByName(name) + if srcVal.IsValid() && dstVal.CanSet() { + rcopy(dstVal, srcVal, false) + } + } + case reflect.Slice: + if src.IsNil() { + break + } + + s := reflect.MakeSlice(src.Type(), src.Len(), src.Cap()) + dst.Set(s) + for i := 0; i < src.Len(); i++ { + rcopy(dst.Index(i), src.Index(i), false) + } + case reflect.Map: + if src.IsNil() { + break + } + + s := reflect.MakeMap(src.Type()) + dst.Set(s) + for _, k := range src.MapKeys() { + v := src.MapIndex(k) + v2 := reflect.New(v.Type()).Elem() + rcopy(v2, v, false) + dst.SetMapIndex(k, v2) + } + default: + // Assign the value if possible. If its not assignable, the value would + // need to be converted and the impact of that may be unexpected, or is + // not compatible with the dst type. + if src.Type().AssignableTo(dst.Type()) { + dst.Set(src) + } + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/awsutil/equal.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/awsutil/equal.go new file mode 100644 index 0000000..bcfe51a --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/internal/awsutil/equal.go @@ -0,0 +1,33 @@ +package awsutil + +import ( + "reflect" +) + +// DeepEqual returns if the two values are deeply equal like reflect.DeepEqual. +// In addition to this, this method will also dereference the input values if +// possible so the DeepEqual performed will not fail if one parameter is a +// pointer and the other is not. +// +// DeepEqual will not perform indirection of nested values of the input parameters. +func DeepEqual(a, b interface{}) bool { + ra := reflect.Indirect(reflect.ValueOf(a)) + rb := reflect.Indirect(reflect.ValueOf(b)) + + if raValid, rbValid := ra.IsValid(), rb.IsValid(); !raValid && !rbValid { + // If the elements are both nil, and of the same type the are equal + // If they are of different types they are not equal + return reflect.TypeOf(a) == reflect.TypeOf(b) + } else if raValid != rbValid { + // Both values must be valid to be equal + return false + } + + // Special casing for strings as typed enumerations are string aliases + // but are not deep equal. + if ra.Kind() == reflect.String && rb.Kind() == reflect.String { + return ra.String() == rb.String() + } + + return reflect.DeepEqual(ra.Interface(), rb.Interface()) +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/awsutil/path_value.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/awsutil/path_value.go new file mode 100644 index 0000000..7e69bd5 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/internal/awsutil/path_value.go @@ -0,0 +1,225 @@ +package awsutil + +import ( + "reflect" + "regexp" + "strconv" + "strings" + + "github.com/jmespath/go-jmespath" +) + +var indexRe = regexp.MustCompile(`(.+)\[(-?\d+)?\]$`) + +// rValuesAtPath returns a slice of values found in value v. The values +// in v are explored recursively so all nested values are collected. +func rValuesAtPath(v interface{}, path string, createPath, caseSensitive, nilTerm bool) []reflect.Value { + pathparts := strings.Split(path, "||") + if len(pathparts) > 1 { + for _, pathpart := range pathparts { + vals := rValuesAtPath(v, pathpart, createPath, caseSensitive, nilTerm) + if len(vals) > 0 { + return vals + } + } + return nil + } + + values := []reflect.Value{reflect.Indirect(reflect.ValueOf(v))} + components := strings.Split(path, ".") + for len(values) > 0 && len(components) > 0 { + var index *int64 + var indexStar bool + c := strings.TrimSpace(components[0]) + if c == "" { // no actual component, illegal syntax + return nil + } else if caseSensitive && c != "*" && strings.ToLower(c[0:1]) == c[0:1] { + // TODO normalize case for user + return nil // don't support unexported fields + } + + // parse this component + if m := indexRe.FindStringSubmatch(c); m != nil { + c = m[1] + if m[2] == "" { + index = nil + indexStar = true + } else { + i, _ := strconv.ParseInt(m[2], 10, 32) + index = &i + indexStar = false + } + } + + nextvals := []reflect.Value{} + for _, value := range values { + // pull component name out of struct member + if value.Kind() != reflect.Struct { + continue + } + + if c == "*" { // pull all members + for i := 0; i < value.NumField(); i++ { + if f := reflect.Indirect(value.Field(i)); f.IsValid() { + nextvals = append(nextvals, f) + } + } + continue + } + + value = value.FieldByNameFunc(func(name string) bool { + if c == name { + return true + } else if !caseSensitive && strings.ToLower(name) == strings.ToLower(c) { + return true + } + return false + }) + + if nilTerm && value.Kind() == reflect.Ptr && len(components[1:]) == 0 { + if !value.IsNil() { + value.Set(reflect.Zero(value.Type())) + } + return []reflect.Value{value} + } + + if createPath && value.Kind() == reflect.Ptr && value.IsNil() { + // TODO if the value is the terminus it should not be created + // if the value to be set to its position is nil. + value.Set(reflect.New(value.Type().Elem())) + value = value.Elem() + } else { + value = reflect.Indirect(value) + } + + if value.Kind() == reflect.Slice || value.Kind() == reflect.Map { + if !createPath && value.IsNil() { + value = reflect.ValueOf(nil) + } + } + + if value.IsValid() { + nextvals = append(nextvals, value) + } + } + values = nextvals + + if indexStar || index != nil { + nextvals = []reflect.Value{} + for _, valItem := range values { + value := reflect.Indirect(valItem) + if value.Kind() != reflect.Slice { + continue + } + + if indexStar { // grab all indices + for i := 0; i < value.Len(); i++ { + idx := reflect.Indirect(value.Index(i)) + if idx.IsValid() { + nextvals = append(nextvals, idx) + } + } + continue + } + + // pull out index + i := int(*index) + if i >= value.Len() { // check out of bounds + if createPath { + // TODO resize slice + } else { + continue + } + } else if i < 0 { // support negative indexing + i = value.Len() + i + } + value = reflect.Indirect(value.Index(i)) + + if value.Kind() == reflect.Slice || value.Kind() == reflect.Map { + if !createPath && value.IsNil() { + value = reflect.ValueOf(nil) + } + } + + if value.IsValid() { + nextvals = append(nextvals, value) + } + } + values = nextvals + } + + components = components[1:] + } + return values +} + +// ValuesAtPath returns a list of values at the case insensitive lexical +// path inside of a structure. +func ValuesAtPath(i interface{}, path string) ([]interface{}, error) { + result, err := jmespath.Search(path, i) + if err != nil { + return nil, err + } + + v := reflect.ValueOf(result) + if !v.IsValid() || (v.Kind() == reflect.Ptr && v.IsNil()) { + return nil, nil + } + if s, ok := result.([]interface{}); ok { + return s, err + } + if v.Kind() == reflect.Map && v.Len() == 0 { + return nil, nil + } + if v.Kind() == reflect.Slice { + out := make([]interface{}, v.Len()) + for i := 0; i < v.Len(); i++ { + out[i] = v.Index(i).Interface() + } + return out, nil + } + + return []interface{}{result}, nil +} + +// SetValueAtPath sets a value at the case insensitive lexical path inside +// of a structure. +func SetValueAtPath(i interface{}, path string, v interface{}) { + if rvals := rValuesAtPath(i, path, true, false, v == nil); rvals != nil { + for _, rval := range rvals { + if rval.Kind() == reflect.Ptr && rval.IsNil() { + continue + } + setValue(rval, v) + } + } +} + +func setValue(dstVal reflect.Value, src interface{}) { + if dstVal.Kind() == reflect.Ptr { + dstVal = reflect.Indirect(dstVal) + } + srcVal := reflect.ValueOf(src) + + if !srcVal.IsValid() { // src is literal nil + if dstVal.CanAddr() { + // Convert to pointer so that pointer's value can be nil'ed + // dstVal = dstVal.Addr() + } + dstVal.Set(reflect.Zero(dstVal.Type())) + + } else if srcVal.Kind() == reflect.Ptr { + if srcVal.IsNil() { + srcVal = reflect.Zero(dstVal.Type()) + } else { + srcVal = reflect.ValueOf(src).Elem() + } + dstVal.Set(srcVal) + } else { + if dstVal.Kind() == reflect.String { + dstVal.SetString(srcVal.String()) + } else { + dstVal.Set(srcVal) + } + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/awsutil/prettify.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/awsutil/prettify.go new file mode 100644 index 0000000..710eb43 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/internal/awsutil/prettify.go @@ -0,0 +1,113 @@ +package awsutil + +import ( + "bytes" + "fmt" + "io" + "reflect" + "strings" +) + +// Prettify returns the string representation of a value. +func Prettify(i interface{}) string { + var buf bytes.Buffer + prettify(reflect.ValueOf(i), 0, &buf) + return buf.String() +} + +// prettify will recursively walk value v to build a textual +// representation of the value. +func prettify(v reflect.Value, indent int, buf *bytes.Buffer) { + for v.Kind() == reflect.Ptr { + v = v.Elem() + } + + switch v.Kind() { + case reflect.Struct: + strtype := v.Type().String() + if strtype == "time.Time" { + fmt.Fprintf(buf, "%s", v.Interface()) + break + } else if strings.HasPrefix(strtype, "io.") { + buf.WriteString("") + break + } + + buf.WriteString("{\n") + + names := []string{} + for i := 0; i < v.Type().NumField(); i++ { + name := v.Type().Field(i).Name + f := v.Field(i) + if name[0:1] == strings.ToLower(name[0:1]) { + continue // ignore unexported fields + } + if (f.Kind() == reflect.Ptr || f.Kind() == reflect.Slice || f.Kind() == reflect.Map) && f.IsNil() { + continue // ignore unset fields + } + names = append(names, name) + } + + for i, n := range names { + val := v.FieldByName(n) + buf.WriteString(strings.Repeat(" ", indent+2)) + buf.WriteString(n + ": ") + prettify(val, indent+2, buf) + + if i < len(names)-1 { + buf.WriteString(",\n") + } + } + + buf.WriteString("\n" + strings.Repeat(" ", indent) + "}") + case reflect.Slice: + strtype := v.Type().String() + if strtype == "[]uint8" { + fmt.Fprintf(buf, " len %d", v.Len()) + break + } + + nl, id, id2 := "", "", "" + if v.Len() > 3 { + nl, id, id2 = "\n", strings.Repeat(" ", indent), strings.Repeat(" ", indent+2) + } + buf.WriteString("[" + nl) + for i := 0; i < v.Len(); i++ { + buf.WriteString(id2) + prettify(v.Index(i), indent+2, buf) + + if i < v.Len()-1 { + buf.WriteString("," + nl) + } + } + + buf.WriteString(nl + id + "]") + case reflect.Map: + buf.WriteString("{\n") + + for i, k := range v.MapKeys() { + buf.WriteString(strings.Repeat(" ", indent+2)) + buf.WriteString(k.String() + ": ") + prettify(v.MapIndex(k), indent+2, buf) + + if i < v.Len()-1 { + buf.WriteString(",\n") + } + } + + buf.WriteString("\n" + strings.Repeat(" ", indent) + "}") + default: + if !v.IsValid() { + fmt.Fprint(buf, "") + return + } + format := "%v" + switch v.Interface().(type) { + case string: + format = "%q" + case io.ReadSeeker, io.Reader: + format = "buffer(%p)" + } + fmt.Fprintf(buf, format, v.Interface()) + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/awsutil/string_value.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/awsutil/string_value.go new file mode 100644 index 0000000..b6432f1 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/internal/awsutil/string_value.go @@ -0,0 +1,89 @@ +package awsutil + +import ( + "bytes" + "fmt" + "reflect" + "strings" +) + +// StringValue returns the string representation of a value. +func StringValue(i interface{}) string { + var buf bytes.Buffer + stringValue(reflect.ValueOf(i), 0, &buf) + return buf.String() +} + +func stringValue(v reflect.Value, indent int, buf *bytes.Buffer) { + for v.Kind() == reflect.Ptr { + v = v.Elem() + } + + switch v.Kind() { + case reflect.Struct: + buf.WriteString("{\n") + + names := []string{} + for i := 0; i < v.Type().NumField(); i++ { + name := v.Type().Field(i).Name + f := v.Field(i) + if name[0:1] == strings.ToLower(name[0:1]) { + continue // ignore unexported fields + } + if (f.Kind() == reflect.Ptr || f.Kind() == reflect.Slice) && f.IsNil() { + continue // ignore unset fields + } + names = append(names, name) + } + + for i, n := range names { + val := v.FieldByName(n) + buf.WriteString(strings.Repeat(" ", indent+2)) + buf.WriteString(n + ": ") + stringValue(val, indent+2, buf) + + if i < len(names)-1 { + buf.WriteString(",\n") + } + } + + buf.WriteString("\n" + strings.Repeat(" ", indent) + "}") + case reflect.Slice: + nl, id, id2 := "", "", "" + if v.Len() > 3 { + nl, id, id2 = "\n", strings.Repeat(" ", indent), strings.Repeat(" ", indent+2) + } + buf.WriteString("[" + nl) + for i := 0; i < v.Len(); i++ { + buf.WriteString(id2) + stringValue(v.Index(i), indent+2, buf) + + if i < v.Len()-1 { + buf.WriteString("," + nl) + } + } + + buf.WriteString(nl + id + "]") + case reflect.Map: + buf.WriteString("{\n") + + for i, k := range v.MapKeys() { + buf.WriteString(strings.Repeat(" ", indent+2)) + buf.WriteString(k.String() + ": ") + stringValue(v.MapIndex(k), indent+2, buf) + + if i < v.Len()-1 { + buf.WriteString(",\n") + } + } + + buf.WriteString("\n" + strings.Repeat(" ", indent) + "}") + default: + format := "%v" + switch v.Interface().(type) { + case string: + format = "%q" + } + fmt.Fprintf(buf, format, v.Interface()) + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/sdk/interfaces.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/sdk/interfaces.go new file mode 100644 index 0000000..2b42cbe --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/internal/sdk/interfaces.go @@ -0,0 +1,9 @@ +package sdk + +// Invalidator provides access to a type's invalidate method to make it +// invalidate it cache. +// +// e.g aws.SafeCredentialsProvider's Invalidate method. +type Invalidator interface { + Invalidate() +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/sdk/time.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/sdk/time.go new file mode 100644 index 0000000..e5640ab --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/internal/sdk/time.go @@ -0,0 +1,44 @@ +package sdk + +import ( + "context" + "time" +) + +func init() { + NowTime = time.Now + Sleep = time.Sleep + SleepWithContext = DefaultSleepWithContext +} + +// NowTime is a value for getting the current time. This value can be overriden +// for testing mocking out current time. +var NowTime func() time.Time + +// Sleep is a value for sleeping for a duration. This value can be overriden +// for testing and mocking out sleep duration. +var Sleep func(time.Duration) + +// SleepWithContext will wait for the timer duration to expire, or the context +// is canceled. Which ever happens first. If the context is canceled the Context's +// error will be returned. +// +// This value can be overriden for testing and mocking out sleep duration. +var SleepWithContext func(context.Context, time.Duration) error + +// DefaultSleepWithContext will wait for the timer duration to expire, or the context +// is canceled. Which ever happens first. If the context is canceled the Context's +// error will be returned. +func DefaultSleepWithContext(ctx context.Context, dur time.Duration) error { + t := time.NewTimer(dur) + defer t.Stop() + + select { + case <-t.C: + break + case <-ctx.Done(): + return ctx.Err() + } + + return nil +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/private/protocol/encode.go b/vendor/github.com/aws/aws-sdk-go-v2/private/protocol/encode.go new file mode 100644 index 0000000..dc3d129 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/private/protocol/encode.go @@ -0,0 +1,95 @@ +package protocol + +import ( + "io" +) + +// A FieldMarshaler interface is used to marshal struct fields when encoding. +type FieldMarshaler interface { + MarshalFields(FieldEncoder) error +} + +// FieldMarshalerFunc is a helper utility that wrapps a function and allows +// that function to be called as a FieldMarshaler. +type FieldMarshalerFunc func(FieldEncoder) error + +// MarshalFields will call the underlying function passing in the field encoder +// with the protocol field encoder. +func (fn FieldMarshalerFunc) MarshalFields(e FieldEncoder) error { + return fn(e) +} + +// ValueMarshaler provides a generic type for all encoding field values to be +// passed into a encoder's methods with. +type ValueMarshaler interface { + MarshalValue() (string, error) + MarshalValueBuf([]byte) ([]byte, error) +} + +// A StreamMarshaler interface is used to marshal a stream when encoding. +type StreamMarshaler interface { + MarshalStream() (io.ReadSeeker, error) +} + +// MarshalListValues is a marshaler for list encoders. +type MarshalListValues interface { + MarshalValues(enc ListEncoder) error +} + +// MapMarshaler is a marshaler for map encoders. +type MapMarshaler interface { + MarshalValues(enc MapEncoder) error +} + +// A ListEncoder provides the interface for encoders that will encode List elements. +type ListEncoder interface { + Start() + End() + + Map() MapEncoder + List() ListEncoder + + ListAddValue(v ValueMarshaler) + ListAddFields(m FieldMarshaler) +} + +// A MapEncoder provides the interface for encoders that will encode map elements. +type MapEncoder interface { + Start() + End() + + Map(k string) MapEncoder + List(k string) ListEncoder + + MapSetValue(k string, v ValueMarshaler) + MapSetFields(k string, m FieldMarshaler) +} + +// A FieldEncoder provides the interface for encoding struct field members. +type FieldEncoder interface { + SetValue(t Target, k string, m ValueMarshaler, meta Metadata) + SetStream(t Target, k string, m StreamMarshaler, meta Metadata) + SetFields(t Target, k string, m FieldMarshaler, meta Metadata) + + Map(t Target, k string, meta Metadata) MapEncoder + List(t Target, k string, meta Metadata) ListEncoder +} + +// A FieldBuffer provides buffering of fields so the number of +// allocations are reduced by providng a persistent buffer that is +// used between fields. +type FieldBuffer struct { + buf []byte +} + +// GetValue will retrieve the ValueMarshaler's value by appending the +// value to the buffer. Will return the buffer that was populated. +// +// This buffer is only valid until the next time GetValue is called. +func (b *FieldBuffer) GetValue(m ValueMarshaler) ([]byte, error) { + v, err := m.MarshalValueBuf(b.buf) + if len(v) > len(b.buf) { + b.buf = v + } + return v, err +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/private/protocol/fields.go b/vendor/github.com/aws/aws-sdk-go-v2/private/protocol/fields.go new file mode 100644 index 0000000..b131e22 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/private/protocol/fields.go @@ -0,0 +1,197 @@ +package protocol + +import ( + "bytes" + "encoding/base64" + "io" + "strconv" + "strings" + "time" + + "github.com/aws/aws-sdk-go-v2/aws" +) + +// QuotedValue represents a type that should be quoted when encoding +// a string value. +type QuotedValue struct { + ValueMarshaler +} + +// BoolValue provies encoding of bool for AWS protocols. +type BoolValue bool + +// MarshalValue formats the value into a string for encoding. +func (v BoolValue) MarshalValue() (string, error) { + return strconv.FormatBool(bool(v)), nil +} + +// MarshalValueBuf formats the value into a byte slice for encoding. +// If there is enough room in the passed in slice v will be appended to it. +// +// Will reset the length of the passed in slice to 0. +func (v BoolValue) MarshalValueBuf(b []byte) ([]byte, error) { + b = b[0:0] + return strconv.AppendBool(b, bool(v)), nil +} + +// BytesValue provies encoding of string for AWS protocols. +type BytesValue string + +// MarshalValue formats the value into a string for encoding. +func (v BytesValue) MarshalValue() (string, error) { + return base64.StdEncoding.EncodeToString([]byte(v)), nil +} + +// MarshalValueBuf formats the value into a byte slice for encoding. +// If there is enough room in the passed in slice v will be appended to it. +func (v BytesValue) MarshalValueBuf(b []byte) ([]byte, error) { + m := []byte(v) + + n := base64.StdEncoding.EncodedLen(len(m)) + if len(b) < n { + b = make([]byte, n) + } + base64.StdEncoding.Encode(b, m) + return b[:n], nil +} + +// StringValue provies encoding of string for AWS protocols. +type StringValue string + +// MarshalValue formats the value into a string for encoding. +func (v StringValue) MarshalValue() (string, error) { + return string(v), nil +} + +// MarshalValueBuf formats the value into a byte slice for encoding. +// If there is enough room in the passed in slice v will be appended to it. +// +// Will reset the length of the passed in slice to 0. +func (v StringValue) MarshalValueBuf(b []byte) ([]byte, error) { + b = b[0:0] + return append(b, v...), nil +} + +// Int64Value provies encoding of int64 for AWS protocols. +type Int64Value int64 + +// MarshalValue formats the value into a string for encoding. +func (v Int64Value) MarshalValue() (string, error) { + return strconv.FormatInt(int64(v), 10), nil +} + +// MarshalValueBuf formats the value into a byte slice for encoding. +// If there is enough room in the passed in slice v will be appended to it. +// +// Will reset the length of the passed in slice to 0. +func (v Int64Value) MarshalValueBuf(b []byte) ([]byte, error) { + b = b[0:0] + return strconv.AppendInt(b, int64(v), 10), nil +} + +// Float64Value provies encoding of float64 for AWS protocols. +type Float64Value float64 + +// MarshalValue formats the value into a string for encoding. +func (v Float64Value) MarshalValue() (string, error) { + return strconv.FormatFloat(float64(v), 'f', -1, 64), nil +} + +// MarshalValueBuf formats the value into a byte slice for encoding. +// If there is enough room in the passed in slice v will be appended to it. +// +// Will reset the length of the passed in slice to 0. +func (v Float64Value) MarshalValueBuf(b []byte) ([]byte, error) { + b = b[0:0] + return strconv.AppendFloat(b, float64(v), 'f', -1, 64), nil +} + +// JSONValue provies encoding of aws.JSONValues for AWS protocols. +type JSONValue struct { + V aws.JSONValue + EscapeMode EscapeMode +} + +// MarshalValue formats the value into a string for encoding. +func (v JSONValue) MarshalValue() (string, error) { + return EncodeJSONValue(v.V, v.EscapeMode) +} + +// MarshalValueBuf formats the value into a byte slice for encoding. +// If there is enough room in the passed in slice v will be appended to it. +// +// Will reset the length of the passed in slice to 0. +func (v JSONValue) MarshalValueBuf(b []byte) ([]byte, error) { + b = b[0:0] + + m, err := EncodeJSONValue(v.V, v.EscapeMode) + if err != nil { + return nil, err + } + + return append(b, []byte(m)...), nil +} + +// Time formats for protocol time fields. +const ( + ISO8601TimeFormat = "2006-01-02T15:04:05Z" // ISO 8601 formated time. + RFC822TimeFromat = "Mon, 2 Jan 2006 15:04:05 GMT" // RFC822 formatted time. + UnixTimeFormat = "unix time format" // Special case for Unix time +) + +// TimeValue provies encoding of time.Time for AWS protocols. +type TimeValue struct { + V time.Time + Format string +} + +// MarshalValue formats the value into a string givin a format for encoding. +func (v TimeValue) MarshalValue() (string, error) { + t := time.Time(v.V) + + if v.Format == UnixTimeFormat { + return strconv.FormatInt(t.UTC().Unix(), 10), nil + } + return t.UTC().Format(v.Format), nil +} + +// MarshalValueBuf formats the value into a byte slice for encoding. +// If there is enough room in the passed in slice v will be appended to it. +// +// Will reset the length of the passed in slice to 0. +func (v TimeValue) MarshalValueBuf(b []byte) ([]byte, error) { + b = b[0:0] + + m, err := v.MarshalValue() + if err != nil { + return nil, err + } + + return append(b, m...), nil +} + +// A ReadSeekerStream wrapps an io.ReadSeeker to be used as a StreamMarshaler. +type ReadSeekerStream struct { + V io.ReadSeeker +} + +// MarshalStream returns the wrapped io.ReadSeeker for encoding. +func (v ReadSeekerStream) MarshalStream() (io.ReadSeeker, error) { + return v.V, nil +} + +// A BytesStream aliases a byte slice to be used as a StreamMarshaler. +type BytesStream []byte + +// MarshalStream marshals a byte slice into an io.ReadSeeker for encoding. +func (v BytesStream) MarshalStream() (io.ReadSeeker, error) { + return bytes.NewReader([]byte(v)), nil +} + +// A StringStream aliases a string to be used as a StreamMarshaler. +type StringStream string + +// MarshalStream marshals a string into an io.ReadSeeker for encoding. +func (v StringStream) MarshalStream() (io.ReadSeeker, error) { + return strings.NewReader(string(v)), nil +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/private/protocol/header_encoder.go b/vendor/github.com/aws/aws-sdk-go-v2/private/protocol/header_encoder.go new file mode 100644 index 0000000..38bae69 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/private/protocol/header_encoder.go @@ -0,0 +1,116 @@ +package protocol + +import ( + "fmt" + "net/http" +) + +// HeaderMapEncoder builds a map valu +type HeaderMapEncoder struct { + Prefix string + Header http.Header + Err error +} + +// MapSetValue adds a single value to the header. +func (e *HeaderMapEncoder) MapSetValue(k string, v ValueMarshaler) { + if e.Err != nil { + return + } + + str, err := v.MarshalValue() + if err != nil { + e.Err = err + return + } + + if len(e.Prefix) > 0 { + k = e.Prefix + k + } + + e.Header.Set(k, str) +} + +// List executes the passed in callback with a list encoder based on +// the context of this HeaderMapEncoder. +func (e *HeaderMapEncoder) List(k string) ListEncoder { + if e.Err != nil { + return nil + } + + if len(e.Prefix) > 0 { + k = e.Prefix + k + } + + return &HeaderListEncoder{Key: k, Header: e.Header} +} + +// Map sets the header element with nested maps appending the +// passed in k to the prefix if one was set. +func (e *HeaderMapEncoder) Map(k string) MapEncoder { + if e.Err != nil { + return nil + } + + if len(e.Prefix) > 0 { + k = e.Prefix + k + } + + return &HeaderMapEncoder{Prefix: k, Header: e.Header} +} + +// Start does nothing for header encodings. +func (e *HeaderMapEncoder) Start() {} + +// End does nothing for header encodings. +func (e *HeaderMapEncoder) End() {} + +// MapSetFields Is not implemented, query map of FieldMarshaler is undefined. +func (e *HeaderMapEncoder) MapSetFields(k string, m FieldMarshaler) { + e.Err = fmt.Errorf("header map encoder MapSetFields not supported, %s", k) +} + +// HeaderListEncoder will encode list values nested into a header key. +type HeaderListEncoder struct { + Key string + Header http.Header + Err error +} + +// ListAddValue encodes an individual list value into the header. +func (e *HeaderListEncoder) ListAddValue(v ValueMarshaler) { + if e.Err != nil { + return + } + + str, err := v.MarshalValue() + if err != nil { + e.Err = err + return + } + + e.Header.Add(e.Key, str) +} + +// List Is not implemented, header list of list is undefined. +func (e *HeaderListEncoder) List() ListEncoder { + e.Err = fmt.Errorf("header list encoder ListAddList not supported, %s", e.Key) + return nil +} + +// Map Is not implemented, header list of map is undefined. +func (e *HeaderListEncoder) Map() MapEncoder { + e.Err = fmt.Errorf("header list encoder ListAddMap not supported, %s", e.Key) + return nil +} + +// Start does nothing for header list encodings. +func (e *HeaderListEncoder) Start() {} + +// End does nothing for header list encodings. +func (e *HeaderListEncoder) End() {} + +// ListAddFields Is not implemented, query list of FieldMarshaler is undefined. +func (e *HeaderListEncoder) ListAddFields(m FieldMarshaler) { + e.Err = fmt.Errorf("header list encoder ListAddFields not supported, %s", e.Key) +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/private/protocol/host.go b/vendor/github.com/aws/aws-sdk-go-v2/private/protocol/host.go new file mode 100644 index 0000000..14ed78d --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/private/protocol/host.go @@ -0,0 +1,68 @@ +package protocol + +import ( + "strings" + + "github.com/aws/aws-sdk-go-v2/aws" +) + +// ValidateEndpointHostHandler is a request handler that will validate the +// request endpoint's hosts is a valid RFC 3986 host. +var ValidateEndpointHostHandler = aws.NamedHandler{ + Name: "awssdk.protocol.ValidateEndpointHostHandler", + Fn: func(r *aws.Request) { + err := ValidateEndpointHost(r.Operation.Name, r.HTTPRequest.URL.Host) + if err != nil { + r.Error = err + } + }, +} + +// ValidateEndpointHost validates that the host string passed in is a valid RFC +// 3986 host. Returns error if the host is not valid. +func ValidateEndpointHost(opName, host string) error { + paramErrs := aws.ErrInvalidParams{Context: opName} + labels := strings.Split(host, ".") + + for i, label := range labels { + if i == len(labels)-1 && len(label) == 0 { + // Allow trailing dot for FQDN hosts. + continue + } + + if !ValidHostLabel(label) { + paramErrs.Add(aws.NewErrParamFormat( + "endpoint host label", "[a-zA-Z0-9-]{1,63}", label)) + } + } + + if len(host) > 255 { + paramErrs.Add(aws.NewErrParamMaxLen( + "endpoint host", 255, host, + )) + } + + if paramErrs.Len() > 0 { + return paramErrs + } + return nil +} + +// ValidHostLabel returns if the label is a valid RFC 3986 host label. +func ValidHostLabel(label string) bool { + if l := len(label); l == 0 || l > 63 { + return false + } + for _, r := range label { + switch { + case r >= '0' && r <= '9': + case r >= 'A' && r <= 'Z': + case r >= 'a' && r <= 'z': + case r == '-': + default: + return false + } + } + + return true +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/private/protocol/host_prefix.go b/vendor/github.com/aws/aws-sdk-go-v2/private/protocol/host_prefix.go new file mode 100644 index 0000000..2018867 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/private/protocol/host_prefix.go @@ -0,0 +1,49 @@ +package protocol + +import ( + "strings" + + "github.com/aws/aws-sdk-go-v2/aws" +) + +// HostPrefixHandlerName is the handler name for the host prefix request +// handler. +const HostPrefixHandlerName = "awssdk.endpoint.HostPrefixHandler" + +// NewHostPrefixHandler constructs a build handler +func NewHostPrefixHandler(prefix string, labelsFn func() map[string]string) aws.NamedHandler { + builder := HostPrefixBuilder{ + Prefix: prefix, + LabelsFn: labelsFn, + } + return aws.NamedHandler{ + Name: HostPrefixHandlerName, + Fn: builder.Build, + } +} + +// HostPrefixBuilder provides the request handler to expand and prepend +// the host prefix into the operation's request endpoint host. +type HostPrefixBuilder struct { + Prefix string + LabelsFn func() map[string]string +} + +// Build updates the passed in Request with the HostPrefix template expanded. +func (h HostPrefixBuilder) Build(r *aws.Request) { + if r.Config.DisableEndpointHostPrefix { + return + } + var labels map[string]string + if h.LabelsFn != nil { + labels = h.LabelsFn() + } + prefix := h.Prefix + for name, value := range labels { + prefix = strings.Replace(prefix, "{"+name+"}", value, -1) + } + r.HTTPRequest.URL.Host = prefix + r.HTTPRequest.URL.Host + if len(r.HTTPRequest.Host) > 0 { + r.HTTPRequest.Host = prefix + r.HTTPRequest.Host + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/private/protocol/idempotency.go b/vendor/github.com/aws/aws-sdk-go-v2/private/protocol/idempotency.go new file mode 100644 index 0000000..53831df --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/private/protocol/idempotency.go @@ -0,0 +1,75 @@ +package protocol + +import ( + "crypto/rand" + "fmt" + "reflect" +) + +// RandReader is the random reader the protocol package will use to read +// random bytes from. This is exported for testing, and should not be used. +var RandReader = rand.Reader + +const idempotencyTokenFillTag = `idempotencyToken` + +// CanSetIdempotencyToken returns true if the struct field should be +// automatically populated with a Idempotency token. +// +// Only *string and string type fields that are tagged with idempotencyToken +// which are not already set can be auto filled. +func CanSetIdempotencyToken(v reflect.Value, f reflect.StructField) bool { + switch u := v.Interface().(type) { + // To auto fill an Idempotency token the field must be a string, + // tagged for auto fill, and have a zero value. + case *string: + return u == nil && len(f.Tag.Get(idempotencyTokenFillTag)) != 0 + case string: + return len(u) == 0 && len(f.Tag.Get(idempotencyTokenFillTag)) != 0 + } + + return false +} + +// GetIdempotencyToken returns a randomly generated idempotency token. +func GetIdempotencyToken() string { + b := make([]byte, 16) + RandReader.Read(b) + + return UUIDVersion4(b) +} + +// SetIdempotencyToken will set the value provided with a Idempotency Token. +// Given that the value can be set. Will panic if value is not setable. +func SetIdempotencyToken(v reflect.Value) { + if v.Kind() == reflect.Ptr { + if v.IsNil() && v.CanSet() { + v.Set(reflect.New(v.Type().Elem())) + } + v = v.Elem() + } + v = reflect.Indirect(v) + + if !v.CanSet() { + panic(fmt.Sprintf("unable to set idempotnecy token %v", v)) + } + + b := make([]byte, 16) + _, err := rand.Read(b) + if err != nil { + // TODO handle error + return + } + + v.Set(reflect.ValueOf(UUIDVersion4(b))) +} + +// UUIDVersion4 returns a Version 4 random UUID from the byte slice provided +func UUIDVersion4(u []byte) string { + // https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_4_.28random.29 + // 13th character is "4" + u[6] = (u[6] | 0x40) & 0x4F + // 17th character is "8", "9", "a", or "b" + u[8] = (u[8] | 0x80) & 0xBF + + return fmt.Sprintf(`%X-%X-%X-%X-%X`, u[0:4], u[4:6], u[6:8], u[8:10], u[10:]) +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/private/protocol/json/jsonutil/build.go b/vendor/github.com/aws/aws-sdk-go-v2/private/protocol/json/jsonutil/build.go new file mode 100644 index 0000000..029be32 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/private/protocol/json/jsonutil/build.go @@ -0,0 +1,293 @@ +// Package jsonutil provides JSON serialization of AWS requests and responses. +package jsonutil + +import ( + "bytes" + "encoding/base64" + "encoding/json" + "fmt" + "math" + "reflect" + "sort" + "strconv" + "time" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/private/protocol" +) + +var timeType = reflect.ValueOf(time.Time{}).Type() +var byteSliceType = reflect.ValueOf([]byte{}).Type() + +// BuildJSON builds a JSON string for a given object v. +func BuildJSON(v interface{}) ([]byte, error) { + var buf bytes.Buffer + + err := buildAny(reflect.ValueOf(v), &buf, "", false) + return buf.Bytes(), err +} + +func buildAny(value reflect.Value, buf *bytes.Buffer, tag reflect.StructTag, parentCollection bool) error { + origVal := value + value = reflect.Indirect(value) + if !value.IsValid() { + return nil + } + + vtype := value.Type() + + t := tag.Get("type") + if t == "" { + switch vtype.Kind() { + case reflect.Struct: + // also it can't be a time object + if value.Type() != timeType { + t = "structure" + } + case reflect.Slice: + // also it can't be a byte slice + if _, ok := value.Interface().([]byte); !ok { + t = "list" + } + case reflect.Map: + // cannot be a JSONValue map + if _, ok := value.Interface().(aws.JSONValue); !ok { + t = "map" + } + } + } + + switch t { + case "structure": + if field, ok := vtype.FieldByName("_"); ok { + tag = field.Tag + } + return buildStruct(value, buf, tag) + case "list": + return buildList(value, buf, tag) + case "map": + return buildMap(value, buf, tag) + default: + return buildScalar(origVal, buf, tag, parentCollection) + } +} + +func buildStruct(value reflect.Value, buf *bytes.Buffer, tag reflect.StructTag) error { + if !value.IsValid() { + return nil + } + + // unwrap payloads + if payload := tag.Get("payload"); payload != "" { + field, _ := value.Type().FieldByName(payload) + tag = field.Tag + value = elemOf(value.FieldByName(payload)) + + if !value.IsValid() { + return nil + } + } + + buf.WriteByte('{') + + t := value.Type() + first := true + for i := 0; i < t.NumField(); i++ { + member := value.Field(i) + + // This allocates the most memory. + // Additionally, we cannot skip nil fields due to + // idempotency auto filling. + field := t.Field(i) + + if field.PkgPath != "" { + continue // ignore unexported fields + } + if field.Tag.Get("json") == "-" { + continue + } + if field.Tag.Get("location") != "" { + continue // ignore non-body elements + } + if field.Tag.Get("ignore") != "" { + continue + } + + if protocol.CanSetIdempotencyToken(member, field) { + token := protocol.GetIdempotencyToken() + member = reflect.ValueOf(&token) + } + + if (member.Kind() == reflect.Ptr || member.Kind() == reflect.Slice || member.Kind() == reflect.Map) && member.IsNil() { + continue // ignore unset fields + } else if member.Kind() == reflect.String && member.Len() == 0 { + continue + } + + if first { + first = false + } else { + buf.WriteByte(',') + } + + // figure out what this field is called + name := field.Name + if locName := field.Tag.Get("locationName"); locName != "" { + name = locName + } + + writeString(name, buf) + buf.WriteString(`:`) + + err := buildAny(member, buf, field.Tag, false) + if err != nil { + return err + } + + } + + buf.WriteString("}") + + return nil +} + +func buildList(value reflect.Value, buf *bytes.Buffer, tag reflect.StructTag) error { + buf.WriteString("[") + + for i := 0; i < value.Len(); i++ { + elem := value.Index(i) + buildAny(elem, buf, "", true) + + if i < value.Len()-1 { + buf.WriteString(",") + } + } + + buf.WriteString("]") + + return nil +} + +type sortedValues []reflect.Value + +func (sv sortedValues) Len() int { return len(sv) } +func (sv sortedValues) Swap(i, j int) { sv[i], sv[j] = sv[j], sv[i] } +func (sv sortedValues) Less(i, j int) bool { return sv[i].String() < sv[j].String() } + +func buildMap(value reflect.Value, buf *bytes.Buffer, tag reflect.StructTag) error { + buf.WriteString("{") + + sv := sortedValues(value.MapKeys()) + sort.Sort(sv) + + for i, k := range sv { + if i > 0 { + buf.WriteByte(',') + } + + writeString(k.String(), buf) + buf.WriteString(`:`) + + buildAny(value.MapIndex(k), buf, "", true) + } + + buf.WriteString("}") + + return nil +} + +func buildScalar(v reflect.Value, buf *bytes.Buffer, tag reflect.StructTag, parentCollection bool) error { + // prevents allocation on the heap. + scratch := [64]byte{} + switch value := reflect.Indirect(v); value.Kind() { + case reflect.String: + str := value.String() + isEnum := len(tag.Get("enum")) != 0 + if parentCollection || (len(str) > 0 && isEnum) || !isEnum { + writeString(str, buf) + } + case reflect.Bool: + if value.Bool() { + buf.WriteString("true") + } else { + buf.WriteString("false") + } + case reflect.Int64: + buf.Write(strconv.AppendInt(scratch[:0], value.Int(), 10)) + case reflect.Float64: + f := value.Float() + if math.IsInf(f, 0) || math.IsNaN(f) { + return &json.UnsupportedValueError{Value: v, Str: strconv.FormatFloat(f, 'f', -1, 64)} + } + buf.Write(strconv.AppendFloat(scratch[:0], f, 'f', -1, 64)) + default: + switch converted := value.Interface().(type) { + case time.Time: + buf.Write(strconv.AppendInt(scratch[:0], converted.UTC().Unix(), 10)) + case []byte: + if !value.IsNil() { + buf.WriteByte('"') + if len(converted) < 1024 { + // for small buffers, using Encode directly is much faster. + dst := make([]byte, base64.StdEncoding.EncodedLen(len(converted))) + base64.StdEncoding.Encode(dst, converted) + buf.Write(dst) + } else { + // for large buffers, avoid unnecessary extra temporary + // buffer space. + enc := base64.NewEncoder(base64.StdEncoding, buf) + enc.Write(converted) + enc.Close() + } + buf.WriteByte('"') + } + case aws.JSONValue: + str, err := protocol.EncodeJSONValue(converted, protocol.QuotedEscape) + if err != nil { + return fmt.Errorf("unable to encode JSONValue, %v", err) + } + buf.WriteString(str) + default: + return fmt.Errorf("unsupported JSON value %v (%s)", value.Interface(), value.Type()) + } + } + return nil +} + +var hex = "0123456789abcdef" + +func writeString(s string, buf *bytes.Buffer) { + buf.WriteByte('"') + for i := 0; i < len(s); i++ { + if s[i] == '"' { + buf.WriteString(`\"`) + } else if s[i] == '\\' { + buf.WriteString(`\\`) + } else if s[i] == '\b' { + buf.WriteString(`\b`) + } else if s[i] == '\f' { + buf.WriteString(`\f`) + } else if s[i] == '\r' { + buf.WriteString(`\r`) + } else if s[i] == '\t' { + buf.WriteString(`\t`) + } else if s[i] == '\n' { + buf.WriteString(`\n`) + } else if s[i] < 32 { + buf.WriteString("\\u00") + buf.WriteByte(hex[s[i]>>4]) + buf.WriteByte(hex[s[i]&0xF]) + } else { + buf.WriteByte(s[i]) + } + } + buf.WriteByte('"') +} + +// Returns the reflection element of a value, if it is a pointer. +func elemOf(value reflect.Value) reflect.Value { + for value.Kind() == reflect.Ptr { + value = value.Elem() + } + return value +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/private/protocol/json/jsonutil/unmarshal.go b/vendor/github.com/aws/aws-sdk-go-v2/private/protocol/json/jsonutil/unmarshal.go new file mode 100644 index 0000000..dce3a67 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/private/protocol/json/jsonutil/unmarshal.go @@ -0,0 +1,242 @@ +package jsonutil + +import ( + "encoding/base64" + "encoding/json" + "fmt" + "io" + "io/ioutil" + "reflect" + "time" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/private/protocol" +) + +// UnmarshalJSON reads a stream and unmarshals the results in object v. +func UnmarshalJSON(v interface{}, stream io.Reader) error { + var out interface{} + + b, err := ioutil.ReadAll(stream) + if err != nil { + return err + } + + if len(b) == 0 { + return nil + } + + if err := json.Unmarshal(b, &out); err != nil { + return err + } + + return unmarshalAny(reflect.ValueOf(v), out, "") +} + +func unmarshalAny(value reflect.Value, data interface{}, tag reflect.StructTag) error { + vtype := value.Type() + if vtype.Kind() == reflect.Ptr { + vtype = vtype.Elem() // check kind of actual element type + } + + t := tag.Get("type") + if t == "" { + switch vtype.Kind() { + case reflect.Struct: + // also it can't be a time object + _, tok := value.Interface().(*time.Time) + if _, ok := value.Interface().(time.Time); !(ok || tok) { + t = "structure" + } + case reflect.Slice: + // also it can't be a byte slice + if _, ok := value.Interface().([]byte); !ok { + t = "list" + } + case reflect.Map: + // cannot be a JSONValue map + if _, ok := value.Interface().(aws.JSONValue); !ok { + t = "map" + } + } + } + + switch t { + case "structure": + if field, ok := vtype.FieldByName("_"); ok { + tag = field.Tag + } + return unmarshalStruct(value, data, tag) + case "list": + return unmarshalList(value, data, tag) + case "map": + return unmarshalMap(value, data, tag) + default: + return unmarshalScalar(value, data, tag) + } +} + +func unmarshalStruct(value reflect.Value, data interface{}, tag reflect.StructTag) error { + if data == nil { + return nil + } + + mapData, ok := data.(map[string]interface{}) + if !ok { + return fmt.Errorf("JSON value is not a structure (%#v)", data) + } + + t := value.Type() + if value.Kind() == reflect.Ptr { + if value.IsNil() { // create the structure if it's nil + s := reflect.New(value.Type().Elem()) + value.Set(s) + value = s + } + + value = value.Elem() + t = t.Elem() + } + + // unwrap any payloads + if payload := tag.Get("payload"); payload != "" { + field, _ := t.FieldByName(payload) + return unmarshalAny(value.FieldByName(payload), data, field.Tag) + } + + for i := 0; i < t.NumField(); i++ { + field := t.Field(i) + if field.PkgPath != "" { + continue // ignore unexported fields + } + + // figure out what this field is called + name := field.Name + if locName := field.Tag.Get("locationName"); locName != "" { + name = locName + } + + member := value.FieldByIndex(field.Index) + err := unmarshalAny(member, mapData[name], field.Tag) + if err != nil { + return err + } + } + return nil +} + +func unmarshalList(value reflect.Value, data interface{}, tag reflect.StructTag) error { + if data == nil { + return nil + } + listData, ok := data.([]interface{}) + if !ok { + return fmt.Errorf("JSON value is not a list (%#v)", data) + } + + if value.IsNil() { + l := len(listData) + value.Set(reflect.MakeSlice(value.Type(), l, l)) + } + + for i, c := range listData { + err := unmarshalAny(value.Index(i), c, "") + if err != nil { + return err + } + } + + return nil +} + +func unmarshalMap(value reflect.Value, data interface{}, tag reflect.StructTag) error { + if data == nil { + return nil + } + mapData, ok := data.(map[string]interface{}) + if !ok { + return fmt.Errorf("JSON value is not a map (%#v)", data) + } + + if value.IsNil() { + value.Set(reflect.MakeMap(value.Type())) + } + + for k, v := range mapData { + kvalue := reflect.ValueOf(k) + vvalue := reflect.New(value.Type().Elem()).Elem() + unmarshalAny(vvalue, v, "") + value.SetMapIndex(kvalue, vvalue) + } + + return nil +} + +func unmarshalScalar(value reflect.Value, data interface{}, tag reflect.StructTag) error { + errf := func() error { + return fmt.Errorf("unsupported value: %v (%s)", value.Interface(), value.Type()) + } + + switch d := data.(type) { + case nil: + return nil // nothing to do here + case string: + if value.Kind() == reflect.String { + value.SetString(d) + return nil + } + + switch value.Interface().(type) { + case *string: + value.Set(reflect.ValueOf(&d)) + case string: + value.Set(reflect.ValueOf(d)) + case []byte: + b, err := base64.StdEncoding.DecodeString(d) + if err != nil { + return err + } + value.Set(reflect.ValueOf(b)) + case aws.JSONValue: + // No need to use escaping as the value is a non-quoted string. + v, err := protocol.DecodeJSONValue(d, protocol.NoEscape) + if err != nil { + return err + } + value.Set(reflect.ValueOf(v)) + default: + return errf() + } + case float64: + switch value.Interface().(type) { + case *int64: + di := int64(d) + value.Set(reflect.ValueOf(&di)) + case int64: + di := int64(d) + value.Set(reflect.ValueOf(di)) + case *float64: + value.Set(reflect.ValueOf(&d)) + case float64: + value.Set(reflect.ValueOf(d)) + case *time.Time: + t := time.Unix(int64(d), 0).UTC() + value.Set(reflect.ValueOf(&t)) + case time.Time: + t := time.Unix(int64(d), 0).UTC() + value.Set(reflect.ValueOf(t)) + default: + return errf() + } + case bool: + switch value.Interface().(type) { + case *bool: + value.Set(reflect.ValueOf(&d)) + default: + return errf() + } + default: + return fmt.Errorf("unsupported JSON value (%v)", data) + } + return nil +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/private/protocol/jsonrpc/jsonrpc.go b/vendor/github.com/aws/aws-sdk-go-v2/private/protocol/jsonrpc/jsonrpc.go new file mode 100644 index 0000000..d2d4f82 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/private/protocol/jsonrpc/jsonrpc.go @@ -0,0 +1,109 @@ +// Package jsonrpc provides JSON RPC utilities for serialization of AWS +// requests and responses. +package jsonrpc + +//go:generate go run -tags codegen ../../../models/protocol_tests/generate.go ../../../models/protocol_tests/input/json.json build_test.go +//go:generate go run -tags codegen ../../../models/protocol_tests/generate.go ../../../models/protocol_tests/output/json.json unmarshal_test.go + +import ( + "encoding/json" + "io/ioutil" + "strings" + + request "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/aws/awserr" + "github.com/aws/aws-sdk-go-v2/private/protocol/json/jsonutil" + "github.com/aws/aws-sdk-go-v2/private/protocol/rest" +) + +var emptyJSON = []byte("{}") + +// BuildHandler is a named request handler for building jsonrpc protocol requests +var BuildHandler = request.NamedHandler{Name: "awssdk.jsonrpc.Build", Fn: Build} + +// UnmarshalHandler is a named request handler for unmarshaling jsonrpc protocol requests +var UnmarshalHandler = request.NamedHandler{Name: "awssdk.jsonrpc.Unmarshal", Fn: Unmarshal} + +// UnmarshalMetaHandler is a named request handler for unmarshaling jsonrpc protocol request metadata +var UnmarshalMetaHandler = request.NamedHandler{Name: "awssdk.jsonrpc.UnmarshalMeta", Fn: UnmarshalMeta} + +// UnmarshalErrorHandler is a named request handler for unmarshaling jsonrpc protocol request errors +var UnmarshalErrorHandler = request.NamedHandler{Name: "awssdk.jsonrpc.UnmarshalError", Fn: UnmarshalError} + +// Build builds a JSON payload for a JSON RPC request. +func Build(req *request.Request) { + var buf []byte + var err error + if req.ParamsFilled() { + buf, err = jsonutil.BuildJSON(req.Params) + if err != nil { + req.Error = awserr.New("SerializationError", "failed encoding JSON RPC request", err) + return + } + } else { + buf = emptyJSON + } + + if req.Metadata.TargetPrefix != "" || string(buf) != "{}" { + req.SetBufferBody(buf) + } + + if req.Metadata.TargetPrefix != "" { + target := req.Metadata.TargetPrefix + "." + req.Operation.Name + req.HTTPRequest.Header.Add("X-Amz-Target", target) + } + if req.Metadata.JSONVersion != "" { + jsonVersion := req.Metadata.JSONVersion + req.HTTPRequest.Header.Add("Content-Type", "application/x-amz-json-"+jsonVersion) + } +} + +// Unmarshal unmarshals a response for a JSON RPC service. +func Unmarshal(req *request.Request) { + defer req.HTTPResponse.Body.Close() + err := jsonutil.UnmarshalJSON(req.Data, req.HTTPResponse.Body) + if err != nil { + req.Error = awserr.New("SerializationError", "failed decoding JSON RPC response", err) + } + return +} + +// UnmarshalMeta unmarshals headers from a response for a JSON RPC service. +func UnmarshalMeta(req *request.Request) { + rest.UnmarshalMeta(req) +} + +// UnmarshalError unmarshals an error response for a JSON RPC service. +func UnmarshalError(req *request.Request) { + defer req.HTTPResponse.Body.Close() + bodyBytes, err := ioutil.ReadAll(req.HTTPResponse.Body) + if err != nil { + req.Error = awserr.New("SerializationError", "failed reading JSON RPC error response", err) + return + } + if len(bodyBytes) == 0 { + req.Error = awserr.NewRequestFailure( + awserr.New("SerializationError", req.HTTPResponse.Status, nil), + req.HTTPResponse.StatusCode, + "", + ) + return + } + var jsonErr jsonErrorResponse + if err := json.Unmarshal(bodyBytes, &jsonErr); err != nil { + req.Error = awserr.New("SerializationError", "failed decoding JSON RPC error response", err) + return + } + + codes := strings.SplitN(jsonErr.Code, "#", 2) + req.Error = awserr.NewRequestFailure( + awserr.New(codes[len(codes)-1], jsonErr.Message, nil), + req.HTTPResponse.StatusCode, + req.RequestID, + ) +} + +type jsonErrorResponse struct { + Code string `json:"__type"` + Message string `json:"message"` +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/private/protocol/jsonvalue.go b/vendor/github.com/aws/aws-sdk-go-v2/private/protocol/jsonvalue.go new file mode 100644 index 0000000..8a27043 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/private/protocol/jsonvalue.go @@ -0,0 +1,76 @@ +package protocol + +import ( + "encoding/base64" + "encoding/json" + "fmt" + "strconv" + + "github.com/aws/aws-sdk-go-v2/aws" +) + +// EscapeMode is the mode that should be use for escaping a value +type EscapeMode uint + +// The modes for escaping a value before it is marshaled, and unmarshaled. +const ( + NoEscape EscapeMode = iota + Base64Escape + QuotedEscape +) + +// EncodeJSONValue marshals the value into a JSON string, and optionally base64 +// encodes the string before returning it. +// +// Will panic if the escape mode is unknown. +func EncodeJSONValue(v aws.JSONValue, escape EscapeMode) (string, error) { + b, err := json.Marshal(v) + if err != nil { + return "", err + } + + switch escape { + case NoEscape: + return string(b), nil + case Base64Escape: + return base64.StdEncoding.EncodeToString(b), nil + case QuotedEscape: + return strconv.Quote(string(b)), nil + } + + panic(fmt.Sprintf("EncodeJSONValue called with unknown EscapeMode, %v", escape)) +} + +// DecodeJSONValue will attempt to decode the string input as a JSONValue. +// Optionally decoding base64 the value first before JSON unmarshaling. +// +// Will panic if the escape mode is unknown. +func DecodeJSONValue(v string, escape EscapeMode) (aws.JSONValue, error) { + var b []byte + var err error + + switch escape { + case NoEscape: + b = []byte(v) + case Base64Escape: + b, err = base64.StdEncoding.DecodeString(v) + case QuotedEscape: + var u string + u, err = strconv.Unquote(v) + b = []byte(u) + default: + panic(fmt.Sprintf("DecodeJSONValue called with unknown EscapeMode, %v", escape)) + } + + if err != nil { + return nil, err + } + + m := aws.JSONValue{} + err = json.Unmarshal(b, &m) + if err != nil { + return nil, err + } + + return m, nil +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/private/protocol/metadata.go b/vendor/github.com/aws/aws-sdk-go-v2/private/protocol/metadata.go new file mode 100644 index 0000000..3a94fd0 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/private/protocol/metadata.go @@ -0,0 +1,24 @@ +package protocol + +// An Attribute is a FieldValue that resides within the imediant context of +// another field. Such as XML attribute for tags. +type Attribute struct { + Name string + Value ValueMarshaler + Meta Metadata +} + +// Metadata is a collection of configuration flags for encoders to render the +// output. +type Metadata struct { + Attributes []Attribute + + Flatten bool + + ListLocationName string + MapLocationNameKey string + MapLocationNameValue string + + XMLNamespacePrefix string + XMLNamespaceURI string +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/private/protocol/path_replace.go b/vendor/github.com/aws/aws-sdk-go-v2/private/protocol/path_replace.go new file mode 100644 index 0000000..ae64a17 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/private/protocol/path_replace.go @@ -0,0 +1,136 @@ +package protocol + +import ( + "bytes" + "fmt" +) + +const ( + uriTokenStart = '{' + uriTokenStop = '}' + uriTokenSkip = '+' +) + +func bufCap(b []byte, n int) []byte { + if cap(b) < n { + return make([]byte, 0, n) + } + + return b[0:0] +} + +// PathReplace replaces path elements using field buffers +type PathReplace struct { + // May mutate path slice + path []byte + rawPath []byte + fieldBuf []byte +} + +// NewPathReplace creats a built PathReplace value that can be used to replace +// path elements. +func NewPathReplace(path string) PathReplace { + return PathReplace{ + path: []byte(path), + rawPath: []byte(path), + } +} + +// Encode returns an unescaped path, and escaped path. +func (r *PathReplace) Encode() (path string, rawPath string) { + return string(r.path), string(r.rawPath) +} + +// ReplaceElement replaces a single element in the path string. +func (r *PathReplace) ReplaceElement(key, val string) (err error) { + r.path, r.fieldBuf, err = replacePathElement(r.path, r.fieldBuf, key, val, false) + r.rawPath, r.fieldBuf, err = replacePathElement(r.rawPath, r.fieldBuf, key, val, true) + return err +} + +func replacePathElement(path, fieldBuf []byte, key, val string, escape bool) ([]byte, []byte, error) { + fieldBuf = bufCap(fieldBuf, len(key)+3) // { [+] } + fieldBuf = append(fieldBuf, uriTokenStart) + fieldBuf = append(fieldBuf, key...) + + start := bytes.Index(path, fieldBuf) + end := start + len(fieldBuf) + if start < 0 || len(path[end:]) == 0 { + // TODO what to do about error? + return path, fieldBuf, fmt.Errorf("invalid path index, start=%d,end=%d. %s", start, end, path) + } + + encodeSep := true + if path[end] == uriTokenSkip { + // '+' token means do not escape slashes + encodeSep = false + end++ + } + + if escape { + val = escapePath(val, encodeSep) + } + + if path[end] != uriTokenStop { + return path, fieldBuf, fmt.Errorf("invalid path element, does not contain token stop, %s", path) + } + end++ + + fieldBuf = bufCap(fieldBuf, len(val)) + fieldBuf = append(fieldBuf, val...) + + keyLen := end - start + valLen := len(fieldBuf) + + if keyLen == valLen { + copy(path[start:], fieldBuf) + return path, fieldBuf, nil + } + + newLen := len(path) + (valLen - keyLen) + if len(path) < newLen { + path = path[:cap(path)] + } + if cap(path) < newLen { + newURI := make([]byte, newLen) + copy(newURI, path) + path = newURI + } + + // shift + copy(path[start+valLen:], path[end:]) + path = path[:newLen] + copy(path[start:], fieldBuf) + + return path, fieldBuf, nil +} + +// copied from rest.EscapePath +// escapes part of a URL path in Amazon style +func escapePath(path string, encodeSep bool) string { + var buf bytes.Buffer + for i := 0; i < len(path); i++ { + c := path[i] + if noEscape[c] || (c == '/' && !encodeSep) { + buf.WriteByte(c) + } else { + fmt.Fprintf(&buf, "%%%02X", c) + } + } + return buf.String() +} + +var noEscape [256]bool + +func init() { + for i := 0; i < len(noEscape); i++ { + // AWS expects every character except these to be escaped + noEscape[i] = (i >= 'A' && i <= 'Z') || + (i >= 'a' && i <= 'z') || + (i >= '0' && i <= '9') || + i == '-' || + i == '.' || + i == '_' || + i == '~' + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/private/protocol/query_encoder.go b/vendor/github.com/aws/aws-sdk-go-v2/private/protocol/query_encoder.go new file mode 100644 index 0000000..baebc99 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/private/protocol/query_encoder.go @@ -0,0 +1,105 @@ +package protocol + +import ( + "fmt" + "net/url" +) + +// QueryMapEncoder builds a query string. +type QueryMapEncoder struct { + Prefix string + Query url.Values + Err error +} + +// List will return a new QueryListEncoder. +func (e *QueryMapEncoder) List(k string) ListEncoder { + if len(e.Prefix) > 0 { + k = e.Prefix + k + } + + return &QueryListEncoder{k, e.Query, nil} +} + +// Map will return a new QueryMapEncoder. +func (e *QueryMapEncoder) Map(k string) MapEncoder { + if len(e.Prefix) > 0 { + k = e.Prefix + k + } + + return &QueryMapEncoder{k, e.Query, nil} +} + +// Start does nothing. +func (e *QueryMapEncoder) Start() {} + +// End does nothing. +func (e *QueryMapEncoder) End() {} + +// MapSetValue adds a single value to the query. +func (e *QueryMapEncoder) MapSetValue(k string, v ValueMarshaler) { + if e.Err != nil { + return + } + + str, err := v.MarshalValue() + if err != nil { + e.Err = err + return + } + + if len(e.Prefix) > 0 { + k = e.Prefix + k + } + + e.Query.Add(k, str) +} + +// MapSetFields Is not implemented, query map of map is undefined. +func (e *QueryMapEncoder) MapSetFields(k string, m FieldMarshaler) { + e.Err = fmt.Errorf("query map encoder MapSetFields not supported, %s", e.Prefix) +} + +// QueryListEncoder will encode list values nested into a query key. +type QueryListEncoder struct { + Key string + Query url.Values + Err error +} + +// List will return a new QueryListEncoder. +func (e *QueryListEncoder) List() ListEncoder { + return &QueryListEncoder{e.Key, e.Query, nil} +} + +// Start does nothing for the query protocol. +func (e *QueryListEncoder) Start() {} + +// End does nothing for the query protocol. +func (e *QueryListEncoder) End() {} + +// Map will return a new QueryMapEncoder. +func (e *QueryListEncoder) Map() MapEncoder { + k := e.Key + return &QueryMapEncoder{k, e.Query, nil} +} + +// ListAddValue encodes an individual list value into the querystring. +func (e *QueryListEncoder) ListAddValue(v ValueMarshaler) { + if e.Err != nil { + return + } + + str, err := v.MarshalValue() + if err != nil { + e.Err = err + return + } + + e.Query.Add(e.Key, str) +} + +// ListAddFields Is not implemented, query list of FieldMarshaler is undefined. +func (e *QueryListEncoder) ListAddFields(m FieldMarshaler) { + e.Err = fmt.Errorf("query list encoder ListAddFields not supported, %s", e.Key) +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/private/protocol/rest/build.go b/vendor/github.com/aws/aws-sdk-go-v2/private/protocol/rest/build.go new file mode 100644 index 0000000..14c9f47 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/private/protocol/rest/build.go @@ -0,0 +1,339 @@ +// Package rest provides RESTful serialization of AWS requests and responses. +package rest + +import ( + "bytes" + "encoding/base64" + "fmt" + "io" + "net/http" + "net/url" + "path" + "reflect" + "strconv" + "strings" + "time" + + "github.com/aws/aws-sdk-go-v2/aws" + request "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/aws/awserr" + "github.com/aws/aws-sdk-go-v2/private/protocol" +) + +// RFC822 returns an RFC822 formatted timestamp for AWS protocols +const RFC822 = "Mon, 2 Jan 2006 15:04:05 GMT" + +// Whether the byte value can be sent without escaping in AWS URLs +var noEscape [256]bool + +func init() { + for i := 0; i < len(noEscape); i++ { + // AWS expects every character except these to be escaped + noEscape[i] = (i >= 'A' && i <= 'Z') || + (i >= 'a' && i <= 'z') || + (i >= '0' && i <= '9') || + i == '-' || + i == '.' || + i == '_' || + i == '~' + } +} + +// BuildHandler is a named request handler for building rest protocol requests +var BuildHandler = request.NamedHandler{Name: "awssdk.rest.Build", Fn: Build} + +// Build builds the REST component of a service request. +func Build(r *request.Request) { + if r.ParamsFilled() { + v := reflect.ValueOf(r.Params).Elem() + buildLocationElements(r, v, false) + buildBody(r, v) + } +} + +// BuildAsGET builds the REST component of a service request with the ability to hoist +// data from the body. +func BuildAsGET(r *request.Request) { + if r.ParamsFilled() { + v := reflect.ValueOf(r.Params).Elem() + buildLocationElements(r, v, true) + buildBody(r, v) + } +} + +func buildLocationElements(r *request.Request, v reflect.Value, buildGETQuery bool) { + query := r.HTTPRequest.URL.Query() + + // Setup the raw path to match the base path pattern. This is needed + // so that when the path is mutated a custom escaped version can be + // stored in RawPath that will be used by the Go client. + r.HTTPRequest.URL.RawPath = r.HTTPRequest.URL.Path + + for i := 0; i < v.NumField(); i++ { + m := v.Field(i) + if n := v.Type().Field(i).Name; n[0:1] == strings.ToLower(n[0:1]) { + continue + } + + if m.IsValid() { + field := v.Type().Field(i) + name := field.Tag.Get("locationName") + if name == "" { + name = field.Name + } + + switch m.Kind() { + case reflect.Ptr, reflect.Interface: + if !m.Elem().IsValid() { + continue + } + } + + if field.Tag.Get("ignore") != "" { + continue + } + + var err error + switch field.Tag.Get("location") { + case "headers": // header maps + err = buildHeaderMap(&r.HTTPRequest.Header, m, field.Tag) + case "header": + err = buildHeader(&r.HTTPRequest.Header, m, name, field.Tag) + case "uri": + err = buildURI(r.HTTPRequest.URL, m, name, field.Tag) + case "querystring": + err = buildQueryString(query, m, name, field.Tag) + default: + if buildGETQuery { + err = buildQueryString(query, m, name, field.Tag) + } + } + + if protocol.IsNotSetError(err) { + err = nil + } + r.Error = err + } + if r.Error != nil { + return + } + } + + r.HTTPRequest.URL.RawQuery = query.Encode() + if !r.Config.DisableRestProtocolURICleaning { + cleanPath(r.HTTPRequest.URL) + } +} + +func buildBody(r *request.Request, v reflect.Value) { + if field, ok := v.Type().FieldByName("_"); ok { + if payloadName := field.Tag.Get("payload"); payloadName != "" { + pfield, _ := v.Type().FieldByName(payloadName) + if ptag := pfield.Tag.Get("type"); ptag != "" && ptag != "structure" { + payload := reflect.Indirect(v.FieldByName(payloadName)) + if payload.IsValid() && payload.Interface() != nil { + switch reader := payload.Interface().(type) { + case io.ReadSeeker: + r.SetReaderBody(reader) + case []byte: + r.SetBufferBody(reader) + case string: + r.SetStringBody(reader) + default: + r.Error = awserr.New("SerializationError", + "failed to encode REST request", + fmt.Errorf("unknown payload type %s", payload.Type())) + } + } + } + } + } +} + +func buildHeader(header *http.Header, v reflect.Value, name string, tag reflect.StructTag) error { + var err error + str := "" + + if v.Kind() == reflect.String { + str, err = protocol.GetValue(v) + } else { + str, err = convertType(v, tag) + } + + if protocol.IsNotSetError(err) { + return nil + } else if err != nil { + return awserr.New("SerializationError", "failed to encode REST request", err) + } + + header.Add(name, str) + + return nil +} + +func buildHeaderMap(header *http.Header, v reflect.Value, tag reflect.StructTag) error { + prefix := tag.Get("locationName") + for _, key := range v.MapKeys() { + str, err := convertType(v.MapIndex(key), tag) + if protocol.IsNotSetError(err) { + continue + } else if err != nil { + return awserr.New("SerializationError", "failed to encode REST request", err) + + } + + header.Add(prefix+key.String(), str) + } + return nil +} + +func buildURI(u *url.URL, v reflect.Value, name string, tag reflect.StructTag) error { + value := "" + var err error + if v.Kind() == reflect.String { + value, err = protocol.GetValue(v) + } else { + value, err = convertType(v, tag) + } + + if protocol.IsNotSetError(err) { + return nil + } else if err != nil { + return awserr.New("SerializationError", "failed to encode REST request", err) + } + + u.Path = strings.Replace(u.Path, "{"+name+"}", value, -1) + u.Path = strings.Replace(u.Path, "{"+name+"+}", value, -1) + + u.RawPath = strings.Replace(u.RawPath, "{"+name+"}", EscapePath(value, true), -1) + u.RawPath = strings.Replace(u.RawPath, "{"+name+"+}", EscapePath(value, false), -1) + + return nil +} + +func buildQueryString(query url.Values, v reflect.Value, name string, tag reflect.StructTag) error { + if kind := v.Kind(); kind == reflect.String { + value, err := protocol.GetValue(v) + if err == nil { + query.Add(name, value) + } + return err + } else if kind == reflect.Ptr { + v = v.Elem() + } + + if v.Kind() == reflect.Slice && v.Type().Elem().Kind() == reflect.String { + for i := 0; i < v.Len(); i++ { + query.Add(name, v.Index(i).String()) + } + return nil + } + + switch value := v.Interface().(type) { + case []*string: + for _, item := range value { + query.Add(name, *item) + } + case []string: + for _, item := range value { + query.Add(name, item) + } + case map[string]*string: + for key, item := range value { + query.Add(key, *item) + } + case map[string]string: + for key, item := range value { + query.Add(key, item) + } + case map[string][]*string: + for key, items := range value { + for _, item := range items { + query.Add(key, *item) + } + } + case map[string][]string: + for key, items := range value { + for _, item := range items { + query.Add(key, item) + } + } + default: + str, err := convertType(v, tag) + if protocol.IsNotSetError(err) { + return nil + } else if err != nil { + return awserr.New("SerializationError", "failed to encode REST request", err) + } + + query.Set(name, str) + } + + return nil +} + +func cleanPath(u *url.URL) { + hasSlash := strings.HasSuffix(u.Path, "/") + + // clean up path, removing duplicate `/` + u.Path = path.Clean(u.Path) + u.RawPath = path.Clean(u.RawPath) + + if hasSlash && !strings.HasSuffix(u.Path, "/") { + u.Path += "/" + u.RawPath += "/" + } +} + +// EscapePath escapes part of a URL path in Amazon style +func EscapePath(path string, encodeSep bool) string { + var buf bytes.Buffer + for i := 0; i < len(path); i++ { + c := path[i] + if noEscape[c] || (c == '/' && !encodeSep) { + buf.WriteByte(c) + } else { + fmt.Fprintf(&buf, "%%%02X", c) + } + } + return buf.String() +} + +func convertType(v reflect.Value, tag reflect.StructTag) (str string, err error) { + v = reflect.Indirect(v) + if !v.IsValid() { + return "", &protocol.ErrValueNotSet{} + } + + switch value := v.Interface().(type) { + case string: + str = value + case []byte: + str = base64.StdEncoding.EncodeToString(value) + case bool: + str = strconv.FormatBool(value) + case int64: + str = strconv.FormatInt(value, 10) + case float64: + str = strconv.FormatFloat(value, 'f', -1, 64) + case time.Time: + str = value.UTC().Format(RFC822) + case aws.JSONValue: + if len(value) == 0 { + return "", &protocol.ErrValueNotSet{} + } + escaping := protocol.NoEscape + if tag.Get("location") == "header" { + escaping = protocol.Base64Escape + } + str, err = protocol.EncodeJSONValue(value, escaping) + if err != nil { + return "", fmt.Errorf("unable to encode JSONValue, %v", err) + } + + default: + err := fmt.Errorf("unsupported value for param %v (%s)", v.Interface(), v.Type()) + return "", err + } + return str, nil +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/private/protocol/rest/encode.go b/vendor/github.com/aws/aws-sdk-go-v2/private/protocol/rest/encode.go new file mode 100644 index 0000000..ff1ce94 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/private/protocol/rest/encode.go @@ -0,0 +1,144 @@ +package rest + +import ( + "fmt" + "io" + "net/http" + "net/url" + + "github.com/aws/aws-sdk-go-v2/private/protocol" +) + +// An Encoder provides encoding of REST URI path, query, and header components +// of an HTTP request. Can also encode a stream as the payload. +// +// Does not support SetFields. +type Encoder struct { + req *http.Request + + path protocol.PathReplace + + query url.Values + header http.Header + + payload io.ReadSeeker + + err error +} + +// NewEncoder creates a new encoder from the passed in request. All query and +// header values will be added on top of the request's existing values. Overwriting +// duplicate values. +func NewEncoder(req *http.Request) *Encoder { + e := &Encoder{ + req: req, + + path: protocol.NewPathReplace(req.URL.Path), + query: req.URL.Query(), + header: req.Header, + } + + return e +} + +// Encode will return the request and body if one was set. If the body +// payload was not set the io.ReadSeeker will be nil. +// +// returns any error if one occured while encoding the API's parameters. +func (e *Encoder) Encode() (*http.Request, io.ReadSeeker, error) { + if e.err != nil { + return nil, nil, e.err + } + + e.req.URL.Path, e.req.URL.RawPath = e.path.Encode() + e.req.URL.RawQuery = e.query.Encode() + e.req.Header = e.header + + return e.req, e.payload, nil +} + +// SetValue will set a value to the header, path, query. +// +// If the request's method is GET all BodyTarget values will be written to +// the query string. +func (e *Encoder) SetValue(t protocol.Target, k string, v protocol.ValueMarshaler, meta protocol.Metadata) { + if e.err != nil { + return + } + + var str string + str, e.err = v.MarshalValue() + if e.err != nil { + return + } + + switch t { + case protocol.HeaderTarget: + e.header.Set(k, str) + case protocol.PathTarget: + e.path.ReplaceElement(k, str) + case protocol.QueryTarget: + e.query.Set(k, str) + case protocol.BodyTarget: + if e.req.Method != "GET" { + e.err = fmt.Errorf("body target not supported for rest non-GET methods %s, %s", t, k) + return + } + e.query.Set(k, str) + default: + e.err = fmt.Errorf("unknown SetValue rest encode target, %s, %s", t, k) + } +} + +// SetStream will set the stream to the payload of the request. +func (e *Encoder) SetStream(t protocol.Target, k string, v protocol.StreamMarshaler, meta protocol.Metadata) { + if e.err != nil { + return + } + + switch t { + case protocol.PayloadTarget: + e.payload, e.err = v.MarshalStream() + default: + e.err = fmt.Errorf("unknown SetStream rest encode target, %s, %s", t, k) + } +} + +// List will set the nested list values to the header or query. +func (e *Encoder) List(t protocol.Target, k string, meta protocol.Metadata) protocol.ListEncoder { + if e.err != nil { + return nil + } + + switch t { + case protocol.QueryTarget: + return &protocol.QueryListEncoder{Key: k, Query: e.query} + case protocol.HeaderTarget: + return &protocol.HeaderListEncoder{Key: k, Header: e.header} + default: + e.err = fmt.Errorf("unknown SetList rest encode target, %s, %s", t, k) + return nil + } +} + +// Map will set the nested map values to the header or query. +func (e *Encoder) Map(t protocol.Target, k string, meta protocol.Metadata) protocol.MapEncoder { + if e.err != nil { + return nil + } + + switch t { + case protocol.QueryTarget: + return &protocol.QueryMapEncoder{Query: e.query} + case protocol.HeadersTarget: + return &protocol.HeaderMapEncoder{Prefix: k, Header: e.header} + default: + e.err = fmt.Errorf("unknown SetMap rest encode target, %s, %s", t, k) + return nil + } +} + +// SetFields is not supported for REST encoder. +func (e *Encoder) SetFields(t protocol.Target, k string, m protocol.FieldMarshaler, meta protocol.Metadata) { + e.err = fmt.Errorf("rest encoder SetFields not supported, %s, %s", t, k) +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/private/protocol/rest/payload.go b/vendor/github.com/aws/aws-sdk-go-v2/private/protocol/rest/payload.go new file mode 100644 index 0000000..4366de2 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/private/protocol/rest/payload.go @@ -0,0 +1,45 @@ +package rest + +import "reflect" + +// PayloadMember returns the payload field member of i if there is one, or nil. +func PayloadMember(i interface{}) interface{} { + if i == nil { + return nil + } + + v := reflect.ValueOf(i).Elem() + if !v.IsValid() { + return nil + } + if field, ok := v.Type().FieldByName("_"); ok { + if payloadName := field.Tag.Get("payload"); payloadName != "" { + field, _ := v.Type().FieldByName(payloadName) + if field.Tag.Get("type") != "structure" { + return nil + } + + payload := v.FieldByName(payloadName) + if payload.IsValid() || (payload.Kind() == reflect.Ptr && !payload.IsNil()) { + return payload.Interface() + } + } + } + return nil +} + +// 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 payloadName := field.Tag.Get("payload"); payloadName != "" { + if member, ok := v.Type().FieldByName(payloadName); ok { + return member.Tag.Get("type") + } + } + } + return "" +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/private/protocol/rest/unmarshal.go b/vendor/github.com/aws/aws-sdk-go-v2/private/protocol/rest/unmarshal.go new file mode 100644 index 0000000..a9f1415 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/private/protocol/rest/unmarshal.go @@ -0,0 +1,251 @@ +package rest + +import ( + "bytes" + "encoding/base64" + "fmt" + "io" + "io/ioutil" + "net/http" + "reflect" + "strconv" + "strings" + "time" + + "github.com/aws/aws-sdk-go-v2/aws" + request "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/aws/awserr" + "github.com/aws/aws-sdk-go-v2/private/protocol" +) + +// UnmarshalHandler is a named request handler for unmarshaling rest protocol requests +var UnmarshalHandler = request.NamedHandler{Name: "awssdk.rest.Unmarshal", Fn: Unmarshal} + +// UnmarshalMetaHandler is a named request handler for unmarshaling rest protocol request metadata +var UnmarshalMetaHandler = request.NamedHandler{Name: "awssdk.rest.UnmarshalMeta", Fn: UnmarshalMeta} + +// Unmarshal unmarshals the REST component of a response in a REST service. +func Unmarshal(r *request.Request) { + v := reflect.Indirect(reflect.ValueOf(r.Data)) + unmarshalBody(r, v) +} + +// UnmarshalMeta unmarshals the REST metadata of a response in a REST service +func UnmarshalMeta(r *request.Request) { + r.RequestID = r.HTTPResponse.Header.Get("X-Amzn-Requestid") + if r.RequestID == "" { + // Alternative version of request id in the header + r.RequestID = r.HTTPResponse.Header.Get("X-Amz-Request-Id") + } + v := reflect.Indirect(reflect.ValueOf(r.Data)) + unmarshalLocationElements(r, v) +} + +func unmarshalBody(r *request.Request, v reflect.Value) { + if field, ok := v.Type().FieldByName("_"); ok { + if payloadName := field.Tag.Get("payload"); payloadName != "" { + pfield, _ := v.Type().FieldByName(payloadName) + if ptag := pfield.Tag.Get("type"); ptag != "" && ptag != "structure" { + payload := v.FieldByName(payloadName) + if payload.IsValid() { + switch payload.Interface().(type) { + case []byte: + defer r.HTTPResponse.Body.Close() + b, err := ioutil.ReadAll(r.HTTPResponse.Body) + if err != nil { + r.Error = awserr.New("SerializationError", "failed to decode REST response", err) + } else { + payload.Set(reflect.ValueOf(b)) + } + case *string: + defer r.HTTPResponse.Body.Close() + b, err := ioutil.ReadAll(r.HTTPResponse.Body) + if err != nil { + r.Error = awserr.New("SerializationError", "failed to decode REST response", err) + } else { + str := string(b) + payload.Set(reflect.ValueOf(&str)) + } + default: + switch payload.Type().String() { + case "io.ReadCloser": + payload.Set(reflect.ValueOf(r.HTTPResponse.Body)) + case "io.ReadSeeker": + b, err := ioutil.ReadAll(r.HTTPResponse.Body) + if err != nil { + r.Error = awserr.New("SerializationError", + "failed to read response body", err) + return + } + payload.Set(reflect.ValueOf(ioutil.NopCloser(bytes.NewReader(b)))) + default: + io.Copy(ioutil.Discard, r.HTTPResponse.Body) + defer r.HTTPResponse.Body.Close() + r.Error = awserr.New("SerializationError", + "failed to decode REST response", + fmt.Errorf("unknown payload type %s", payload.Type())) + } + } + } + } + } + } +} + +func unmarshalLocationElements(r *request.Request, v reflect.Value) { + for i := 0; i < v.NumField(); i++ { + m, field := v.Field(i), v.Type().Field(i) + if n := field.Name; n[0:1] == strings.ToLower(n[0:1]) { + continue + } + + if m.IsValid() { + name := field.Tag.Get("locationName") + if name == "" { + name = field.Name + } + + switch field.Tag.Get("location") { + case "statusCode": + unmarshalStatusCode(m, r.HTTPResponse.StatusCode) + case "header": + err := unmarshalHeader(m, r.HTTPResponse.Header.Get(name), field.Tag) + if err != nil { + r.Error = awserr.New("SerializationError", "failed to decode REST response", err) + break + } + case "headers": + prefix := field.Tag.Get("locationName") + err := unmarshalHeaderMap(m, r.HTTPResponse.Header, prefix) + if err != nil { + r.Error = awserr.New("SerializationError", "failed to decode REST response", err) + break + } + } + } + if r.Error != nil { + return + } + } +} + +func unmarshalStatusCode(v reflect.Value, statusCode int) { + if !v.IsValid() { + return + } + + switch v.Interface().(type) { + case *int64: + s := int64(statusCode) + v.Set(reflect.ValueOf(&s)) + case int64: + s := int64(statusCode) + v.Set(reflect.ValueOf(s)) + } +} + +func unmarshalHeaderMap(r reflect.Value, headers http.Header, prefix string) error { + switch r.Interface().(type) { + case map[string]string: // we only support string map value types + out := map[string]string{} + for k, v := range headers { + k = http.CanonicalHeaderKey(k) + if strings.HasPrefix(strings.ToLower(k), strings.ToLower(prefix)) { + out[k[len(prefix):]] = v[0] + } + } + r.Set(reflect.ValueOf(out)) + } + return nil +} + +func unmarshalHeader(v reflect.Value, header string, tag reflect.StructTag) error { + isJSONValue := tag.Get("type") == "jsonvalue" + if isJSONValue { + if len(header) == 0 { + return nil + } + } else if v.Kind() == reflect.String { + if len(header) > 0 { + v.SetString(header) + } + return nil + } else if !v.IsValid() || (header == "" && v.Elem().Kind() != reflect.String) { + return nil + } + + switch v.Interface().(type) { + case *string: + v.Set(reflect.ValueOf(&header)) + case string: + v.Set(reflect.ValueOf(header)) + case []byte: + b, err := base64.StdEncoding.DecodeString(header) + if err != nil { + return err + } + v.Set(reflect.ValueOf(&b)) + case *bool: + b, err := strconv.ParseBool(header) + if err != nil { + return err + } + v.Set(reflect.ValueOf(&b)) + case bool: + b, err := strconv.ParseBool(header) + if err != nil { + return err + } + v.Set(reflect.ValueOf(b)) + case *int64: + i, err := strconv.ParseInt(header, 10, 64) + if err != nil { + return err + } + v.Set(reflect.ValueOf(&i)) + case int64: + i, err := strconv.ParseInt(header, 10, 64) + if err != nil { + return err + } + v.Set(reflect.ValueOf(i)) + case *float64: + f, err := strconv.ParseFloat(header, 64) + if err != nil { + return err + } + v.Set(reflect.ValueOf(&f)) + case float64: + f, err := strconv.ParseFloat(header, 64) + if err != nil { + return err + } + v.Set(reflect.ValueOf(f)) + case *time.Time: + t, err := time.Parse(RFC822, header) + if err != nil { + return err + } + v.Set(reflect.ValueOf(&t)) + case time.Time: + t, err := time.Parse(RFC822, header) + if err != nil { + return err + } + v.Set(reflect.ValueOf(t)) + case aws.JSONValue: + escaping := protocol.NoEscape + if tag.Get("location") == "header" { + escaping = protocol.Base64Escape + } + m, err := protocol.DecodeJSONValue(header, escaping) + if err != nil { + return err + } + v.Set(reflect.ValueOf(m)) + default: + err := fmt.Errorf("Unsupported value for param %v (%s)", v.Interface(), v.Type()) + return err + } + return nil +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/private/protocol/target.go b/vendor/github.com/aws/aws-sdk-go-v2/private/protocol/target.go new file mode 100644 index 0000000..36e65d3 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/private/protocol/target.go @@ -0,0 +1,38 @@ +package protocol + +import "fmt" + +// Target is the encode and decode targets of protocol marshaling. +type Target int + +// The protocol marshaling targets. +const ( + PathTarget Target = iota + QueryTarget + HeaderTarget + HeadersTarget + StatusCodeTarget + BodyTarget + PayloadTarget +) + +func (e Target) String() string { + switch e { + case PathTarget: + return "Path" + case QueryTarget: + return "Query" + case HeaderTarget: + return "Header" + case HeadersTarget: + return "Headers" + case StatusCodeTarget: + return "StatusCode" + case BodyTarget: + return "Body" + case PayloadTarget: + return "Payload" + default: + panic(fmt.Sprintf("// unknown encoding target, %d", e)) + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/private/protocol/unmarshal.go b/vendor/github.com/aws/aws-sdk-go-v2/private/protocol/unmarshal.go new file mode 100644 index 0000000..de04834 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/private/protocol/unmarshal.go @@ -0,0 +1,21 @@ +package protocol + +import ( + "io" + "io/ioutil" + + request "github.com/aws/aws-sdk-go-v2/aws" +) + +// UnmarshalDiscardBodyHandler is a named request handler to empty and close a response's body +var UnmarshalDiscardBodyHandler = request.NamedHandler{Name: "awssdk.shared.UnmarshalDiscardBody", Fn: UnmarshalDiscardBody} + +// UnmarshalDiscardBody is a request handler to empty a response's body and closing it. +func UnmarshalDiscardBody(r *request.Request) { + if r.HTTPResponse == nil || r.HTTPResponse.Body == nil { + return + } + + io.Copy(ioutil.Discard, r.HTTPResponse.Body) + r.HTTPResponse.Body.Close() +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/private/protocol/value.go b/vendor/github.com/aws/aws-sdk-go-v2/private/protocol/value.go new file mode 100644 index 0000000..892b286 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/private/protocol/value.go @@ -0,0 +1,30 @@ +package protocol + +import ( + "reflect" +) + +// ErrValueNotSet is an error that is returned when the value +// has not been set. +type ErrValueNotSet struct{} + +func (err *ErrValueNotSet) Error() string { + return "value not set" +} + +// IsNotSetError will return true if the error is of ErrValueNotSet +func IsNotSetError(err error) bool { + _, ok := err.(*ErrValueNotSet) + return ok +} + +// GetValue will return the value that is associated with the reflect.Value. +// If that value is not set, this will return an ErrValueNotSet +func GetValue(r reflect.Value) (string, error) { + val := r.String() + if len(val) == 0 { + return "", &ErrValueNotSet{} + } + + return val, nil +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/acmpca/acmpcaiface/interface.go b/vendor/github.com/aws/aws-sdk-go-v2/service/acmpca/acmpcaiface/interface.go new file mode 100644 index 0000000..dd66a19 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/acmpca/acmpcaiface/interface.go @@ -0,0 +1,110 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package acmpcaiface provides an interface to enable mocking the AWS Certificate Manager Private Certificate Authority service client +// for testing your code. +// +// It is important to note that this interface will have breaking changes +// when the service model is updated and adds new API operations, paginators, +// and waiters. +package acmpcaiface + +import ( + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/acmpca" +) + +// ACMPCAAPI provides an interface to enable mocking the +// acmpca.ACMPCA service client's API operation, +// paginators, and waiters. This make unit testing your code that calls out +// to the SDK's service client's calls easier. +// +// The best way to use this interface is so the SDK's service client's calls +// can be stubbed out for unit testing your code with the SDK without needing +// to inject custom request handlers into the SDK's request pipeline. +// +// // myFunc uses an SDK service client to make a request to +// // AWS Certificate Manager Private Certificate Authority. +// func myFunc(svc acmpcaiface.ACMPCAAPI) bool { +// // Make svc.CreateCertificateAuthority request +// } +// +// func main() { +// cfg, err := external.LoadDefaultAWSConfig() +// if err != nil { +// panic("failed to load config, " + err.Error()) +// } +// +// svc := acmpca.New(cfg) +// +// myFunc(svc) +// } +// +// In your _test.go file: +// +// // Define a mock struct to be used in your unit tests of myFunc. +// type mockACMPCAClient struct { +// acmpcaiface.ACMPCAAPI +// } +// func (m *mockACMPCAClient) CreateCertificateAuthority(input *acmpca.CreateCertificateAuthorityInput) (*acmpca.CreateCertificateAuthorityOutput, error) { +// // mock response/functionality +// } +// +// func TestMyFunc(t *testing.T) { +// // Setup Test +// mockSvc := &mockACMPCAClient{} +// +// myfunc(mockSvc) +// +// // Verify myFunc's functionality +// } +// +// It is important to note that this interface will have breaking changes +// when the service model is updated and adds new API operations, paginators, +// and waiters. Its suggested to use the pattern above for testing, or using +// tooling to generate mocks to satisfy the interfaces. +type ACMPCAAPI interface { + CreateCertificateAuthorityRequest(*acmpca.CreateCertificateAuthorityInput) acmpca.CreateCertificateAuthorityRequest + + CreateCertificateAuthorityAuditReportRequest(*acmpca.CreateCertificateAuthorityAuditReportInput) acmpca.CreateCertificateAuthorityAuditReportRequest + + DeleteCertificateAuthorityRequest(*acmpca.DeleteCertificateAuthorityInput) acmpca.DeleteCertificateAuthorityRequest + + DescribeCertificateAuthorityRequest(*acmpca.DescribeCertificateAuthorityInput) acmpca.DescribeCertificateAuthorityRequest + + DescribeCertificateAuthorityAuditReportRequest(*acmpca.DescribeCertificateAuthorityAuditReportInput) acmpca.DescribeCertificateAuthorityAuditReportRequest + + GetCertificateRequest(*acmpca.GetCertificateInput) acmpca.GetCertificateRequest + + GetCertificateAuthorityCertificateRequest(*acmpca.GetCertificateAuthorityCertificateInput) acmpca.GetCertificateAuthorityCertificateRequest + + GetCertificateAuthorityCsrRequest(*acmpca.GetCertificateAuthorityCsrInput) acmpca.GetCertificateAuthorityCsrRequest + + ImportCertificateAuthorityCertificateRequest(*acmpca.ImportCertificateAuthorityCertificateInput) acmpca.ImportCertificateAuthorityCertificateRequest + + IssueCertificateRequest(*acmpca.IssueCertificateInput) acmpca.IssueCertificateRequest + + ListCertificateAuthoritiesRequest(*acmpca.ListCertificateAuthoritiesInput) acmpca.ListCertificateAuthoritiesRequest + + ListTagsRequest(*acmpca.ListTagsInput) acmpca.ListTagsRequest + + RestoreCertificateAuthorityRequest(*acmpca.RestoreCertificateAuthorityInput) acmpca.RestoreCertificateAuthorityRequest + + RevokeCertificateRequest(*acmpca.RevokeCertificateInput) acmpca.RevokeCertificateRequest + + TagCertificateAuthorityRequest(*acmpca.TagCertificateAuthorityInput) acmpca.TagCertificateAuthorityRequest + + UntagCertificateAuthorityRequest(*acmpca.UntagCertificateAuthorityInput) acmpca.UntagCertificateAuthorityRequest + + UpdateCertificateAuthorityRequest(*acmpca.UpdateCertificateAuthorityInput) acmpca.UpdateCertificateAuthorityRequest + + WaitUntilAuditReportCreated(*acmpca.DescribeCertificateAuthorityAuditReportInput) error + WaitUntilAuditReportCreatedWithContext(aws.Context, *acmpca.DescribeCertificateAuthorityAuditReportInput, ...aws.WaiterOption) error + + WaitUntilCertificateAuthorityCSRCreated(*acmpca.GetCertificateAuthorityCsrInput) error + WaitUntilCertificateAuthorityCSRCreatedWithContext(aws.Context, *acmpca.GetCertificateAuthorityCsrInput, ...aws.WaiterOption) error + + WaitUntilCertificateIssued(*acmpca.GetCertificateInput) error + WaitUntilCertificateIssuedWithContext(aws.Context, *acmpca.GetCertificateInput, ...aws.WaiterOption) error +} + +var _ ACMPCAAPI = (*acmpca.ACMPCA)(nil) diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/acmpca/api.go b/vendor/github.com/aws/aws-sdk-go-v2/service/acmpca/api.go new file mode 100644 index 0000000..5b39903 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/acmpca/api.go @@ -0,0 +1,3066 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +package acmpca + +import ( + "fmt" + "time" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/internal/awsutil" + "github.com/aws/aws-sdk-go-v2/private/protocol" + "github.com/aws/aws-sdk-go-v2/private/protocol/jsonrpc" +) + +const opCreateCertificateAuthority = "CreateCertificateAuthority" + +// CreateCertificateAuthorityRequest is a API request type for the CreateCertificateAuthority API operation. +type CreateCertificateAuthorityRequest struct { + *aws.Request + Input *CreateCertificateAuthorityInput + Copy func(*CreateCertificateAuthorityInput) CreateCertificateAuthorityRequest +} + +// Send marshals and sends the CreateCertificateAuthority API request. +func (r CreateCertificateAuthorityRequest) Send() (*CreateCertificateAuthorityOutput, error) { + err := r.Request.Send() + if err != nil { + return nil, err + } + + return r.Request.Data.(*CreateCertificateAuthorityOutput), nil +} + +// CreateCertificateAuthorityRequest returns a request value for making API operation for +// AWS Certificate Manager Private Certificate Authority. +// +// Creates a private subordinate certificate authority (CA). You must specify +// the CA configuration, the revocation configuration, the CA type, and an optional +// idempotency token. The CA configuration specifies the name of the algorithm +// and key size to be used to create the CA private key, the type of signing +// algorithm that the CA uses to sign, and X.500 subject information. The CRL +// (certificate revocation list) configuration specifies the CRL expiration +// period in days (the validity period of the CRL), the Amazon S3 bucket that +// will contain the CRL, and a CNAME alias for the S3 bucket that is included +// in certificates issued by the CA. If successful, this operation returns the +// Amazon Resource Name (ARN) of the CA. +// +// // Example sending a request using the CreateCertificateAuthorityRequest method. +// req := client.CreateCertificateAuthorityRequest(params) +// resp, err := req.Send() +// if err == nil { +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/CreateCertificateAuthority +func (c *ACMPCA) CreateCertificateAuthorityRequest(input *CreateCertificateAuthorityInput) CreateCertificateAuthorityRequest { + op := &aws.Operation{ + Name: opCreateCertificateAuthority, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &CreateCertificateAuthorityInput{} + } + + output := &CreateCertificateAuthorityOutput{} + req := c.newRequest(op, input, output) + output.responseMetadata = aws.Response{Request: req} + + return CreateCertificateAuthorityRequest{Request: req, Input: input, Copy: c.CreateCertificateAuthorityRequest} +} + +const opCreateCertificateAuthorityAuditReport = "CreateCertificateAuthorityAuditReport" + +// CreateCertificateAuthorityAuditReportRequest is a API request type for the CreateCertificateAuthorityAuditReport API operation. +type CreateCertificateAuthorityAuditReportRequest struct { + *aws.Request + Input *CreateCertificateAuthorityAuditReportInput + Copy func(*CreateCertificateAuthorityAuditReportInput) CreateCertificateAuthorityAuditReportRequest +} + +// Send marshals and sends the CreateCertificateAuthorityAuditReport API request. +func (r CreateCertificateAuthorityAuditReportRequest) Send() (*CreateCertificateAuthorityAuditReportOutput, error) { + err := r.Request.Send() + if err != nil { + return nil, err + } + + return r.Request.Data.(*CreateCertificateAuthorityAuditReportOutput), nil +} + +// CreateCertificateAuthorityAuditReportRequest returns a request value for making API operation for +// AWS Certificate Manager Private Certificate Authority. +// +// Creates an audit report that lists every time that the your CA private key +// is used. The report is saved in the Amazon S3 bucket that you specify on +// input. The IssueCertificate and RevokeCertificate operations use the private +// key. You can generate a new report every 30 minutes. +// +// // Example sending a request using the CreateCertificateAuthorityAuditReportRequest method. +// req := client.CreateCertificateAuthorityAuditReportRequest(params) +// resp, err := req.Send() +// if err == nil { +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/CreateCertificateAuthorityAuditReport +func (c *ACMPCA) CreateCertificateAuthorityAuditReportRequest(input *CreateCertificateAuthorityAuditReportInput) CreateCertificateAuthorityAuditReportRequest { + op := &aws.Operation{ + Name: opCreateCertificateAuthorityAuditReport, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &CreateCertificateAuthorityAuditReportInput{} + } + + output := &CreateCertificateAuthorityAuditReportOutput{} + req := c.newRequest(op, input, output) + output.responseMetadata = aws.Response{Request: req} + + return CreateCertificateAuthorityAuditReportRequest{Request: req, Input: input, Copy: c.CreateCertificateAuthorityAuditReportRequest} +} + +const opDeleteCertificateAuthority = "DeleteCertificateAuthority" + +// DeleteCertificateAuthorityRequest is a API request type for the DeleteCertificateAuthority API operation. +type DeleteCertificateAuthorityRequest struct { + *aws.Request + Input *DeleteCertificateAuthorityInput + Copy func(*DeleteCertificateAuthorityInput) DeleteCertificateAuthorityRequest +} + +// Send marshals and sends the DeleteCertificateAuthority API request. +func (r DeleteCertificateAuthorityRequest) Send() (*DeleteCertificateAuthorityOutput, error) { + err := r.Request.Send() + if err != nil { + return nil, err + } + + return r.Request.Data.(*DeleteCertificateAuthorityOutput), nil +} + +// DeleteCertificateAuthorityRequest returns a request value for making API operation for +// AWS Certificate Manager Private Certificate Authority. +// +// Deletes a private certificate authority (CA). You must provide the ARN (Amazon +// Resource Name) of the private CA that you want to delete. You can find the +// ARN by calling the ListCertificateAuthorities operation. Before you can delete +// a CA, you must disable it. Call the UpdateCertificateAuthority operation +// and set the CertificateAuthorityStatus parameter to DISABLED. +// +// Additionally, you can delete a CA if you are waiting for it to be created +// (the Status field of the CertificateAuthority is CREATING). You can also +// delete it if the CA has been created but you haven't yet imported the signed +// certificate (the Status is PENDING_CERTIFICATE) into ACM PCA. +// +// If the CA is in one of the aforementioned states and you call DeleteCertificateAuthority, +// the CA's status changes to DELETED. However, the CA won't be permentantly +// deleted until the restoration period has passed. By default, if you do not +// set the PermanentDeletionTimeInDays parameter, the CA remains restorable +// for 30 days. You can set the parameter from 7 to 30 days. The DescribeCertificateAuthority +// operation returns the time remaining in the restoration window of a Private +// CA in the DELETED state. To restore an eligable CA, call the RestoreCertificateAuthority +// operation. +// +// // Example sending a request using the DeleteCertificateAuthorityRequest method. +// req := client.DeleteCertificateAuthorityRequest(params) +// resp, err := req.Send() +// if err == nil { +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/DeleteCertificateAuthority +func (c *ACMPCA) DeleteCertificateAuthorityRequest(input *DeleteCertificateAuthorityInput) DeleteCertificateAuthorityRequest { + op := &aws.Operation{ + Name: opDeleteCertificateAuthority, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &DeleteCertificateAuthorityInput{} + } + + output := &DeleteCertificateAuthorityOutput{} + req := c.newRequest(op, input, output) + req.Handlers.Unmarshal.Remove(jsonrpc.UnmarshalHandler) + req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + output.responseMetadata = aws.Response{Request: req} + + return DeleteCertificateAuthorityRequest{Request: req, Input: input, Copy: c.DeleteCertificateAuthorityRequest} +} + +const opDescribeCertificateAuthority = "DescribeCertificateAuthority" + +// DescribeCertificateAuthorityRequest is a API request type for the DescribeCertificateAuthority API operation. +type DescribeCertificateAuthorityRequest struct { + *aws.Request + Input *DescribeCertificateAuthorityInput + Copy func(*DescribeCertificateAuthorityInput) DescribeCertificateAuthorityRequest +} + +// Send marshals and sends the DescribeCertificateAuthority API request. +func (r DescribeCertificateAuthorityRequest) Send() (*DescribeCertificateAuthorityOutput, error) { + err := r.Request.Send() + if err != nil { + return nil, err + } + + return r.Request.Data.(*DescribeCertificateAuthorityOutput), nil +} + +// DescribeCertificateAuthorityRequest returns a request value for making API operation for +// AWS Certificate Manager Private Certificate Authority. +// +// Lists information about your private certificate authority (CA). You specify +// the private CA on input by its ARN (Amazon Resource Name). The output contains +// the status of your CA. This can be any of the following: +// +// * CREATING - ACM PCA is creating your private certificate authority. +// +// * PENDING_CERTIFICATE - The certificate is pending. You must use your +// on-premises root or subordinate CA to sign your private CA CSR and then +// import it into PCA. +// +// * ACTIVE - Your private CA is active. +// +// * DISABLED - Your private CA has been disabled. +// +// * EXPIRED - Your private CA certificate has expired. +// +// * FAILED - Your private CA has failed. Your CA can fail because of problems +// such a network outage or backend AWS failure or other errors. A failed +// CA can never return to the pending state. You must create a new CA. +// +// * DELETED - Your private CA is within the restoration period, after which +// it is permanently deleted. The length of time remaining in the CA's restoration +// period is also included in this operation's output. +// +// // Example sending a request using the DescribeCertificateAuthorityRequest method. +// req := client.DescribeCertificateAuthorityRequest(params) +// resp, err := req.Send() +// if err == nil { +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/DescribeCertificateAuthority +func (c *ACMPCA) DescribeCertificateAuthorityRequest(input *DescribeCertificateAuthorityInput) DescribeCertificateAuthorityRequest { + op := &aws.Operation{ + Name: opDescribeCertificateAuthority, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &DescribeCertificateAuthorityInput{} + } + + output := &DescribeCertificateAuthorityOutput{} + req := c.newRequest(op, input, output) + output.responseMetadata = aws.Response{Request: req} + + return DescribeCertificateAuthorityRequest{Request: req, Input: input, Copy: c.DescribeCertificateAuthorityRequest} +} + +const opDescribeCertificateAuthorityAuditReport = "DescribeCertificateAuthorityAuditReport" + +// DescribeCertificateAuthorityAuditReportRequest is a API request type for the DescribeCertificateAuthorityAuditReport API operation. +type DescribeCertificateAuthorityAuditReportRequest struct { + *aws.Request + Input *DescribeCertificateAuthorityAuditReportInput + Copy func(*DescribeCertificateAuthorityAuditReportInput) DescribeCertificateAuthorityAuditReportRequest +} + +// Send marshals and sends the DescribeCertificateAuthorityAuditReport API request. +func (r DescribeCertificateAuthorityAuditReportRequest) Send() (*DescribeCertificateAuthorityAuditReportOutput, error) { + err := r.Request.Send() + if err != nil { + return nil, err + } + + return r.Request.Data.(*DescribeCertificateAuthorityAuditReportOutput), nil +} + +// DescribeCertificateAuthorityAuditReportRequest returns a request value for making API operation for +// AWS Certificate Manager Private Certificate Authority. +// +// Lists information about a specific audit report created by calling the CreateCertificateAuthorityAuditReport +// operation. Audit information is created every time the certificate authority +// (CA) private key is used. The private key is used when you call the IssueCertificate +// operation or the RevokeCertificate operation. +// +// // Example sending a request using the DescribeCertificateAuthorityAuditReportRequest method. +// req := client.DescribeCertificateAuthorityAuditReportRequest(params) +// resp, err := req.Send() +// if err == nil { +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/DescribeCertificateAuthorityAuditReport +func (c *ACMPCA) DescribeCertificateAuthorityAuditReportRequest(input *DescribeCertificateAuthorityAuditReportInput) DescribeCertificateAuthorityAuditReportRequest { + op := &aws.Operation{ + Name: opDescribeCertificateAuthorityAuditReport, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &DescribeCertificateAuthorityAuditReportInput{} + } + + output := &DescribeCertificateAuthorityAuditReportOutput{} + req := c.newRequest(op, input, output) + output.responseMetadata = aws.Response{Request: req} + + return DescribeCertificateAuthorityAuditReportRequest{Request: req, Input: input, Copy: c.DescribeCertificateAuthorityAuditReportRequest} +} + +const opGetCertificate = "GetCertificate" + +// GetCertificateRequest is a API request type for the GetCertificate API operation. +type GetCertificateRequest struct { + *aws.Request + Input *GetCertificateInput + Copy func(*GetCertificateInput) GetCertificateRequest +} + +// Send marshals and sends the GetCertificate API request. +func (r GetCertificateRequest) Send() (*GetCertificateOutput, error) { + err := r.Request.Send() + if err != nil { + return nil, err + } + + return r.Request.Data.(*GetCertificateOutput), nil +} + +// GetCertificateRequest returns a request value for making API operation for +// AWS Certificate Manager Private Certificate Authority. +// +// Retrieves a certificate from your private CA. The ARN of the certificate +// is returned when you call the IssueCertificate operation. You must specify +// both the ARN of your private CA and the ARN of the issued certificate when +// calling the GetCertificate operation. You can retrieve the certificate if +// it is in the ISSUED state. You can call the CreateCertificateAuthorityAuditReport +// operation to create a report that contains information about all of the certificates +// issued and revoked by your private CA. +// +// // Example sending a request using the GetCertificateRequest method. +// req := client.GetCertificateRequest(params) +// resp, err := req.Send() +// if err == nil { +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/GetCertificate +func (c *ACMPCA) GetCertificateRequest(input *GetCertificateInput) GetCertificateRequest { + op := &aws.Operation{ + Name: opGetCertificate, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &GetCertificateInput{} + } + + output := &GetCertificateOutput{} + req := c.newRequest(op, input, output) + output.responseMetadata = aws.Response{Request: req} + + return GetCertificateRequest{Request: req, Input: input, Copy: c.GetCertificateRequest} +} + +const opGetCertificateAuthorityCertificate = "GetCertificateAuthorityCertificate" + +// GetCertificateAuthorityCertificateRequest is a API request type for the GetCertificateAuthorityCertificate API operation. +type GetCertificateAuthorityCertificateRequest struct { + *aws.Request + Input *GetCertificateAuthorityCertificateInput + Copy func(*GetCertificateAuthorityCertificateInput) GetCertificateAuthorityCertificateRequest +} + +// Send marshals and sends the GetCertificateAuthorityCertificate API request. +func (r GetCertificateAuthorityCertificateRequest) Send() (*GetCertificateAuthorityCertificateOutput, error) { + err := r.Request.Send() + if err != nil { + return nil, err + } + + return r.Request.Data.(*GetCertificateAuthorityCertificateOutput), nil +} + +// GetCertificateAuthorityCertificateRequest returns a request value for making API operation for +// AWS Certificate Manager Private Certificate Authority. +// +// Retrieves the certificate and certificate chain for your private certificate +// authority (CA). Both the certificate and the chain are base64 PEM-encoded. +// The chain does not include the CA certificate. Each certificate in the chain +// signs the one before it. +// +// // Example sending a request using the GetCertificateAuthorityCertificateRequest method. +// req := client.GetCertificateAuthorityCertificateRequest(params) +// resp, err := req.Send() +// if err == nil { +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/GetCertificateAuthorityCertificate +func (c *ACMPCA) GetCertificateAuthorityCertificateRequest(input *GetCertificateAuthorityCertificateInput) GetCertificateAuthorityCertificateRequest { + op := &aws.Operation{ + Name: opGetCertificateAuthorityCertificate, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &GetCertificateAuthorityCertificateInput{} + } + + output := &GetCertificateAuthorityCertificateOutput{} + req := c.newRequest(op, input, output) + output.responseMetadata = aws.Response{Request: req} + + return GetCertificateAuthorityCertificateRequest{Request: req, Input: input, Copy: c.GetCertificateAuthorityCertificateRequest} +} + +const opGetCertificateAuthorityCsr = "GetCertificateAuthorityCsr" + +// GetCertificateAuthorityCsrRequest is a API request type for the GetCertificateAuthorityCsr API operation. +type GetCertificateAuthorityCsrRequest struct { + *aws.Request + Input *GetCertificateAuthorityCsrInput + Copy func(*GetCertificateAuthorityCsrInput) GetCertificateAuthorityCsrRequest +} + +// Send marshals and sends the GetCertificateAuthorityCsr API request. +func (r GetCertificateAuthorityCsrRequest) Send() (*GetCertificateAuthorityCsrOutput, error) { + err := r.Request.Send() + if err != nil { + return nil, err + } + + return r.Request.Data.(*GetCertificateAuthorityCsrOutput), nil +} + +// GetCertificateAuthorityCsrRequest returns a request value for making API operation for +// AWS Certificate Manager Private Certificate Authority. +// +// Retrieves the certificate signing request (CSR) for your private certificate +// authority (CA). The CSR is created when you call the CreateCertificateAuthority +// operation. Take the CSR to your on-premises X.509 infrastructure and sign +// it by using your root or a subordinate CA. Then import the signed certificate +// back into ACM PCA by calling the ImportCertificateAuthorityCertificate operation. +// The CSR is returned as a base64 PEM-encoded string. +// +// // Example sending a request using the GetCertificateAuthorityCsrRequest method. +// req := client.GetCertificateAuthorityCsrRequest(params) +// resp, err := req.Send() +// if err == nil { +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/GetCertificateAuthorityCsr +func (c *ACMPCA) GetCertificateAuthorityCsrRequest(input *GetCertificateAuthorityCsrInput) GetCertificateAuthorityCsrRequest { + op := &aws.Operation{ + Name: opGetCertificateAuthorityCsr, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &GetCertificateAuthorityCsrInput{} + } + + output := &GetCertificateAuthorityCsrOutput{} + req := c.newRequest(op, input, output) + output.responseMetadata = aws.Response{Request: req} + + return GetCertificateAuthorityCsrRequest{Request: req, Input: input, Copy: c.GetCertificateAuthorityCsrRequest} +} + +const opImportCertificateAuthorityCertificate = "ImportCertificateAuthorityCertificate" + +// ImportCertificateAuthorityCertificateRequest is a API request type for the ImportCertificateAuthorityCertificate API operation. +type ImportCertificateAuthorityCertificateRequest struct { + *aws.Request + Input *ImportCertificateAuthorityCertificateInput + Copy func(*ImportCertificateAuthorityCertificateInput) ImportCertificateAuthorityCertificateRequest +} + +// Send marshals and sends the ImportCertificateAuthorityCertificate API request. +func (r ImportCertificateAuthorityCertificateRequest) Send() (*ImportCertificateAuthorityCertificateOutput, error) { + err := r.Request.Send() + if err != nil { + return nil, err + } + + return r.Request.Data.(*ImportCertificateAuthorityCertificateOutput), nil +} + +// ImportCertificateAuthorityCertificateRequest returns a request value for making API operation for +// AWS Certificate Manager Private Certificate Authority. +// +// Imports your signed private CA certificate into ACM PCA. Before you can call +// this operation, you must create the private certificate authority by calling +// the CreateCertificateAuthority operation. You must then generate a certificate +// signing request (CSR) by calling the GetCertificateAuthorityCsr operation. +// Take the CSR to your on-premises CA and use the root certificate or a subordinate +// certificate to sign it. Create a certificate chain and copy the signed certificate +// and the certificate chain to your working directory. +// +// Your certificate chain must not include the private CA certificate that you +// are importing. +// +// Your on-premises CA certificate must be the last certificate in your chain. +// The subordinate certificate, if any, that your root CA signed must be next +// to last. The subordinate certificate signed by the preceding subordinate +// CA must come next, and so on until your chain is built. +// +// The chain must be PEM-encoded. +// +// // Example sending a request using the ImportCertificateAuthorityCertificateRequest method. +// req := client.ImportCertificateAuthorityCertificateRequest(params) +// resp, err := req.Send() +// if err == nil { +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/ImportCertificateAuthorityCertificate +func (c *ACMPCA) ImportCertificateAuthorityCertificateRequest(input *ImportCertificateAuthorityCertificateInput) ImportCertificateAuthorityCertificateRequest { + op := &aws.Operation{ + Name: opImportCertificateAuthorityCertificate, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &ImportCertificateAuthorityCertificateInput{} + } + + output := &ImportCertificateAuthorityCertificateOutput{} + req := c.newRequest(op, input, output) + req.Handlers.Unmarshal.Remove(jsonrpc.UnmarshalHandler) + req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + output.responseMetadata = aws.Response{Request: req} + + return ImportCertificateAuthorityCertificateRequest{Request: req, Input: input, Copy: c.ImportCertificateAuthorityCertificateRequest} +} + +const opIssueCertificate = "IssueCertificate" + +// IssueCertificateRequest is a API request type for the IssueCertificate API operation. +type IssueCertificateRequest struct { + *aws.Request + Input *IssueCertificateInput + Copy func(*IssueCertificateInput) IssueCertificateRequest +} + +// Send marshals and sends the IssueCertificate API request. +func (r IssueCertificateRequest) Send() (*IssueCertificateOutput, error) { + err := r.Request.Send() + if err != nil { + return nil, err + } + + return r.Request.Data.(*IssueCertificateOutput), nil +} + +// IssueCertificateRequest returns a request value for making API operation for +// AWS Certificate Manager Private Certificate Authority. +// +// Uses your private certificate authority (CA) to issue a client certificate. +// This operation returns the Amazon Resource Name (ARN) of the certificate. +// You can retrieve the certificate by calling the GetCertificate operation +// and specifying the ARN. +// +// You cannot use the ACM ListCertificateAuthorities operation to retrieve the +// ARNs of the certificates that you issue by using ACM PCA. +// +// // Example sending a request using the IssueCertificateRequest method. +// req := client.IssueCertificateRequest(params) +// resp, err := req.Send() +// if err == nil { +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/IssueCertificate +func (c *ACMPCA) IssueCertificateRequest(input *IssueCertificateInput) IssueCertificateRequest { + op := &aws.Operation{ + Name: opIssueCertificate, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &IssueCertificateInput{} + } + + output := &IssueCertificateOutput{} + req := c.newRequest(op, input, output) + output.responseMetadata = aws.Response{Request: req} + + return IssueCertificateRequest{Request: req, Input: input, Copy: c.IssueCertificateRequest} +} + +const opListCertificateAuthorities = "ListCertificateAuthorities" + +// ListCertificateAuthoritiesRequest is a API request type for the ListCertificateAuthorities API operation. +type ListCertificateAuthoritiesRequest struct { + *aws.Request + Input *ListCertificateAuthoritiesInput + Copy func(*ListCertificateAuthoritiesInput) ListCertificateAuthoritiesRequest +} + +// Send marshals and sends the ListCertificateAuthorities API request. +func (r ListCertificateAuthoritiesRequest) Send() (*ListCertificateAuthoritiesOutput, error) { + err := r.Request.Send() + if err != nil { + return nil, err + } + + return r.Request.Data.(*ListCertificateAuthoritiesOutput), nil +} + +// ListCertificateAuthoritiesRequest returns a request value for making API operation for +// AWS Certificate Manager Private Certificate Authority. +// +// Lists the private certificate authorities that you created by using the CreateCertificateAuthority +// operation. +// +// // Example sending a request using the ListCertificateAuthoritiesRequest method. +// req := client.ListCertificateAuthoritiesRequest(params) +// resp, err := req.Send() +// if err == nil { +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/ListCertificateAuthorities +func (c *ACMPCA) ListCertificateAuthoritiesRequest(input *ListCertificateAuthoritiesInput) ListCertificateAuthoritiesRequest { + op := &aws.Operation{ + Name: opListCertificateAuthorities, + HTTPMethod: "POST", + HTTPPath: "/", + Paginator: &aws.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, + } + + if input == nil { + input = &ListCertificateAuthoritiesInput{} + } + + output := &ListCertificateAuthoritiesOutput{} + req := c.newRequest(op, input, output) + output.responseMetadata = aws.Response{Request: req} + + return ListCertificateAuthoritiesRequest{Request: req, Input: input, Copy: c.ListCertificateAuthoritiesRequest} +} + +// Paginate pages iterates over the pages of a ListCertificateAuthoritiesRequest operation, +// calling the Next method for each page. Using the paginators Next +// method will depict whether or not there are more pages. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a ListCertificateAuthorities operation. +// req := client.ListCertificateAuthoritiesRequest(input) +// p := req.Paginate() +// for p.Next() { +// page := p.CurrentPage() +// } +// +// if err := p.Err(); err != nil { +// return err +// } +// +func (p *ListCertificateAuthoritiesRequest) Paginate(opts ...aws.Option) ListCertificateAuthoritiesPager { + return ListCertificateAuthoritiesPager{ + Pager: aws.Pager{ + NewRequest: func() (*aws.Request, error) { + var inCpy *ListCertificateAuthoritiesInput + if p.Input != nil { + tmp := *p.Input + inCpy = &tmp + } + + req := p.Copy(inCpy) + req.ApplyOptions(opts...) + + return req.Request, nil + }, + }, + } +} + +// ListCertificateAuthoritiesPager is used to paginate the request. This can be done by +// calling Next and CurrentPage. +type ListCertificateAuthoritiesPager struct { + aws.Pager +} + +func (p *ListCertificateAuthoritiesPager) CurrentPage() *ListCertificateAuthoritiesOutput { + return p.Pager.CurrentPage().(*ListCertificateAuthoritiesOutput) +} + +const opListTags = "ListTags" + +// ListTagsRequest is a API request type for the ListTags API operation. +type ListTagsRequest struct { + *aws.Request + Input *ListTagsInput + Copy func(*ListTagsInput) ListTagsRequest +} + +// Send marshals and sends the ListTags API request. +func (r ListTagsRequest) Send() (*ListTagsOutput, error) { + err := r.Request.Send() + if err != nil { + return nil, err + } + + return r.Request.Data.(*ListTagsOutput), nil +} + +// ListTagsRequest returns a request value for making API operation for +// AWS Certificate Manager Private Certificate Authority. +// +// Lists the tags, if any, that are associated with your private CA. Tags are +// labels that you can use to identify and organize your CAs. Each tag consists +// of a key and an optional value. Call the TagCertificateAuthority operation +// to add one or more tags to your CA. Call the UntagCertificateAuthority operation +// to remove tags. +// +// // Example sending a request using the ListTagsRequest method. +// req := client.ListTagsRequest(params) +// resp, err := req.Send() +// if err == nil { +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/ListTags +func (c *ACMPCA) ListTagsRequest(input *ListTagsInput) ListTagsRequest { + op := &aws.Operation{ + Name: opListTags, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &ListTagsInput{} + } + + output := &ListTagsOutput{} + req := c.newRequest(op, input, output) + output.responseMetadata = aws.Response{Request: req} + + return ListTagsRequest{Request: req, Input: input, Copy: c.ListTagsRequest} +} + +const opRestoreCertificateAuthority = "RestoreCertificateAuthority" + +// RestoreCertificateAuthorityRequest is a API request type for the RestoreCertificateAuthority API operation. +type RestoreCertificateAuthorityRequest struct { + *aws.Request + Input *RestoreCertificateAuthorityInput + Copy func(*RestoreCertificateAuthorityInput) RestoreCertificateAuthorityRequest +} + +// Send marshals and sends the RestoreCertificateAuthority API request. +func (r RestoreCertificateAuthorityRequest) Send() (*RestoreCertificateAuthorityOutput, error) { + err := r.Request.Send() + if err != nil { + return nil, err + } + + return r.Request.Data.(*RestoreCertificateAuthorityOutput), nil +} + +// RestoreCertificateAuthorityRequest returns a request value for making API operation for +// AWS Certificate Manager Private Certificate Authority. +// +// Restores a certificate authority (CA) that is in the DELETED state. You can +// restore a CA during the period that you defined in the PermanentDeletionTimeInDays +// parameter of the DeleteCertificateAuthority operation. Currently, you can +// specify 7 to 30 days. If you did not specify a PermanentDeletionTimeInDays +// value, by default you can restore the CA at any time in a 30 day period. +// You can check the time remaining in the restoration period of a private CA +// in the DELETED state by calling the DescribeCertificateAuthority or ListCertificateAuthorities +// operations. The status of a restored CA is set to its pre-deletion status +// when the RestoreCertificateAuthority operation returns. To change its status +// to ACTIVE, call the UpdateCertificateAuthority operation. If the private +// CA was in the PENDING_CERTIFICATE state at deletion, you must use the ImportCertificateAuthorityCertificate +// operation to import a certificate authority into the private CA before it +// can be activated. You cannot restore a CA after the restoration period has +// ended. +// +// // Example sending a request using the RestoreCertificateAuthorityRequest method. +// req := client.RestoreCertificateAuthorityRequest(params) +// resp, err := req.Send() +// if err == nil { +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/RestoreCertificateAuthority +func (c *ACMPCA) RestoreCertificateAuthorityRequest(input *RestoreCertificateAuthorityInput) RestoreCertificateAuthorityRequest { + op := &aws.Operation{ + Name: opRestoreCertificateAuthority, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &RestoreCertificateAuthorityInput{} + } + + output := &RestoreCertificateAuthorityOutput{} + req := c.newRequest(op, input, output) + req.Handlers.Unmarshal.Remove(jsonrpc.UnmarshalHandler) + req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + output.responseMetadata = aws.Response{Request: req} + + return RestoreCertificateAuthorityRequest{Request: req, Input: input, Copy: c.RestoreCertificateAuthorityRequest} +} + +const opRevokeCertificate = "RevokeCertificate" + +// RevokeCertificateRequest is a API request type for the RevokeCertificate API operation. +type RevokeCertificateRequest struct { + *aws.Request + Input *RevokeCertificateInput + Copy func(*RevokeCertificateInput) RevokeCertificateRequest +} + +// Send marshals and sends the RevokeCertificate API request. +func (r RevokeCertificateRequest) Send() (*RevokeCertificateOutput, error) { + err := r.Request.Send() + if err != nil { + return nil, err + } + + return r.Request.Data.(*RevokeCertificateOutput), nil +} + +// RevokeCertificateRequest returns a request value for making API operation for +// AWS Certificate Manager Private Certificate Authority. +// +// Revokes a certificate that you issued by calling the IssueCertificate operation. +// If you enable a certificate revocation list (CRL) when you create or update +// your private CA, information about the revoked certificates will be included +// in the CRL. ACM PCA writes the CRL to an S3 bucket that you specify. For +// more information about revocation, see the CrlConfiguration structure. ACM +// PCA also writes revocation information to the audit report. For more information, +// see CreateCertificateAuthorityAuditReport. +// +// // Example sending a request using the RevokeCertificateRequest method. +// req := client.RevokeCertificateRequest(params) +// resp, err := req.Send() +// if err == nil { +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/RevokeCertificate +func (c *ACMPCA) RevokeCertificateRequest(input *RevokeCertificateInput) RevokeCertificateRequest { + op := &aws.Operation{ + Name: opRevokeCertificate, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &RevokeCertificateInput{} + } + + output := &RevokeCertificateOutput{} + req := c.newRequest(op, input, output) + req.Handlers.Unmarshal.Remove(jsonrpc.UnmarshalHandler) + req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + output.responseMetadata = aws.Response{Request: req} + + return RevokeCertificateRequest{Request: req, Input: input, Copy: c.RevokeCertificateRequest} +} + +const opTagCertificateAuthority = "TagCertificateAuthority" + +// TagCertificateAuthorityRequest is a API request type for the TagCertificateAuthority API operation. +type TagCertificateAuthorityRequest struct { + *aws.Request + Input *TagCertificateAuthorityInput + Copy func(*TagCertificateAuthorityInput) TagCertificateAuthorityRequest +} + +// Send marshals and sends the TagCertificateAuthority API request. +func (r TagCertificateAuthorityRequest) Send() (*TagCertificateAuthorityOutput, error) { + err := r.Request.Send() + if err != nil { + return nil, err + } + + return r.Request.Data.(*TagCertificateAuthorityOutput), nil +} + +// TagCertificateAuthorityRequest returns a request value for making API operation for +// AWS Certificate Manager Private Certificate Authority. +// +// Adds one or more tags to your private CA. Tags are labels that you can use +// to identify and organize your AWS resources. Each tag consists of a key and +// an optional value. You specify the private CA on input by its Amazon Resource +// Name (ARN). You specify the tag by using a key-value pair. You can apply +// a tag to just one private CA if you want to identify a specific characteristic +// of that CA, or you can apply the same tag to multiple private CAs if you +// want to filter for a common relationship among those CAs. To remove one or +// more tags, use the UntagCertificateAuthority operation. Call the ListTags +// operation to see what tags are associated with your CA. +// +// // Example sending a request using the TagCertificateAuthorityRequest method. +// req := client.TagCertificateAuthorityRequest(params) +// resp, err := req.Send() +// if err == nil { +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/TagCertificateAuthority +func (c *ACMPCA) TagCertificateAuthorityRequest(input *TagCertificateAuthorityInput) TagCertificateAuthorityRequest { + op := &aws.Operation{ + Name: opTagCertificateAuthority, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &TagCertificateAuthorityInput{} + } + + output := &TagCertificateAuthorityOutput{} + req := c.newRequest(op, input, output) + req.Handlers.Unmarshal.Remove(jsonrpc.UnmarshalHandler) + req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + output.responseMetadata = aws.Response{Request: req} + + return TagCertificateAuthorityRequest{Request: req, Input: input, Copy: c.TagCertificateAuthorityRequest} +} + +const opUntagCertificateAuthority = "UntagCertificateAuthority" + +// UntagCertificateAuthorityRequest is a API request type for the UntagCertificateAuthority API operation. +type UntagCertificateAuthorityRequest struct { + *aws.Request + Input *UntagCertificateAuthorityInput + Copy func(*UntagCertificateAuthorityInput) UntagCertificateAuthorityRequest +} + +// Send marshals and sends the UntagCertificateAuthority API request. +func (r UntagCertificateAuthorityRequest) Send() (*UntagCertificateAuthorityOutput, error) { + err := r.Request.Send() + if err != nil { + return nil, err + } + + return r.Request.Data.(*UntagCertificateAuthorityOutput), nil +} + +// UntagCertificateAuthorityRequest returns a request value for making API operation for +// AWS Certificate Manager Private Certificate Authority. +// +// Remove one or more tags from your private CA. A tag consists of a key-value +// pair. If you do not specify the value portion of the tag when calling this +// operation, the tag will be removed regardless of value. If you specify a +// value, the tag is removed only if it is associated with the specified value. +// To add tags to a private CA, use the TagCertificateAuthority. Call the ListTags +// operation to see what tags are associated with your CA. +// +// // Example sending a request using the UntagCertificateAuthorityRequest method. +// req := client.UntagCertificateAuthorityRequest(params) +// resp, err := req.Send() +// if err == nil { +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/UntagCertificateAuthority +func (c *ACMPCA) UntagCertificateAuthorityRequest(input *UntagCertificateAuthorityInput) UntagCertificateAuthorityRequest { + op := &aws.Operation{ + Name: opUntagCertificateAuthority, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &UntagCertificateAuthorityInput{} + } + + output := &UntagCertificateAuthorityOutput{} + req := c.newRequest(op, input, output) + req.Handlers.Unmarshal.Remove(jsonrpc.UnmarshalHandler) + req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + output.responseMetadata = aws.Response{Request: req} + + return UntagCertificateAuthorityRequest{Request: req, Input: input, Copy: c.UntagCertificateAuthorityRequest} +} + +const opUpdateCertificateAuthority = "UpdateCertificateAuthority" + +// UpdateCertificateAuthorityRequest is a API request type for the UpdateCertificateAuthority API operation. +type UpdateCertificateAuthorityRequest struct { + *aws.Request + Input *UpdateCertificateAuthorityInput + Copy func(*UpdateCertificateAuthorityInput) UpdateCertificateAuthorityRequest +} + +// Send marshals and sends the UpdateCertificateAuthority API request. +func (r UpdateCertificateAuthorityRequest) Send() (*UpdateCertificateAuthorityOutput, error) { + err := r.Request.Send() + if err != nil { + return nil, err + } + + return r.Request.Data.(*UpdateCertificateAuthorityOutput), nil +} + +// UpdateCertificateAuthorityRequest returns a request value for making API operation for +// AWS Certificate Manager Private Certificate Authority. +// +// Updates the status or configuration of a private certificate authority (CA). +// Your private CA must be in the ACTIVE or DISABLED state before you can update +// it. You can disable a private CA that is in the ACTIVE state or make a CA +// that is in the DISABLED state active again. +// +// // Example sending a request using the UpdateCertificateAuthorityRequest method. +// req := client.UpdateCertificateAuthorityRequest(params) +// resp, err := req.Send() +// if err == nil { +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/UpdateCertificateAuthority +func (c *ACMPCA) UpdateCertificateAuthorityRequest(input *UpdateCertificateAuthorityInput) UpdateCertificateAuthorityRequest { + op := &aws.Operation{ + Name: opUpdateCertificateAuthority, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &UpdateCertificateAuthorityInput{} + } + + output := &UpdateCertificateAuthorityOutput{} + req := c.newRequest(op, input, output) + req.Handlers.Unmarshal.Remove(jsonrpc.UnmarshalHandler) + req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + output.responseMetadata = aws.Response{Request: req} + + return UpdateCertificateAuthorityRequest{Request: req, Input: input, Copy: c.UpdateCertificateAuthorityRequest} +} + +// Contains information about the certificate subject. The certificate can be +// one issued by your private certificate authority (CA) or it can be your private +// CA certificate. The Subject field in the certificate identifies the entity +// that owns or controls the public key in the certificate. The entity can be +// a user, computer, device, or service. The Subject must contain an X.500 distinguished +// name (DN). A DN is a sequence of relative distinguished names (RDNs). The +// RDNs are separated by commas in the certificate. The DN must be unique for +// each entity, but your private CA can issue more than one certificate with +// the same DN to the same entity. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/ASN1Subject +type ASN1Subject struct { + _ struct{} `type:"structure"` + + // Fully qualified domain name (FQDN) associated with the certificate subject. + CommonName *string `type:"string"` + + // Two-digit code that specifies the country in which the certificate subject + // located. + Country *string `type:"string"` + + // Disambiguating information for the certificate subject. + DistinguishedNameQualifier *string `type:"string"` + + // Typically a qualifier appended to the name of an individual. Examples include + // Jr. for junior, Sr. for senior, and III for third. + GenerationQualifier *string `type:"string"` + + // First name. + GivenName *string `type:"string"` + + // Concatenation that typically contains the first letter of the GivenName, + // the first letter of the middle name if one exists, and the first letter of + // the SurName. + Initials *string `type:"string"` + + // The locality (such as a city or town) in which the certificate subject is + // located. + Locality *string `type:"string"` + + // Legal name of the organization with which the certificate subject is affiliated. + Organization *string `type:"string"` + + // A subdivision or unit of the organization (such as sales or finance) with + // which the certificate subject is affiliated. + OrganizationalUnit *string `type:"string"` + + // Typically a shortened version of a longer GivenName. For example, Jonathan + // is often shortened to John. Elizabeth is often shortened to Beth, Liz, or + // Eliza. + Pseudonym *string `type:"string"` + + // The certificate serial number. + SerialNumber *string `type:"string"` + + // State in which the subject of the certificate is located. + State *string `type:"string"` + + // Family name. In the US and the UK, for example, the surname of an individual + // is ordered last. In Asian cultures the surname is typically ordered first. + Surname *string `type:"string"` + + // A title such as Mr. or Ms., which is pre-pended to the name to refer formally + // to the certificate subject. + Title *string `type:"string"` +} + +// String returns the string representation +func (s ASN1Subject) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ASN1Subject) GoString() string { + return s.String() +} + +// Contains information about your private certificate authority (CA). Your +// private CA can issue and revoke X.509 digital certificates. Digital certificates +// verify that the entity named in the certificate Subject field owns or controls +// the public key contained in the Subject Public Key Info field. Call the CreateCertificateAuthority +// operation to create your private CA. You must then call the GetCertificateAuthorityCertificate +// operation to retrieve a private CA certificate signing request (CSR). Take +// the CSR to your on-premises CA and sign it with the root CA certificate or +// a subordinate certificate. Call the ImportCertificateAuthorityCertificate +// operation to import the signed certificate into AWS Certificate Manager (ACM). +// Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/CertificateAuthority +type CertificateAuthority struct { + _ struct{} `type:"structure"` + + // Amazon Resource Name (ARN) for your private certificate authority (CA). The + // format is 12345678-1234-1234-1234-123456789012. + Arn *string `min:"5" type:"string"` + + // Your private CA configuration. + CertificateAuthorityConfiguration *CertificateAuthorityConfiguration `type:"structure"` + + // Date and time at which your private CA was created. + CreatedAt *time.Time `type:"timestamp" timestampFormat:"unix"` + + // Reason the request to create your private CA failed. + FailureReason FailureReason `type:"string" enum:"true"` + + // Date and time at which your private CA was last updated. + LastStateChangeAt *time.Time `type:"timestamp" timestampFormat:"unix"` + + // Date and time after which your private CA certificate is not valid. + NotAfter *time.Time `type:"timestamp" timestampFormat:"unix"` + + // Date and time before which your private CA certificate is not valid. + NotBefore *time.Time `type:"timestamp" timestampFormat:"unix"` + + // The period during which a deleted CA can be restored. For more information, + // see the PermanentDeletionTimeInDays parameter of the DeleteCertificateAuthorityRequest + // operation. + RestorableUntil *time.Time `type:"timestamp" timestampFormat:"unix"` + + // Information about the certificate revocation list (CRL) created and maintained + // by your private CA. + RevocationConfiguration *RevocationConfiguration `type:"structure"` + + // Serial number of your private CA. + Serial *string `type:"string"` + + // Status of your private CA. + Status CertificateAuthorityStatus `type:"string" enum:"true"` + + // Type of your private CA. + Type CertificateAuthorityType `type:"string" enum:"true"` +} + +// String returns the string representation +func (s CertificateAuthority) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CertificateAuthority) GoString() string { + return s.String() +} + +// Contains configuration information for your private certificate authority +// (CA). This includes information about the class of public key algorithm and +// the key pair that your private CA creates when it issues a certificate, the +// signature algorithm it uses used when issuing certificates, and its X.500 +// distinguished name. You must specify this information when you call the CreateCertificateAuthority +// operation. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/CertificateAuthorityConfiguration +type CertificateAuthorityConfiguration struct { + _ struct{} `type:"structure"` + + // Type of the public key algorithm and size, in bits, of the key pair that + // your key pair creates when it issues a certificate. + // + // KeyAlgorithm is a required field + KeyAlgorithm KeyAlgorithm `type:"string" required:"true" enum:"true"` + + // Name of the algorithm your private CA uses to sign certificate requests. + // + // SigningAlgorithm is a required field + SigningAlgorithm SigningAlgorithm `type:"string" required:"true" enum:"true"` + + // Structure that contains X.500 distinguished name information for your private + // CA. + // + // Subject is a required field + Subject *ASN1Subject `type:"structure" required:"true"` +} + +// String returns the string representation +func (s CertificateAuthorityConfiguration) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CertificateAuthorityConfiguration) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CertificateAuthorityConfiguration) Validate() error { + invalidParams := aws.ErrInvalidParams{Context: "CertificateAuthorityConfiguration"} + if len(s.KeyAlgorithm) == 0 { + invalidParams.Add(aws.NewErrParamRequired("KeyAlgorithm")) + } + if len(s.SigningAlgorithm) == 0 { + invalidParams.Add(aws.NewErrParamRequired("SigningAlgorithm")) + } + + if s.Subject == nil { + invalidParams.Add(aws.NewErrParamRequired("Subject")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/CreateCertificateAuthorityAuditReportRequest +type CreateCertificateAuthorityAuditReportInput struct { + _ struct{} `type:"structure"` + + // Format in which to create the report. This can be either JSON or CSV. + // + // AuditReportResponseFormat is a required field + AuditReportResponseFormat AuditReportResponseFormat `type:"string" required:"true" enum:"true"` + + // Amazon Resource Name (ARN) of the CA to be audited. This is of the form: + // + // arn:aws:acm-pca:region:account:certificate-authority/12345678-1234-1234-1234-123456789012. + // + // CertificateAuthorityArn is a required field + CertificateAuthorityArn *string `min:"5" type:"string" required:"true"` + + // Name of the S3 bucket that will contain the audit report. + // + // S3BucketName is a required field + S3BucketName *string `type:"string" required:"true"` +} + +// String returns the string representation +func (s CreateCertificateAuthorityAuditReportInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateCertificateAuthorityAuditReportInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CreateCertificateAuthorityAuditReportInput) Validate() error { + invalidParams := aws.ErrInvalidParams{Context: "CreateCertificateAuthorityAuditReportInput"} + if len(s.AuditReportResponseFormat) == 0 { + invalidParams.Add(aws.NewErrParamRequired("AuditReportResponseFormat")) + } + + if s.CertificateAuthorityArn == nil { + invalidParams.Add(aws.NewErrParamRequired("CertificateAuthorityArn")) + } + if s.CertificateAuthorityArn != nil && len(*s.CertificateAuthorityArn) < 5 { + invalidParams.Add(aws.NewErrParamMinLen("CertificateAuthorityArn", 5)) + } + + if s.S3BucketName == nil { + invalidParams.Add(aws.NewErrParamRequired("S3BucketName")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/CreateCertificateAuthorityAuditReportResponse +type CreateCertificateAuthorityAuditReportOutput struct { + _ struct{} `type:"structure"` + + responseMetadata aws.Response + + // An alphanumeric string that contains a report identifier. + AuditReportId *string `min:"36" type:"string"` + + // The key that uniquely identifies the report file in your S3 bucket. + S3Key *string `type:"string"` +} + +// String returns the string representation +func (s CreateCertificateAuthorityAuditReportOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateCertificateAuthorityAuditReportOutput) GoString() string { + return s.String() +} + +// SDKResponseMetdata return sthe response metadata for the API. +func (s CreateCertificateAuthorityAuditReportOutput) SDKResponseMetadata() aws.Response { + return s.responseMetadata +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/CreateCertificateAuthorityRequest +type CreateCertificateAuthorityInput struct { + _ struct{} `type:"structure"` + + // Name and bit size of the private key algorithm, the name of the signing algorithm, + // and X.500 certificate subject information. + // + // CertificateAuthorityConfiguration is a required field + CertificateAuthorityConfiguration *CertificateAuthorityConfiguration `type:"structure" required:"true"` + + // The type of the certificate authority. Currently, this must be SUBORDINATE. + // + // CertificateAuthorityType is a required field + CertificateAuthorityType CertificateAuthorityType `type:"string" required:"true" enum:"true"` + + // Alphanumeric string that can be used to distinguish between calls to CreateCertificateAuthority. + // Idempotency tokens time out after five minutes. Therefore, if you call CreateCertificateAuthority + // multiple times with the same idempotency token within a five minute period, + // ACM PCA recognizes that you are requesting only one certificate. As a result, + // ACM PCA issues only one. If you change the idempotency token for each call, + // however, ACM PCA recognizes that you are requesting multiple certificates. + IdempotencyToken *string `min:"1" type:"string"` + + // Contains a Boolean value that you can use to enable a certification revocation + // list (CRL) for the CA, the name of the S3 bucket to which ACM PCA will write + // the CRL, and an optional CNAME alias that you can use to hide the name of + // your bucket in the CRL Distribution Points extension of your CA certificate. + // For more information, see the CrlConfiguration structure. + RevocationConfiguration *RevocationConfiguration `type:"structure"` +} + +// String returns the string representation +func (s CreateCertificateAuthorityInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateCertificateAuthorityInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CreateCertificateAuthorityInput) Validate() error { + invalidParams := aws.ErrInvalidParams{Context: "CreateCertificateAuthorityInput"} + + if s.CertificateAuthorityConfiguration == nil { + invalidParams.Add(aws.NewErrParamRequired("CertificateAuthorityConfiguration")) + } + if len(s.CertificateAuthorityType) == 0 { + invalidParams.Add(aws.NewErrParamRequired("CertificateAuthorityType")) + } + if s.IdempotencyToken != nil && len(*s.IdempotencyToken) < 1 { + invalidParams.Add(aws.NewErrParamMinLen("IdempotencyToken", 1)) + } + if s.CertificateAuthorityConfiguration != nil { + if err := s.CertificateAuthorityConfiguration.Validate(); err != nil { + invalidParams.AddNested("CertificateAuthorityConfiguration", err.(aws.ErrInvalidParams)) + } + } + if s.RevocationConfiguration != nil { + if err := s.RevocationConfiguration.Validate(); err != nil { + invalidParams.AddNested("RevocationConfiguration", err.(aws.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/CreateCertificateAuthorityResponse +type CreateCertificateAuthorityOutput struct { + _ struct{} `type:"structure"` + + responseMetadata aws.Response + + // If successful, the Amazon Resource Name (ARN) of the certificate authority + // (CA). This is of the form: + // + // arn:aws:acm-pca:region:account:certificate-authority/12345678-1234-1234-1234-123456789012. + CertificateAuthorityArn *string `min:"5" type:"string"` +} + +// String returns the string representation +func (s CreateCertificateAuthorityOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateCertificateAuthorityOutput) GoString() string { + return s.String() +} + +// SDKResponseMetdata return sthe response metadata for the API. +func (s CreateCertificateAuthorityOutput) SDKResponseMetadata() aws.Response { + return s.responseMetadata +} + +// Contains configuration information for a certificate revocation list (CRL). +// Your private certificate authority (CA) creates base CRLs. Delta CRLs are +// not supported. You can enable CRLs for your new or an existing private CA +// by setting the Enabled parameter to true. Your private CA writes CRLs to +// an S3 bucket that you specify in the S3BucketName parameter. You can hide +// the name of your bucket by specifying a value for the CustomCname parameter. +// Your private CA copies the CNAME or the S3 bucket name to the CRL Distribution +// Points extension of each certificate it issues. Your S3 bucket policy must +// give write permission to ACM PCA. +// +// Your private CA uses the value in the ExpirationInDays parameter to calculate +// the nextUpdate field in the CRL. The CRL is refreshed at 1/2 the age of next +// update or when a certificate is revoked. When a certificate is revoked, it +// is recorded in the next CRL that is generated and in the next audit report. +// Only time valid certificates are listed in the CRL. Expired certificates +// are not included. +// +// CRLs contain the following fields: +// +// * Version: The current version number defined in RFC 5280 is V2. The integer +// value is 0x1. +// +// * Signature Algorithm: The name of the algorithm used to sign the CRL. +// +// * Issuer: The X.500 distinguished name of your private CA that issued +// the CRL. +// +// * Last Update: The issue date and time of this CRL. +// +// * Next Update: The day and time by which the next CRL will be issued. +// +// * Revoked Certificates: List of revoked certificates. Each list item contains +// the following information. +// +// Serial Number: The serial number, in hexadecimal format, of the revoked certificate. +// +// Revocation Date: Date and time the certificate was revoked. +// +// CRL Entry Extensions: Optional extensions for the CRL entry. +// +// X509v3 CRL Reason Code: Reason the certificate was revoked. +// +// * CRL Extensions: Optional extensions for the CRL. +// +// X509v3 Authority Key Identifier: Identifies the public key associated with +// the private key used to sign the certificate. +// +// X509v3 CRL Number:: Decimal sequence number for the CRL. +// +// * Signature Algorithm: Algorithm used by your private CA to sign the CRL. +// +// * Signature Value: Signature computed over the CRL. +// +// Certificate revocation lists created by ACM PCA are DER-encoded. You can +// use the following OpenSSL command to list a CRL. +// +// openssl crl -inform DER -text -in crl_path -noout +// Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/CrlConfiguration +type CrlConfiguration struct { + _ struct{} `type:"structure"` + + // Name inserted into the certificate CRL Distribution Points extension that + // enables the use of an alias for the CRL distribution point. Use this value + // if you don't want the name of your S3 bucket to be public. + CustomCname *string `type:"string"` + + // Boolean value that specifies whether certificate revocation lists (CRLs) + // are enabled. You can use this value to enable certificate revocation for + // a new CA when you call the CreateCertificateAuthority operation or for an + // existing CA when you call the UpdateCertificateAuthority operation. + // + // Enabled is a required field + Enabled *bool `type:"boolean" required:"true"` + + // Number of days until a certificate expires. + ExpirationInDays *int64 `min:"1" type:"integer"` + + // Name of the S3 bucket that contains the CRL. If you do not provide a value + // for the CustomCname argument, the name of your S3 bucket is placed into the + // CRL Distribution Points extension of the issued certificate. You can change + // the name of your bucket by calling the UpdateCertificateAuthority operation. + // You must specify a bucket policy that allows ACM PCA to write the CRL to + // your bucket. + S3BucketName *string `min:"3" type:"string"` +} + +// String returns the string representation +func (s CrlConfiguration) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CrlConfiguration) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CrlConfiguration) Validate() error { + invalidParams := aws.ErrInvalidParams{Context: "CrlConfiguration"} + + if s.Enabled == nil { + invalidParams.Add(aws.NewErrParamRequired("Enabled")) + } + if s.ExpirationInDays != nil && *s.ExpirationInDays < 1 { + invalidParams.Add(aws.NewErrParamMinValue("ExpirationInDays", 1)) + } + if s.S3BucketName != nil && len(*s.S3BucketName) < 3 { + invalidParams.Add(aws.NewErrParamMinLen("S3BucketName", 3)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/DeleteCertificateAuthorityRequest +type DeleteCertificateAuthorityInput struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) that was returned when you called CreateCertificateAuthority. + // This must have the following form: + // + // arn:aws:acm-pca:region:account:certificate-authority/12345678-1234-1234-1234-123456789012. + // + // CertificateAuthorityArn is a required field + CertificateAuthorityArn *string `min:"5" type:"string" required:"true"` + + // The number of days to make a CA restorable after it has been deleted. This + // can be anywhere from 7 to 30 days, with 30 being the default. + PermanentDeletionTimeInDays *int64 `min:"7" type:"integer"` +} + +// String returns the string representation +func (s DeleteCertificateAuthorityInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteCertificateAuthorityInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteCertificateAuthorityInput) Validate() error { + invalidParams := aws.ErrInvalidParams{Context: "DeleteCertificateAuthorityInput"} + + if s.CertificateAuthorityArn == nil { + invalidParams.Add(aws.NewErrParamRequired("CertificateAuthorityArn")) + } + if s.CertificateAuthorityArn != nil && len(*s.CertificateAuthorityArn) < 5 { + invalidParams.Add(aws.NewErrParamMinLen("CertificateAuthorityArn", 5)) + } + if s.PermanentDeletionTimeInDays != nil && *s.PermanentDeletionTimeInDays < 7 { + invalidParams.Add(aws.NewErrParamMinValue("PermanentDeletionTimeInDays", 7)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/DeleteCertificateAuthorityOutput +type DeleteCertificateAuthorityOutput struct { + _ struct{} `type:"structure"` + + responseMetadata aws.Response +} + +// String returns the string representation +func (s DeleteCertificateAuthorityOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteCertificateAuthorityOutput) GoString() string { + return s.String() +} + +// SDKResponseMetdata return sthe response metadata for the API. +func (s DeleteCertificateAuthorityOutput) SDKResponseMetadata() aws.Response { + return s.responseMetadata +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/DescribeCertificateAuthorityAuditReportRequest +type DescribeCertificateAuthorityAuditReportInput struct { + _ struct{} `type:"structure"` + + // The report ID returned by calling the CreateCertificateAuthorityAuditReport + // operation. + // + // AuditReportId is a required field + AuditReportId *string `min:"36" type:"string" required:"true"` + + // The Amazon Resource Name (ARN) of the private CA. This must be of the form: + // + // arn:aws:acm-pca:region:account:certificate-authority/12345678-1234-1234-1234-123456789012. + // + // CertificateAuthorityArn is a required field + CertificateAuthorityArn *string `min:"5" type:"string" required:"true"` +} + +// String returns the string representation +func (s DescribeCertificateAuthorityAuditReportInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeCertificateAuthorityAuditReportInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DescribeCertificateAuthorityAuditReportInput) Validate() error { + invalidParams := aws.ErrInvalidParams{Context: "DescribeCertificateAuthorityAuditReportInput"} + + if s.AuditReportId == nil { + invalidParams.Add(aws.NewErrParamRequired("AuditReportId")) + } + if s.AuditReportId != nil && len(*s.AuditReportId) < 36 { + invalidParams.Add(aws.NewErrParamMinLen("AuditReportId", 36)) + } + + if s.CertificateAuthorityArn == nil { + invalidParams.Add(aws.NewErrParamRequired("CertificateAuthorityArn")) + } + if s.CertificateAuthorityArn != nil && len(*s.CertificateAuthorityArn) < 5 { + invalidParams.Add(aws.NewErrParamMinLen("CertificateAuthorityArn", 5)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/DescribeCertificateAuthorityAuditReportResponse +type DescribeCertificateAuthorityAuditReportOutput struct { + _ struct{} `type:"structure"` + + responseMetadata aws.Response + + // Specifies whether report creation is in progress, has succeeded, or has failed. + AuditReportStatus AuditReportStatus `type:"string" enum:"true"` + + // The date and time at which the report was created. + CreatedAt *time.Time `type:"timestamp" timestampFormat:"unix"` + + // Name of the S3 bucket that contains the report. + S3BucketName *string `type:"string"` + + // S3 key that uniquely identifies the report file in your S3 bucket. + S3Key *string `type:"string"` +} + +// String returns the string representation +func (s DescribeCertificateAuthorityAuditReportOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeCertificateAuthorityAuditReportOutput) GoString() string { + return s.String() +} + +// SDKResponseMetdata return sthe response metadata for the API. +func (s DescribeCertificateAuthorityAuditReportOutput) SDKResponseMetadata() aws.Response { + return s.responseMetadata +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/DescribeCertificateAuthorityRequest +type DescribeCertificateAuthorityInput struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) that was returned when you called CreateCertificateAuthority. + // This must be of the form: + // + // arn:aws:acm-pca:region:account:certificate-authority/12345678-1234-1234-1234-123456789012. + // + // CertificateAuthorityArn is a required field + CertificateAuthorityArn *string `min:"5" type:"string" required:"true"` +} + +// String returns the string representation +func (s DescribeCertificateAuthorityInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeCertificateAuthorityInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DescribeCertificateAuthorityInput) Validate() error { + invalidParams := aws.ErrInvalidParams{Context: "DescribeCertificateAuthorityInput"} + + if s.CertificateAuthorityArn == nil { + invalidParams.Add(aws.NewErrParamRequired("CertificateAuthorityArn")) + } + if s.CertificateAuthorityArn != nil && len(*s.CertificateAuthorityArn) < 5 { + invalidParams.Add(aws.NewErrParamMinLen("CertificateAuthorityArn", 5)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/DescribeCertificateAuthorityResponse +type DescribeCertificateAuthorityOutput struct { + _ struct{} `type:"structure"` + + responseMetadata aws.Response + + // A CertificateAuthority structure that contains information about your private + // CA. + CertificateAuthority *CertificateAuthority `type:"structure"` +} + +// String returns the string representation +func (s DescribeCertificateAuthorityOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeCertificateAuthorityOutput) GoString() string { + return s.String() +} + +// SDKResponseMetdata return sthe response metadata for the API. +func (s DescribeCertificateAuthorityOutput) SDKResponseMetadata() aws.Response { + return s.responseMetadata +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/GetCertificateAuthorityCertificateRequest +type GetCertificateAuthorityCertificateInput struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of your private CA. This is of the form: + // + // arn:aws:acm-pca:region:account:certificate-authority/12345678-1234-1234-1234-123456789012. + // + // CertificateAuthorityArn is a required field + CertificateAuthorityArn *string `min:"5" type:"string" required:"true"` +} + +// String returns the string representation +func (s GetCertificateAuthorityCertificateInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetCertificateAuthorityCertificateInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetCertificateAuthorityCertificateInput) Validate() error { + invalidParams := aws.ErrInvalidParams{Context: "GetCertificateAuthorityCertificateInput"} + + if s.CertificateAuthorityArn == nil { + invalidParams.Add(aws.NewErrParamRequired("CertificateAuthorityArn")) + } + if s.CertificateAuthorityArn != nil && len(*s.CertificateAuthorityArn) < 5 { + invalidParams.Add(aws.NewErrParamMinLen("CertificateAuthorityArn", 5)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/GetCertificateAuthorityCertificateResponse +type GetCertificateAuthorityCertificateOutput struct { + _ struct{} `type:"structure"` + + responseMetadata aws.Response + + // Base64-encoded certificate authority (CA) certificate. + Certificate *string `type:"string"` + + // Base64-encoded certificate chain that includes any intermediate certificates + // and chains up to root on-premises certificate that you used to sign your + // private CA certificate. The chain does not include your private CA certificate. + CertificateChain *string `type:"string"` +} + +// String returns the string representation +func (s GetCertificateAuthorityCertificateOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetCertificateAuthorityCertificateOutput) GoString() string { + return s.String() +} + +// SDKResponseMetdata return sthe response metadata for the API. +func (s GetCertificateAuthorityCertificateOutput) SDKResponseMetadata() aws.Response { + return s.responseMetadata +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/GetCertificateAuthorityCsrRequest +type GetCertificateAuthorityCsrInput struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) that was returned when you called the CreateCertificateAuthority + // operation. This must be of the form: + // + // arn:aws:acm-pca:region:account:certificate-authority/12345678-1234-1234-1234-123456789012 + // + // CertificateAuthorityArn is a required field + CertificateAuthorityArn *string `min:"5" type:"string" required:"true"` +} + +// String returns the string representation +func (s GetCertificateAuthorityCsrInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetCertificateAuthorityCsrInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetCertificateAuthorityCsrInput) Validate() error { + invalidParams := aws.ErrInvalidParams{Context: "GetCertificateAuthorityCsrInput"} + + if s.CertificateAuthorityArn == nil { + invalidParams.Add(aws.NewErrParamRequired("CertificateAuthorityArn")) + } + if s.CertificateAuthorityArn != nil && len(*s.CertificateAuthorityArn) < 5 { + invalidParams.Add(aws.NewErrParamMinLen("CertificateAuthorityArn", 5)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/GetCertificateAuthorityCsrResponse +type GetCertificateAuthorityCsrOutput struct { + _ struct{} `type:"structure"` + + responseMetadata aws.Response + + // The base64 PEM-encoded certificate signing request (CSR) for your private + // CA certificate. + Csr *string `type:"string"` +} + +// String returns the string representation +func (s GetCertificateAuthorityCsrOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetCertificateAuthorityCsrOutput) GoString() string { + return s.String() +} + +// SDKResponseMetdata return sthe response metadata for the API. +func (s GetCertificateAuthorityCsrOutput) SDKResponseMetadata() aws.Response { + return s.responseMetadata +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/GetCertificateRequest +type GetCertificateInput struct { + _ struct{} `type:"structure"` + + // The ARN of the issued certificate. The ARN contains the certificate serial + // number and must be in the following form: + // + // arn:aws:acm-pca:region:account:certificate-authority/12345678-1234-1234-1234-123456789012/certificate/286535153982981100925020015808220737245 + // + // CertificateArn is a required field + CertificateArn *string `min:"5" type:"string" required:"true"` + + // The Amazon Resource Name (ARN) that was returned when you called CreateCertificateAuthority. + // This must be of the form: + // + // arn:aws:acm-pca:region:account:certificate-authority/12345678-1234-1234-1234-123456789012. + // + // CertificateAuthorityArn is a required field + CertificateAuthorityArn *string `min:"5" type:"string" required:"true"` +} + +// String returns the string representation +func (s GetCertificateInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetCertificateInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetCertificateInput) Validate() error { + invalidParams := aws.ErrInvalidParams{Context: "GetCertificateInput"} + + if s.CertificateArn == nil { + invalidParams.Add(aws.NewErrParamRequired("CertificateArn")) + } + if s.CertificateArn != nil && len(*s.CertificateArn) < 5 { + invalidParams.Add(aws.NewErrParamMinLen("CertificateArn", 5)) + } + + if s.CertificateAuthorityArn == nil { + invalidParams.Add(aws.NewErrParamRequired("CertificateAuthorityArn")) + } + if s.CertificateAuthorityArn != nil && len(*s.CertificateAuthorityArn) < 5 { + invalidParams.Add(aws.NewErrParamMinLen("CertificateAuthorityArn", 5)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/GetCertificateResponse +type GetCertificateOutput struct { + _ struct{} `type:"structure"` + + responseMetadata aws.Response + + // The base64 PEM-encoded certificate specified by the CertificateArn parameter. + Certificate *string `type:"string"` + + // The base64 PEM-encoded certificate chain that chains up to the on-premises + // root CA certificate that you used to sign your private CA certificate. + CertificateChain *string `type:"string"` +} + +// String returns the string representation +func (s GetCertificateOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetCertificateOutput) GoString() string { + return s.String() +} + +// SDKResponseMetdata return sthe response metadata for the API. +func (s GetCertificateOutput) SDKResponseMetadata() aws.Response { + return s.responseMetadata +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/ImportCertificateAuthorityCertificateRequest +type ImportCertificateAuthorityCertificateInput struct { + _ struct{} `type:"structure"` + + // The PEM-encoded certificate for your private CA. This must be signed by using + // your on-premises CA. + // + // Certificate is automatically base64 encoded/decoded by the SDK. + // + // Certificate is a required field + Certificate []byte `min:"1" type:"blob" required:"true"` + + // The Amazon Resource Name (ARN) that was returned when you called CreateCertificateAuthority. + // This must be of the form: + // + // arn:aws:acm-pca:region:account:certificate-authority/12345678-1234-1234-1234-123456789012 + // + // CertificateAuthorityArn is a required field + CertificateAuthorityArn *string `min:"5" type:"string" required:"true"` + + // A PEM-encoded file that contains all of your certificates, other than the + // certificate you're importing, chaining up to your root CA. Your on-premises + // root certificate is the last in the chain, and each certificate in the chain + // signs the one preceding. + // + // CertificateChain is automatically base64 encoded/decoded by the SDK. + // + // CertificateChain is a required field + CertificateChain []byte `type:"blob" required:"true"` +} + +// String returns the string representation +func (s ImportCertificateAuthorityCertificateInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ImportCertificateAuthorityCertificateInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ImportCertificateAuthorityCertificateInput) Validate() error { + invalidParams := aws.ErrInvalidParams{Context: "ImportCertificateAuthorityCertificateInput"} + + if s.Certificate == nil { + invalidParams.Add(aws.NewErrParamRequired("Certificate")) + } + if s.Certificate != nil && len(s.Certificate) < 1 { + invalidParams.Add(aws.NewErrParamMinLen("Certificate", 1)) + } + + if s.CertificateAuthorityArn == nil { + invalidParams.Add(aws.NewErrParamRequired("CertificateAuthorityArn")) + } + if s.CertificateAuthorityArn != nil && len(*s.CertificateAuthorityArn) < 5 { + invalidParams.Add(aws.NewErrParamMinLen("CertificateAuthorityArn", 5)) + } + + if s.CertificateChain == nil { + invalidParams.Add(aws.NewErrParamRequired("CertificateChain")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/ImportCertificateAuthorityCertificateOutput +type ImportCertificateAuthorityCertificateOutput struct { + _ struct{} `type:"structure"` + + responseMetadata aws.Response +} + +// String returns the string representation +func (s ImportCertificateAuthorityCertificateOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ImportCertificateAuthorityCertificateOutput) GoString() string { + return s.String() +} + +// SDKResponseMetdata return sthe response metadata for the API. +func (s ImportCertificateAuthorityCertificateOutput) SDKResponseMetadata() aws.Response { + return s.responseMetadata +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/IssueCertificateRequest +type IssueCertificateInput struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) that was returned when you called CreateCertificateAuthority. + // This must be of the form: + // + // arn:aws:acm-pca:region:account:certificate-authority/12345678-1234-1234-1234-123456789012 + // + // CertificateAuthorityArn is a required field + CertificateAuthorityArn *string `min:"5" type:"string" required:"true"` + + // The certificate signing request (CSR) for the certificate you want to issue. + // You can use the following OpenSSL command to create the CSR and a 2048 bit + // RSA private key. + // + // openssl req -new -newkey rsa:2048 -days 365 -keyout private/test_cert_priv_key.pem + // -out csr/test_cert_.csr + // + // If you have a configuration file, you can use the following OpenSSL command. + // The usr_cert block in the configuration file contains your X509 version 3 + // extensions. + // + // openssl req -new -config openssl_rsa.cnf -extensions usr_cert -newkey rsa:2048 + // -days -365 -keyout private/test_cert_priv_key.pem -out csr/test_cert_.csr + // + // Csr is automatically base64 encoded/decoded by the SDK. + // + // Csr is a required field + Csr []byte `min:"1" type:"blob" required:"true"` + + // Custom string that can be used to distinguish between calls to the IssueCertificate + // operation. Idempotency tokens time out after one hour. Therefore, if you + // call IssueCertificate multiple times with the same idempotency token within + // 5 minutes, ACM PCA recognizes that you are requesting only one certificate + // and will issue only one. If you change the idempotency token for each call, + // PCA recognizes that you are requesting multiple certificates. + IdempotencyToken *string `min:"1" type:"string"` + + // The name of the algorithm that will be used to sign the certificate to be + // issued. + // + // SigningAlgorithm is a required field + SigningAlgorithm SigningAlgorithm `type:"string" required:"true" enum:"true"` + + // The type of the validity period. + // + // Validity is a required field + Validity *Validity `type:"structure" required:"true"` +} + +// String returns the string representation +func (s IssueCertificateInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s IssueCertificateInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *IssueCertificateInput) Validate() error { + invalidParams := aws.ErrInvalidParams{Context: "IssueCertificateInput"} + + if s.CertificateAuthorityArn == nil { + invalidParams.Add(aws.NewErrParamRequired("CertificateAuthorityArn")) + } + if s.CertificateAuthorityArn != nil && len(*s.CertificateAuthorityArn) < 5 { + invalidParams.Add(aws.NewErrParamMinLen("CertificateAuthorityArn", 5)) + } + + if s.Csr == nil { + invalidParams.Add(aws.NewErrParamRequired("Csr")) + } + if s.Csr != nil && len(s.Csr) < 1 { + invalidParams.Add(aws.NewErrParamMinLen("Csr", 1)) + } + if s.IdempotencyToken != nil && len(*s.IdempotencyToken) < 1 { + invalidParams.Add(aws.NewErrParamMinLen("IdempotencyToken", 1)) + } + if len(s.SigningAlgorithm) == 0 { + invalidParams.Add(aws.NewErrParamRequired("SigningAlgorithm")) + } + + if s.Validity == nil { + invalidParams.Add(aws.NewErrParamRequired("Validity")) + } + if s.Validity != nil { + if err := s.Validity.Validate(); err != nil { + invalidParams.AddNested("Validity", err.(aws.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/IssueCertificateResponse +type IssueCertificateOutput struct { + _ struct{} `type:"structure"` + + responseMetadata aws.Response + + // The Amazon Resource Name (ARN) of the issued certificate and the certificate + // serial number. This is of the form: + // + // arn:aws:acm-pca:region:account:certificate-authority/12345678-1234-1234-1234-123456789012/certificate/286535153982981100925020015808220737245 + CertificateArn *string `min:"5" type:"string"` +} + +// String returns the string representation +func (s IssueCertificateOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s IssueCertificateOutput) GoString() string { + return s.String() +} + +// SDKResponseMetdata return sthe response metadata for the API. +func (s IssueCertificateOutput) SDKResponseMetadata() aws.Response { + return s.responseMetadata +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/ListCertificateAuthoritiesRequest +type ListCertificateAuthoritiesInput struct { + _ struct{} `type:"structure"` + + // Use this parameter when paginating results to specify the maximum number + // of items to return in the response on each page. If additional items exist + // beyond the number you specify, the NextToken element is sent in the response. + // Use this NextToken value in a subsequent request to retrieve additional items. + MaxResults *int64 `min:"1" type:"integer"` + + // Use this parameter when paginating results in a subsequent request after + // you receive a response with truncated results. Set it to the value of the + // NextToken parameter from the response you just received. + NextToken *string `min:"1" type:"string"` +} + +// String returns the string representation +func (s ListCertificateAuthoritiesInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListCertificateAuthoritiesInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListCertificateAuthoritiesInput) Validate() error { + invalidParams := aws.ErrInvalidParams{Context: "ListCertificateAuthoritiesInput"} + if s.MaxResults != nil && *s.MaxResults < 1 { + invalidParams.Add(aws.NewErrParamMinValue("MaxResults", 1)) + } + if s.NextToken != nil && len(*s.NextToken) < 1 { + invalidParams.Add(aws.NewErrParamMinLen("NextToken", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/ListCertificateAuthoritiesResponse +type ListCertificateAuthoritiesOutput struct { + _ struct{} `type:"structure"` + + responseMetadata aws.Response + + // Summary information about each certificate authority you have created. + CertificateAuthorities []CertificateAuthority `type:"list"` + + // When the list is truncated, this value is present and should be used for + // the NextToken parameter in a subsequent pagination request. + NextToken *string `min:"1" type:"string"` +} + +// String returns the string representation +func (s ListCertificateAuthoritiesOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListCertificateAuthoritiesOutput) GoString() string { + return s.String() +} + +// SDKResponseMetdata return sthe response metadata for the API. +func (s ListCertificateAuthoritiesOutput) SDKResponseMetadata() aws.Response { + return s.responseMetadata +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/ListTagsRequest +type ListTagsInput struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) that was returned when you called the CreateCertificateAuthority + // operation. This must be of the form: + // + // arn:aws:acm-pca:region:account:certificate-authority/12345678-1234-1234-1234-123456789012 + // + // CertificateAuthorityArn is a required field + CertificateAuthorityArn *string `min:"5" type:"string" required:"true"` + + // Use this parameter when paginating results to specify the maximum number + // of items to return in the response. If additional items exist beyond the + // number you specify, the NextToken element is sent in the response. Use this + // NextToken value in a subsequent request to retrieve additional items. + MaxResults *int64 `min:"1" type:"integer"` + + // Use this parameter when paginating results in a subsequent request after + // you receive a response with truncated results. Set it to the value of NextToken + // from the response you just received. + NextToken *string `min:"1" type:"string"` +} + +// String returns the string representation +func (s ListTagsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListTagsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListTagsInput) Validate() error { + invalidParams := aws.ErrInvalidParams{Context: "ListTagsInput"} + + if s.CertificateAuthorityArn == nil { + invalidParams.Add(aws.NewErrParamRequired("CertificateAuthorityArn")) + } + if s.CertificateAuthorityArn != nil && len(*s.CertificateAuthorityArn) < 5 { + invalidParams.Add(aws.NewErrParamMinLen("CertificateAuthorityArn", 5)) + } + if s.MaxResults != nil && *s.MaxResults < 1 { + invalidParams.Add(aws.NewErrParamMinValue("MaxResults", 1)) + } + if s.NextToken != nil && len(*s.NextToken) < 1 { + invalidParams.Add(aws.NewErrParamMinLen("NextToken", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/ListTagsResponse +type ListTagsOutput struct { + _ struct{} `type:"structure"` + + responseMetadata aws.Response + + // When the list is truncated, this value is present and should be used for + // the NextToken parameter in a subsequent pagination request. + NextToken *string `min:"1" type:"string"` + + // The tags associated with your private CA. + Tags []Tag `min:"1" type:"list"` +} + +// String returns the string representation +func (s ListTagsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListTagsOutput) GoString() string { + return s.String() +} + +// SDKResponseMetdata return sthe response metadata for the API. +func (s ListTagsOutput) SDKResponseMetadata() aws.Response { + return s.responseMetadata +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/RestoreCertificateAuthorityRequest +type RestoreCertificateAuthorityInput struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) that was returned when you called the CreateCertificateAuthority + // operation. This must be of the form: + // + // arn:aws:acm-pca:region:account:certificate-authority/12345678-1234-1234-1234-123456789012 + // + // CertificateAuthorityArn is a required field + CertificateAuthorityArn *string `min:"5" type:"string" required:"true"` +} + +// String returns the string representation +func (s RestoreCertificateAuthorityInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s RestoreCertificateAuthorityInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *RestoreCertificateAuthorityInput) Validate() error { + invalidParams := aws.ErrInvalidParams{Context: "RestoreCertificateAuthorityInput"} + + if s.CertificateAuthorityArn == nil { + invalidParams.Add(aws.NewErrParamRequired("CertificateAuthorityArn")) + } + if s.CertificateAuthorityArn != nil && len(*s.CertificateAuthorityArn) < 5 { + invalidParams.Add(aws.NewErrParamMinLen("CertificateAuthorityArn", 5)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/RestoreCertificateAuthorityOutput +type RestoreCertificateAuthorityOutput struct { + _ struct{} `type:"structure"` + + responseMetadata aws.Response +} + +// String returns the string representation +func (s RestoreCertificateAuthorityOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s RestoreCertificateAuthorityOutput) GoString() string { + return s.String() +} + +// SDKResponseMetdata return sthe response metadata for the API. +func (s RestoreCertificateAuthorityOutput) SDKResponseMetadata() aws.Response { + return s.responseMetadata +} + +// Certificate revocation information used by the CreateCertificateAuthority +// and UpdateCertificateAuthority operations. Your private certificate authority +// (CA) can create and maintain a certificate revocation list (CRL). A CRL contains +// information about certificates revoked by your CA. For more information, +// see RevokeCertificate. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/RevocationConfiguration +type RevocationConfiguration struct { + _ struct{} `type:"structure"` + + // Configuration of the certificate revocation list (CRL), if any, maintained + // by your private CA. + CrlConfiguration *CrlConfiguration `type:"structure"` +} + +// String returns the string representation +func (s RevocationConfiguration) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s RevocationConfiguration) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *RevocationConfiguration) Validate() error { + invalidParams := aws.ErrInvalidParams{Context: "RevocationConfiguration"} + if s.CrlConfiguration != nil { + if err := s.CrlConfiguration.Validate(); err != nil { + invalidParams.AddNested("CrlConfiguration", err.(aws.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/RevokeCertificateRequest +type RevokeCertificateInput struct { + _ struct{} `type:"structure"` + + // Amazon Resource Name (ARN) of the private CA that issued the certificate + // to be revoked. This must be of the form: + // + // arn:aws:acm-pca:region:account:certificate-authority/12345678-1234-1234-1234-123456789012 + // + // CertificateAuthorityArn is a required field + CertificateAuthorityArn *string `min:"5" type:"string" required:"true"` + + // Serial number of the certificate to be revoked. This must be in hexadecimal + // format. You can retrieve the serial number by calling GetCertificate with + // the Amazon Resource Name (ARN) of the certificate you want and the ARN of + // your private CA. The GetCertificate operation retrieves the certificate in + // the PEM format. You can use the following OpenSSL command to list the certificate + // in text format and copy the hexadecimal serial number. + // + // openssl x509 -in file_path -text -noout + // + // You can also copy the serial number from the console or use the DescribeCertificate + // (https://docs.aws.amazon.com/acm/latest/APIReference/API_DescribeCertificate.html) + // operation in the AWS Certificate Manager API Reference. + // + // CertificateSerial is a required field + CertificateSerial *string `type:"string" required:"true"` + + // Specifies why you revoked the certificate. + // + // RevocationReason is a required field + RevocationReason RevocationReason `type:"string" required:"true" enum:"true"` +} + +// String returns the string representation +func (s RevokeCertificateInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s RevokeCertificateInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *RevokeCertificateInput) Validate() error { + invalidParams := aws.ErrInvalidParams{Context: "RevokeCertificateInput"} + + if s.CertificateAuthorityArn == nil { + invalidParams.Add(aws.NewErrParamRequired("CertificateAuthorityArn")) + } + if s.CertificateAuthorityArn != nil && len(*s.CertificateAuthorityArn) < 5 { + invalidParams.Add(aws.NewErrParamMinLen("CertificateAuthorityArn", 5)) + } + + if s.CertificateSerial == nil { + invalidParams.Add(aws.NewErrParamRequired("CertificateSerial")) + } + if len(s.RevocationReason) == 0 { + invalidParams.Add(aws.NewErrParamRequired("RevocationReason")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/RevokeCertificateOutput +type RevokeCertificateOutput struct { + _ struct{} `type:"structure"` + + responseMetadata aws.Response +} + +// String returns the string representation +func (s RevokeCertificateOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s RevokeCertificateOutput) GoString() string { + return s.String() +} + +// SDKResponseMetdata return sthe response metadata for the API. +func (s RevokeCertificateOutput) SDKResponseMetadata() aws.Response { + return s.responseMetadata +} + +// Tags are labels that you can use to identify and organize your private CAs. +// Each tag consists of a key and an optional value. You can associate up to +// 50 tags with a private CA. To add one or more tags to a private CA, call +// the TagCertificateAuthority operation. To remove a tag, call the UntagCertificateAuthority +// operation. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/Tag +type Tag struct { + _ struct{} `type:"structure"` + + // Key (name) of the tag. + // + // Key is a required field + Key *string `min:"1" type:"string" required:"true"` + + // Value of the tag. + Value *string `type:"string"` +} + +// String returns the string representation +func (s Tag) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Tag) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *Tag) Validate() error { + invalidParams := aws.ErrInvalidParams{Context: "Tag"} + + if s.Key == nil { + invalidParams.Add(aws.NewErrParamRequired("Key")) + } + if s.Key != nil && len(*s.Key) < 1 { + invalidParams.Add(aws.NewErrParamMinLen("Key", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/TagCertificateAuthorityRequest +type TagCertificateAuthorityInput struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) that was returned when you called CreateCertificateAuthority. + // This must be of the form: + // + // arn:aws:acm-pca:region:account:certificate-authority/12345678-1234-1234-1234-123456789012 + // + // CertificateAuthorityArn is a required field + CertificateAuthorityArn *string `min:"5" type:"string" required:"true"` + + // List of tags to be associated with the CA. + // + // Tags is a required field + Tags []Tag `min:"1" type:"list" required:"true"` +} + +// String returns the string representation +func (s TagCertificateAuthorityInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s TagCertificateAuthorityInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *TagCertificateAuthorityInput) Validate() error { + invalidParams := aws.ErrInvalidParams{Context: "TagCertificateAuthorityInput"} + + if s.CertificateAuthorityArn == nil { + invalidParams.Add(aws.NewErrParamRequired("CertificateAuthorityArn")) + } + if s.CertificateAuthorityArn != nil && len(*s.CertificateAuthorityArn) < 5 { + invalidParams.Add(aws.NewErrParamMinLen("CertificateAuthorityArn", 5)) + } + + if s.Tags == nil { + invalidParams.Add(aws.NewErrParamRequired("Tags")) + } + if s.Tags != nil && len(s.Tags) < 1 { + invalidParams.Add(aws.NewErrParamMinLen("Tags", 1)) + } + if s.Tags != nil { + for i, v := range s.Tags { + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(aws.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/TagCertificateAuthorityOutput +type TagCertificateAuthorityOutput struct { + _ struct{} `type:"structure"` + + responseMetadata aws.Response +} + +// String returns the string representation +func (s TagCertificateAuthorityOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s TagCertificateAuthorityOutput) GoString() string { + return s.String() +} + +// SDKResponseMetdata return sthe response metadata for the API. +func (s TagCertificateAuthorityOutput) SDKResponseMetadata() aws.Response { + return s.responseMetadata +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/UntagCertificateAuthorityRequest +type UntagCertificateAuthorityInput struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) that was returned when you called CreateCertificateAuthority. + // This must be of the form: + // + // arn:aws:acm-pca:region:account:certificate-authority/12345678-1234-1234-1234-123456789012 + // + // CertificateAuthorityArn is a required field + CertificateAuthorityArn *string `min:"5" type:"string" required:"true"` + + // List of tags to be removed from the CA. + // + // Tags is a required field + Tags []Tag `min:"1" type:"list" required:"true"` +} + +// String returns the string representation +func (s UntagCertificateAuthorityInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UntagCertificateAuthorityInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *UntagCertificateAuthorityInput) Validate() error { + invalidParams := aws.ErrInvalidParams{Context: "UntagCertificateAuthorityInput"} + + if s.CertificateAuthorityArn == nil { + invalidParams.Add(aws.NewErrParamRequired("CertificateAuthorityArn")) + } + if s.CertificateAuthorityArn != nil && len(*s.CertificateAuthorityArn) < 5 { + invalidParams.Add(aws.NewErrParamMinLen("CertificateAuthorityArn", 5)) + } + + if s.Tags == nil { + invalidParams.Add(aws.NewErrParamRequired("Tags")) + } + if s.Tags != nil && len(s.Tags) < 1 { + invalidParams.Add(aws.NewErrParamMinLen("Tags", 1)) + } + if s.Tags != nil { + for i, v := range s.Tags { + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(aws.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/UntagCertificateAuthorityOutput +type UntagCertificateAuthorityOutput struct { + _ struct{} `type:"structure"` + + responseMetadata aws.Response +} + +// String returns the string representation +func (s UntagCertificateAuthorityOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UntagCertificateAuthorityOutput) GoString() string { + return s.String() +} + +// SDKResponseMetdata return sthe response metadata for the API. +func (s UntagCertificateAuthorityOutput) SDKResponseMetadata() aws.Response { + return s.responseMetadata +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/UpdateCertificateAuthorityRequest +type UpdateCertificateAuthorityInput struct { + _ struct{} `type:"structure"` + + // Amazon Resource Name (ARN) of the private CA that issued the certificate + // to be revoked. This must be of the form: + // + // arn:aws:acm-pca:region:account:certificate-authority/12345678-1234-1234-1234-123456789012 + // + // CertificateAuthorityArn is a required field + CertificateAuthorityArn *string `min:"5" type:"string" required:"true"` + + // Revocation information for your private CA. + RevocationConfiguration *RevocationConfiguration `type:"structure"` + + // Status of your private CA. + Status CertificateAuthorityStatus `type:"string" enum:"true"` +} + +// String returns the string representation +func (s UpdateCertificateAuthorityInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateCertificateAuthorityInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *UpdateCertificateAuthorityInput) Validate() error { + invalidParams := aws.ErrInvalidParams{Context: "UpdateCertificateAuthorityInput"} + + if s.CertificateAuthorityArn == nil { + invalidParams.Add(aws.NewErrParamRequired("CertificateAuthorityArn")) + } + if s.CertificateAuthorityArn != nil && len(*s.CertificateAuthorityArn) < 5 { + invalidParams.Add(aws.NewErrParamMinLen("CertificateAuthorityArn", 5)) + } + if s.RevocationConfiguration != nil { + if err := s.RevocationConfiguration.Validate(); err != nil { + invalidParams.AddNested("RevocationConfiguration", err.(aws.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/UpdateCertificateAuthorityOutput +type UpdateCertificateAuthorityOutput struct { + _ struct{} `type:"structure"` + + responseMetadata aws.Response +} + +// String returns the string representation +func (s UpdateCertificateAuthorityOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateCertificateAuthorityOutput) GoString() string { + return s.String() +} + +// SDKResponseMetdata return sthe response metadata for the API. +func (s UpdateCertificateAuthorityOutput) SDKResponseMetadata() aws.Response { + return s.responseMetadata +} + +// Length of time for which the certificate issued by your private certificate +// authority (CA), or by the private CA itself, is valid in days, months, or +// years. You can issue a certificate by calling the IssueCertificate operation. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/Validity +type Validity struct { + _ struct{} `type:"structure"` + + // Specifies whether the Value parameter represents days, months, or years. + // + // Type is a required field + Type ValidityPeriodType `type:"string" required:"true" enum:"true"` + + // Time period. + // + // Value is a required field + Value *int64 `min:"1" type:"long" required:"true"` +} + +// String returns the string representation +func (s Validity) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Validity) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *Validity) Validate() error { + invalidParams := aws.ErrInvalidParams{Context: "Validity"} + if len(s.Type) == 0 { + invalidParams.Add(aws.NewErrParamRequired("Type")) + } + + if s.Value == nil { + invalidParams.Add(aws.NewErrParamRequired("Value")) + } + if s.Value != nil && *s.Value < 1 { + invalidParams.Add(aws.NewErrParamMinValue("Value", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +type AuditReportResponseFormat string + +// Enum values for AuditReportResponseFormat +const ( + AuditReportResponseFormatJson AuditReportResponseFormat = "JSON" + AuditReportResponseFormatCsv AuditReportResponseFormat = "CSV" +) + +func (enum AuditReportResponseFormat) MarshalValue() (string, error) { + return string(enum), nil +} + +func (enum AuditReportResponseFormat) MarshalValueBuf(b []byte) ([]byte, error) { + b = b[0:0] + return append(b, enum...), nil +} + +type AuditReportStatus string + +// Enum values for AuditReportStatus +const ( + AuditReportStatusCreating AuditReportStatus = "CREATING" + AuditReportStatusSuccess AuditReportStatus = "SUCCESS" + AuditReportStatusFailed AuditReportStatus = "FAILED" +) + +func (enum AuditReportStatus) MarshalValue() (string, error) { + return string(enum), nil +} + +func (enum AuditReportStatus) MarshalValueBuf(b []byte) ([]byte, error) { + b = b[0:0] + return append(b, enum...), nil +} + +type CertificateAuthorityStatus string + +// Enum values for CertificateAuthorityStatus +const ( + CertificateAuthorityStatusCreating CertificateAuthorityStatus = "CREATING" + CertificateAuthorityStatusPendingCertificate CertificateAuthorityStatus = "PENDING_CERTIFICATE" + CertificateAuthorityStatusActive CertificateAuthorityStatus = "ACTIVE" + CertificateAuthorityStatusDeleted CertificateAuthorityStatus = "DELETED" + CertificateAuthorityStatusDisabled CertificateAuthorityStatus = "DISABLED" + CertificateAuthorityStatusExpired CertificateAuthorityStatus = "EXPIRED" + CertificateAuthorityStatusFailed CertificateAuthorityStatus = "FAILED" +) + +func (enum CertificateAuthorityStatus) MarshalValue() (string, error) { + return string(enum), nil +} + +func (enum CertificateAuthorityStatus) MarshalValueBuf(b []byte) ([]byte, error) { + b = b[0:0] + return append(b, enum...), nil +} + +type CertificateAuthorityType string + +// Enum values for CertificateAuthorityType +const ( + CertificateAuthorityTypeSubordinate CertificateAuthorityType = "SUBORDINATE" +) + +func (enum CertificateAuthorityType) MarshalValue() (string, error) { + return string(enum), nil +} + +func (enum CertificateAuthorityType) MarshalValueBuf(b []byte) ([]byte, error) { + b = b[0:0] + return append(b, enum...), nil +} + +type FailureReason string + +// Enum values for FailureReason +const ( + FailureReasonRequestTimedOut FailureReason = "REQUEST_TIMED_OUT" + FailureReasonUnsupportedAlgorithm FailureReason = "UNSUPPORTED_ALGORITHM" + FailureReasonOther FailureReason = "OTHER" +) + +func (enum FailureReason) MarshalValue() (string, error) { + return string(enum), nil +} + +func (enum FailureReason) MarshalValueBuf(b []byte) ([]byte, error) { + b = b[0:0] + return append(b, enum...), nil +} + +type KeyAlgorithm string + +// Enum values for KeyAlgorithm +const ( + KeyAlgorithmRsa2048 KeyAlgorithm = "RSA_2048" + KeyAlgorithmRsa4096 KeyAlgorithm = "RSA_4096" + KeyAlgorithmEcPrime256v1 KeyAlgorithm = "EC_prime256v1" + KeyAlgorithmEcSecp384r1 KeyAlgorithm = "EC_secp384r1" +) + +func (enum KeyAlgorithm) MarshalValue() (string, error) { + return string(enum), nil +} + +func (enum KeyAlgorithm) MarshalValueBuf(b []byte) ([]byte, error) { + b = b[0:0] + return append(b, enum...), nil +} + +type RevocationReason string + +// Enum values for RevocationReason +const ( + RevocationReasonUnspecified RevocationReason = "UNSPECIFIED" + RevocationReasonKeyCompromise RevocationReason = "KEY_COMPROMISE" + RevocationReasonCertificateAuthorityCompromise RevocationReason = "CERTIFICATE_AUTHORITY_COMPROMISE" + RevocationReasonAffiliationChanged RevocationReason = "AFFILIATION_CHANGED" + RevocationReasonSuperseded RevocationReason = "SUPERSEDED" + RevocationReasonCessationOfOperation RevocationReason = "CESSATION_OF_OPERATION" + RevocationReasonPrivilegeWithdrawn RevocationReason = "PRIVILEGE_WITHDRAWN" + RevocationReasonAACompromise RevocationReason = "A_A_COMPROMISE" +) + +func (enum RevocationReason) MarshalValue() (string, error) { + return string(enum), nil +} + +func (enum RevocationReason) MarshalValueBuf(b []byte) ([]byte, error) { + b = b[0:0] + return append(b, enum...), nil +} + +type SigningAlgorithm string + +// Enum values for SigningAlgorithm +const ( + SigningAlgorithmSha256withecdsa SigningAlgorithm = "SHA256WITHECDSA" + SigningAlgorithmSha384withecdsa SigningAlgorithm = "SHA384WITHECDSA" + SigningAlgorithmSha512withecdsa SigningAlgorithm = "SHA512WITHECDSA" + SigningAlgorithmSha256withrsa SigningAlgorithm = "SHA256WITHRSA" + SigningAlgorithmSha384withrsa SigningAlgorithm = "SHA384WITHRSA" + SigningAlgorithmSha512withrsa SigningAlgorithm = "SHA512WITHRSA" +) + +func (enum SigningAlgorithm) MarshalValue() (string, error) { + return string(enum), nil +} + +func (enum SigningAlgorithm) MarshalValueBuf(b []byte) ([]byte, error) { + b = b[0:0] + return append(b, enum...), nil +} + +type ValidityPeriodType string + +// Enum values for ValidityPeriodType +const ( + ValidityPeriodTypeEndDate ValidityPeriodType = "END_DATE" + ValidityPeriodTypeAbsolute ValidityPeriodType = "ABSOLUTE" + ValidityPeriodTypeDays ValidityPeriodType = "DAYS" + ValidityPeriodTypeMonths ValidityPeriodType = "MONTHS" + ValidityPeriodTypeYears ValidityPeriodType = "YEARS" +) + +func (enum ValidityPeriodType) MarshalValue() (string, error) { + return string(enum), nil +} + +func (enum ValidityPeriodType) MarshalValueBuf(b []byte) ([]byte, error) { + b = b[0:0] + return append(b, enum...), nil +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/acmpca/doc.go b/vendor/github.com/aws/aws-sdk-go-v2/service/acmpca/doc.go new file mode 100644 index 0000000..df27a53 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/acmpca/doc.go @@ -0,0 +1,55 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package acmpca provides the client and types for making API +// requests to AWS Certificate Manager Private Certificate Authority. +// +// You can use the ACM PCA API to create a private certificate authority (CA). +// You must first call the CreateCertificateAuthority operation. If successful, +// the operation returns an Amazon Resource Name (ARN) for your private CA. +// Use this ARN as input to the GetCertificateAuthorityCsr operation to retrieve +// the certificate signing request (CSR) for your private CA certificate. Sign +// the CSR using the root or an intermediate CA in your on-premises PKI hierarchy, +// and call the ImportCertificateAuthorityCertificate to import your signed +// private CA certificate into ACM PCA. +// +// Use your private CA to issue and revoke certificates. These are private certificates +// that identify and secure client computers, servers, applications, services, +// devices, and users over SSLS/TLS connections within your organization. Call +// the IssueCertificate operation to issue a certificate. Call the RevokeCertificate +// operation to revoke a certificate. +// +// Certificates issued by your private CA can be trusted only within your organization, +// not publicly. +// +// Your private CA can optionally create a certificate revocation list (CRL) +// to track the certificates you revoke. To create a CRL, you must specify a +// RevocationConfiguration object when you call the CreateCertificateAuthority +// operation. ACM PCA writes the CRL to an S3 bucket that you specify. You must +// specify a bucket policy that grants ACM PCA write permission. +// +// You can also call the CreateCertificateAuthorityAuditReport to create an +// optional audit report that lists every time the CA private key is used. The +// private key is used for signing when the IssueCertificate or RevokeCertificate +// operation is called. +// +// See https://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22 for more information on this service. +// +// See acmpca package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/acmpca/ +// +// Using the Client +// +// To AWS Certificate Manager Private Certificate Authority with the SDK use the New function to create +// a new service client. With that client you can make API requests to the service. +// These clients are safe to use concurrently. +// +// See the SDK's documentation for more information on how to use the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// See aws.Config documentation for more information on configuring SDK clients. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// See the AWS Certificate Manager Private Certificate Authority client ACMPCA for more +// information on creating client for this service. +// https://docs.aws.amazon.com/sdk-for-go/api/service/acmpca/#New +package acmpca diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/acmpca/errors.go b/vendor/github.com/aws/aws-sdk-go-v2/service/acmpca/errors.go new file mode 100644 index 0000000..5ce2781 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/acmpca/errors.go @@ -0,0 +1,110 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +package acmpca + +const ( + + // ErrCodeCertificateMismatchException for service response error code + // "CertificateMismatchException". + // + // The certificate authority certificate you are importing does not comply with + // conditions specified in the certificate that signed it. + ErrCodeCertificateMismatchException = "CertificateMismatchException" + + // ErrCodeConcurrentModificationException for service response error code + // "ConcurrentModificationException". + // + // A previous update to your private CA is still ongoing. + ErrCodeConcurrentModificationException = "ConcurrentModificationException" + + // ErrCodeInvalidArgsException for service response error code + // "InvalidArgsException". + // + // One or more of the specified arguments was not valid. + ErrCodeInvalidArgsException = "InvalidArgsException" + + // ErrCodeInvalidArnException for service response error code + // "InvalidArnException". + // + // The requested Amazon Resource Name (ARN) does not refer to an existing resource. + ErrCodeInvalidArnException = "InvalidArnException" + + // ErrCodeInvalidNextTokenException for service response error code + // "InvalidNextTokenException". + // + // The token specified in the NextToken argument is not valid. Use the token + // returned from your previous call to ListCertificateAuthorities. + ErrCodeInvalidNextTokenException = "InvalidNextTokenException" + + // ErrCodeInvalidPolicyException for service response error code + // "InvalidPolicyException". + // + // The S3 bucket policy is not valid. The policy must give ACM PCA rights to + // read from and write to the bucket and find the bucket location. + ErrCodeInvalidPolicyException = "InvalidPolicyException" + + // ErrCodeInvalidStateException for service response error code + // "InvalidStateException". + // + // The private CA is in a state during which a report or certificate cannot + // be generated. + ErrCodeInvalidStateException = "InvalidStateException" + + // ErrCodeInvalidTagException for service response error code + // "InvalidTagException". + // + // The tag associated with the CA is not valid. The invalid argument is contained + // in the message field. + ErrCodeInvalidTagException = "InvalidTagException" + + // ErrCodeLimitExceededException for service response error code + // "LimitExceededException". + // + // An ACM PCA limit has been exceeded. See the exception message returned to + // determine the limit that was exceeded. + ErrCodeLimitExceededException = "LimitExceededException" + + // ErrCodeMalformedCSRException for service response error code + // "MalformedCSRException". + // + // The certificate signing request is invalid. + ErrCodeMalformedCSRException = "MalformedCSRException" + + // ErrCodeMalformedCertificateException for service response error code + // "MalformedCertificateException". + // + // One or more fields in the certificate are invalid. + ErrCodeMalformedCertificateException = "MalformedCertificateException" + + // ErrCodeRequestAlreadyProcessedException for service response error code + // "RequestAlreadyProcessedException". + // + // Your request has already been completed. + ErrCodeRequestAlreadyProcessedException = "RequestAlreadyProcessedException" + + // ErrCodeRequestFailedException for service response error code + // "RequestFailedException". + // + // The request has failed for an unspecified reason. + ErrCodeRequestFailedException = "RequestFailedException" + + // ErrCodeRequestInProgressException for service response error code + // "RequestInProgressException". + // + // Your request is already in progress. + ErrCodeRequestInProgressException = "RequestInProgressException" + + // ErrCodeResourceNotFoundException for service response error code + // "ResourceNotFoundException". + // + // A resource such as a private CA, S3 bucket, certificate, or audit report + // cannot be found. + ErrCodeResourceNotFoundException = "ResourceNotFoundException" + + // ErrCodeTooManyTagsException for service response error code + // "TooManyTagsException". + // + // You can associate up to 50 tags with a private CA. Exception information + // is contained in the exception message field. + ErrCodeTooManyTagsException = "TooManyTagsException" +) diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/acmpca/service.go b/vendor/github.com/aws/aws-sdk-go-v2/service/acmpca/service.go new file mode 100644 index 0000000..2c22867 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/acmpca/service.go @@ -0,0 +1,82 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +package acmpca + +import ( + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/aws/signer/v4" + "github.com/aws/aws-sdk-go-v2/private/protocol/jsonrpc" +) + +// ACMPCA provides the API operation methods for making requests to +// AWS Certificate Manager Private Certificate Authority. See this package's package overview docs +// for details on the service. +// +// ACMPCA methods are safe to use concurrently. It is not safe to +// modify mutate any of the struct's properties though. +type ACMPCA struct { + *aws.Client +} + +// Used for custom client initialization logic +var initClient func(*ACMPCA) + +// Used for custom request initialization logic +var initRequest func(*ACMPCA, *aws.Request) + +// Service information constants +const ( + ServiceName = "acm-pca" // Service endpoint prefix API calls made to. + EndpointsID = ServiceName // Service ID for Regions and Endpoints metadata. +) + +// New creates a new instance of the ACMPCA client with a config. +// +// Example: +// // Create a ACMPCA client from just a config. +// svc := acmpca.New(myConfig) +func New(config aws.Config) *ACMPCA { + var signingName string + signingRegion := config.Region + + svc := &ACMPCA{ + Client: aws.NewClient( + config, + aws.Metadata{ + ServiceName: ServiceName, + SigningName: signingName, + SigningRegion: signingRegion, + APIVersion: "2017-08-22", + JSONVersion: "1.1", + TargetPrefix: "ACMPrivateCA", + }, + ), + } + + // Handlers + svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) + svc.Handlers.Build.PushBackNamed(jsonrpc.BuildHandler) + svc.Handlers.Unmarshal.PushBackNamed(jsonrpc.UnmarshalHandler) + svc.Handlers.UnmarshalMeta.PushBackNamed(jsonrpc.UnmarshalMetaHandler) + svc.Handlers.UnmarshalError.PushBackNamed(jsonrpc.UnmarshalErrorHandler) + + // Run custom client initialization if present + if initClient != nil { + initClient(svc) + } + + return svc +} + +// newRequest creates a new request for a ACMPCA operation and runs any +// custom request initialization. +func (c *ACMPCA) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { + req := c.NewRequest(op, params, data) + + // Run custom request initialization if present + if initRequest != nil { + initRequest(c, req) + } + + return req +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/acmpca/waiters.go b/vendor/github.com/aws/aws-sdk-go-v2/service/acmpca/waiters.go new file mode 100644 index 0000000..d1ca143 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/acmpca/waiters.go @@ -0,0 +1,157 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +package acmpca + +import ( + "time" + + "github.com/aws/aws-sdk-go-v2/aws" +) + +// WaitUntilAuditReportCreated uses the ACM-PCA API operation +// DescribeCertificateAuthorityAuditReport 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 *ACMPCA) WaitUntilAuditReportCreated(input *DescribeCertificateAuthorityAuditReportInput) error { + return c.WaitUntilAuditReportCreatedWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilAuditReportCreatedWithContext is an extended version of WaitUntilAuditReportCreated. +// 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 *ACMPCA) WaitUntilAuditReportCreatedWithContext(ctx aws.Context, input *DescribeCertificateAuthorityAuditReportInput, opts ...aws.WaiterOption) error { + w := aws.Waiter{ + Name: "WaitUntilAuditReportCreated", + MaxAttempts: 60, + Delay: aws.ConstantWaiterDelay(3 * time.Second), + Acceptors: []aws.WaiterAcceptor{ + { + State: aws.SuccessWaiterState, + Matcher: aws.PathWaiterMatch, Argument: "AuditReportStatus", + Expected: "SUCCESS", + }, + }, + Logger: c.Config.Logger, + NewRequest: func(opts []aws.Option) (*aws.Request, error) { + var inCpy *DescribeCertificateAuthorityAuditReportInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req := c.DescribeCertificateAuthorityAuditReportRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req.Request, nil + }, + } + w.ApplyOptions(opts...) + + return w.WaitWithContext(ctx) +} + +// WaitUntilCertificateAuthorityCSRCreated uses the ACM-PCA API operation +// GetCertificateAuthorityCsr 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 *ACMPCA) WaitUntilCertificateAuthorityCSRCreated(input *GetCertificateAuthorityCsrInput) error { + return c.WaitUntilCertificateAuthorityCSRCreatedWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilCertificateAuthorityCSRCreatedWithContext is an extended version of WaitUntilCertificateAuthorityCSRCreated. +// 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 *ACMPCA) WaitUntilCertificateAuthorityCSRCreatedWithContext(ctx aws.Context, input *GetCertificateAuthorityCsrInput, opts ...aws.WaiterOption) error { + w := aws.Waiter{ + Name: "WaitUntilCertificateAuthorityCSRCreated", + MaxAttempts: 60, + Delay: aws.ConstantWaiterDelay(3 * time.Second), + Acceptors: []aws.WaiterAcceptor{ + { + State: aws.SuccessWaiterState, + Matcher: aws.StatusWaiterMatch, + Expected: 200, + }, + { + State: aws.RetryWaiterState, + Matcher: aws.ErrorWaiterMatch, + Expected: "RequestInProgressException", + }, + }, + Logger: c.Config.Logger, + NewRequest: func(opts []aws.Option) (*aws.Request, error) { + var inCpy *GetCertificateAuthorityCsrInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req := c.GetCertificateAuthorityCsrRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req.Request, nil + }, + } + w.ApplyOptions(opts...) + + return w.WaitWithContext(ctx) +} + +// WaitUntilCertificateIssued uses the ACM-PCA API operation +// GetCertificate 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 *ACMPCA) WaitUntilCertificateIssued(input *GetCertificateInput) error { + return c.WaitUntilCertificateIssuedWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilCertificateIssuedWithContext is an extended version of WaitUntilCertificateIssued. +// 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 *ACMPCA) WaitUntilCertificateIssuedWithContext(ctx aws.Context, input *GetCertificateInput, opts ...aws.WaiterOption) error { + w := aws.Waiter{ + Name: "WaitUntilCertificateIssued", + MaxAttempts: 60, + Delay: aws.ConstantWaiterDelay(3 * time.Second), + Acceptors: []aws.WaiterAcceptor{ + { + State: aws.SuccessWaiterState, + Matcher: aws.StatusWaiterMatch, + Expected: 200, + }, + { + State: aws.RetryWaiterState, + Matcher: aws.ErrorWaiterMatch, + Expected: "RequestInProgressException", + }, + }, + Logger: c.Config.Logger, + NewRequest: func(opts []aws.Option) (*aws.Request, error) { + var inCpy *GetCertificateInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req := c.GetCertificateRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req.Request, nil + }, + } + w.ApplyOptions(opts...) + + return w.WaitWithContext(ctx) +} diff --git a/vendor/github.com/jmespath/go-jmespath/LICENSE b/vendor/github.com/jmespath/go-jmespath/LICENSE new file mode 100644 index 0000000..b03310a --- /dev/null +++ b/vendor/github.com/jmespath/go-jmespath/LICENSE @@ -0,0 +1,13 @@ +Copyright 2015 James Saryerwinnie + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/vendor/github.com/jmespath/go-jmespath/api.go b/vendor/github.com/jmespath/go-jmespath/api.go new file mode 100644 index 0000000..8e26ffe --- /dev/null +++ b/vendor/github.com/jmespath/go-jmespath/api.go @@ -0,0 +1,49 @@ +package jmespath + +import "strconv" + +// JMESPath is the epresentation of a compiled JMES path query. A JMESPath is +// safe for concurrent use by multiple goroutines. +type JMESPath struct { + ast ASTNode + intr *treeInterpreter +} + +// Compile parses a JMESPath expression and returns, if successful, a JMESPath +// object that can be used to match against data. +func Compile(expression string) (*JMESPath, error) { + parser := NewParser() + ast, err := parser.Parse(expression) + if err != nil { + return nil, err + } + jmespath := &JMESPath{ast: ast, intr: newInterpreter()} + return jmespath, nil +} + +// MustCompile is like Compile but panics if the expression cannot be parsed. +// It simplifies safe initialization of global variables holding compiled +// JMESPaths. +func MustCompile(expression string) *JMESPath { + jmespath, err := Compile(expression) + if err != nil { + panic(`jmespath: Compile(` + strconv.Quote(expression) + `): ` + err.Error()) + } + return jmespath +} + +// Search evaluates a JMESPath expression against input data and returns the result. +func (jp *JMESPath) Search(data interface{}) (interface{}, error) { + return jp.intr.Execute(jp.ast, data) +} + +// Search evaluates a JMESPath expression against input data and returns the result. +func Search(expression string, data interface{}) (interface{}, error) { + intr := newInterpreter() + parser := NewParser() + ast, err := parser.Parse(expression) + if err != nil { + return nil, err + } + return intr.Execute(ast, data) +} diff --git a/vendor/github.com/jmespath/go-jmespath/astnodetype_string.go b/vendor/github.com/jmespath/go-jmespath/astnodetype_string.go new file mode 100644 index 0000000..1cd2d23 --- /dev/null +++ b/vendor/github.com/jmespath/go-jmespath/astnodetype_string.go @@ -0,0 +1,16 @@ +// generated by stringer -type astNodeType; DO NOT EDIT + +package jmespath + +import "fmt" + +const _astNodeType_name = "ASTEmptyASTComparatorASTCurrentNodeASTExpRefASTFunctionExpressionASTFieldASTFilterProjectionASTFlattenASTIdentityASTIndexASTIndexExpressionASTKeyValPairASTLiteralASTMultiSelectHashASTMultiSelectListASTOrExpressionASTAndExpressionASTNotExpressionASTPipeASTProjectionASTSubexpressionASTSliceASTValueProjection" + +var _astNodeType_index = [...]uint16{0, 8, 21, 35, 44, 65, 73, 92, 102, 113, 121, 139, 152, 162, 180, 198, 213, 229, 245, 252, 265, 281, 289, 307} + +func (i astNodeType) String() string { + if i < 0 || i >= astNodeType(len(_astNodeType_index)-1) { + return fmt.Sprintf("astNodeType(%d)", i) + } + return _astNodeType_name[_astNodeType_index[i]:_astNodeType_index[i+1]] +} diff --git a/vendor/github.com/jmespath/go-jmespath/functions.go b/vendor/github.com/jmespath/go-jmespath/functions.go new file mode 100644 index 0000000..9b7cd89 --- /dev/null +++ b/vendor/github.com/jmespath/go-jmespath/functions.go @@ -0,0 +1,842 @@ +package jmespath + +import ( + "encoding/json" + "errors" + "fmt" + "math" + "reflect" + "sort" + "strconv" + "strings" + "unicode/utf8" +) + +type jpFunction func(arguments []interface{}) (interface{}, error) + +type jpType string + +const ( + jpUnknown jpType = "unknown" + jpNumber jpType = "number" + jpString jpType = "string" + jpArray jpType = "array" + jpObject jpType = "object" + jpArrayNumber jpType = "array[number]" + jpArrayString jpType = "array[string]" + jpExpref jpType = "expref" + jpAny jpType = "any" +) + +type functionEntry struct { + name string + arguments []argSpec + handler jpFunction + hasExpRef bool +} + +type argSpec struct { + types []jpType + variadic bool +} + +type byExprString struct { + intr *treeInterpreter + node ASTNode + items []interface{} + hasError bool +} + +func (a *byExprString) Len() int { + return len(a.items) +} +func (a *byExprString) Swap(i, j int) { + a.items[i], a.items[j] = a.items[j], a.items[i] +} +func (a *byExprString) Less(i, j int) bool { + first, err := a.intr.Execute(a.node, a.items[i]) + if err != nil { + a.hasError = true + // Return a dummy value. + return true + } + ith, ok := first.(string) + if !ok { + a.hasError = true + return true + } + second, err := a.intr.Execute(a.node, a.items[j]) + if err != nil { + a.hasError = true + // Return a dummy value. + return true + } + jth, ok := second.(string) + if !ok { + a.hasError = true + return true + } + return ith < jth +} + +type byExprFloat struct { + intr *treeInterpreter + node ASTNode + items []interface{} + hasError bool +} + +func (a *byExprFloat) Len() int { + return len(a.items) +} +func (a *byExprFloat) Swap(i, j int) { + a.items[i], a.items[j] = a.items[j], a.items[i] +} +func (a *byExprFloat) Less(i, j int) bool { + first, err := a.intr.Execute(a.node, a.items[i]) + if err != nil { + a.hasError = true + // Return a dummy value. + return true + } + ith, ok := first.(float64) + if !ok { + a.hasError = true + return true + } + second, err := a.intr.Execute(a.node, a.items[j]) + if err != nil { + a.hasError = true + // Return a dummy value. + return true + } + jth, ok := second.(float64) + if !ok { + a.hasError = true + return true + } + return ith < jth +} + +type functionCaller struct { + functionTable map[string]functionEntry +} + +func newFunctionCaller() *functionCaller { + caller := &functionCaller{} + caller.functionTable = map[string]functionEntry{ + "length": { + name: "length", + arguments: []argSpec{ + {types: []jpType{jpString, jpArray, jpObject}}, + }, + handler: jpfLength, + }, + "starts_with": { + name: "starts_with", + arguments: []argSpec{ + {types: []jpType{jpString}}, + {types: []jpType{jpString}}, + }, + handler: jpfStartsWith, + }, + "abs": { + name: "abs", + arguments: []argSpec{ + {types: []jpType{jpNumber}}, + }, + handler: jpfAbs, + }, + "avg": { + name: "avg", + arguments: []argSpec{ + {types: []jpType{jpArrayNumber}}, + }, + handler: jpfAvg, + }, + "ceil": { + name: "ceil", + arguments: []argSpec{ + {types: []jpType{jpNumber}}, + }, + handler: jpfCeil, + }, + "contains": { + name: "contains", + arguments: []argSpec{ + {types: []jpType{jpArray, jpString}}, + {types: []jpType{jpAny}}, + }, + handler: jpfContains, + }, + "ends_with": { + name: "ends_with", + arguments: []argSpec{ + {types: []jpType{jpString}}, + {types: []jpType{jpString}}, + }, + handler: jpfEndsWith, + }, + "floor": { + name: "floor", + arguments: []argSpec{ + {types: []jpType{jpNumber}}, + }, + handler: jpfFloor, + }, + "map": { + name: "amp", + arguments: []argSpec{ + {types: []jpType{jpExpref}}, + {types: []jpType{jpArray}}, + }, + handler: jpfMap, + hasExpRef: true, + }, + "max": { + name: "max", + arguments: []argSpec{ + {types: []jpType{jpArrayNumber, jpArrayString}}, + }, + handler: jpfMax, + }, + "merge": { + name: "merge", + arguments: []argSpec{ + {types: []jpType{jpObject}, variadic: true}, + }, + handler: jpfMerge, + }, + "max_by": { + name: "max_by", + arguments: []argSpec{ + {types: []jpType{jpArray}}, + {types: []jpType{jpExpref}}, + }, + handler: jpfMaxBy, + hasExpRef: true, + }, + "sum": { + name: "sum", + arguments: []argSpec{ + {types: []jpType{jpArrayNumber}}, + }, + handler: jpfSum, + }, + "min": { + name: "min", + arguments: []argSpec{ + {types: []jpType{jpArrayNumber, jpArrayString}}, + }, + handler: jpfMin, + }, + "min_by": { + name: "min_by", + arguments: []argSpec{ + {types: []jpType{jpArray}}, + {types: []jpType{jpExpref}}, + }, + handler: jpfMinBy, + hasExpRef: true, + }, + "type": { + name: "type", + arguments: []argSpec{ + {types: []jpType{jpAny}}, + }, + handler: jpfType, + }, + "keys": { + name: "keys", + arguments: []argSpec{ + {types: []jpType{jpObject}}, + }, + handler: jpfKeys, + }, + "values": { + name: "values", + arguments: []argSpec{ + {types: []jpType{jpObject}}, + }, + handler: jpfValues, + }, + "sort": { + name: "sort", + arguments: []argSpec{ + {types: []jpType{jpArrayString, jpArrayNumber}}, + }, + handler: jpfSort, + }, + "sort_by": { + name: "sort_by", + arguments: []argSpec{ + {types: []jpType{jpArray}}, + {types: []jpType{jpExpref}}, + }, + handler: jpfSortBy, + hasExpRef: true, + }, + "join": { + name: "join", + arguments: []argSpec{ + {types: []jpType{jpString}}, + {types: []jpType{jpArrayString}}, + }, + handler: jpfJoin, + }, + "reverse": { + name: "reverse", + arguments: []argSpec{ + {types: []jpType{jpArray, jpString}}, + }, + handler: jpfReverse, + }, + "to_array": { + name: "to_array", + arguments: []argSpec{ + {types: []jpType{jpAny}}, + }, + handler: jpfToArray, + }, + "to_string": { + name: "to_string", + arguments: []argSpec{ + {types: []jpType{jpAny}}, + }, + handler: jpfToString, + }, + "to_number": { + name: "to_number", + arguments: []argSpec{ + {types: []jpType{jpAny}}, + }, + handler: jpfToNumber, + }, + "not_null": { + name: "not_null", + arguments: []argSpec{ + {types: []jpType{jpAny}, variadic: true}, + }, + handler: jpfNotNull, + }, + } + return caller +} + +func (e *functionEntry) resolveArgs(arguments []interface{}) ([]interface{}, error) { + if len(e.arguments) == 0 { + return arguments, nil + } + if !e.arguments[len(e.arguments)-1].variadic { + if len(e.arguments) != len(arguments) { + return nil, errors.New("incorrect number of args") + } + for i, spec := range e.arguments { + userArg := arguments[i] + err := spec.typeCheck(userArg) + if err != nil { + return nil, err + } + } + return arguments, nil + } + if len(arguments) < len(e.arguments) { + return nil, errors.New("Invalid arity.") + } + return arguments, nil +} + +func (a *argSpec) typeCheck(arg interface{}) error { + for _, t := range a.types { + switch t { + case jpNumber: + if _, ok := arg.(float64); ok { + return nil + } + case jpString: + if _, ok := arg.(string); ok { + return nil + } + case jpArray: + if isSliceType(arg) { + return nil + } + case jpObject: + if _, ok := arg.(map[string]interface{}); ok { + return nil + } + case jpArrayNumber: + if _, ok := toArrayNum(arg); ok { + return nil + } + case jpArrayString: + if _, ok := toArrayStr(arg); ok { + return nil + } + case jpAny: + return nil + case jpExpref: + if _, ok := arg.(expRef); ok { + return nil + } + } + } + return fmt.Errorf("Invalid type for: %v, expected: %#v", arg, a.types) +} + +func (f *functionCaller) CallFunction(name string, arguments []interface{}, intr *treeInterpreter) (interface{}, error) { + entry, ok := f.functionTable[name] + if !ok { + return nil, errors.New("unknown function: " + name) + } + resolvedArgs, err := entry.resolveArgs(arguments) + if err != nil { + return nil, err + } + if entry.hasExpRef { + var extra []interface{} + extra = append(extra, intr) + resolvedArgs = append(extra, resolvedArgs...) + } + return entry.handler(resolvedArgs) +} + +func jpfAbs(arguments []interface{}) (interface{}, error) { + num := arguments[0].(float64) + return math.Abs(num), nil +} + +func jpfLength(arguments []interface{}) (interface{}, error) { + arg := arguments[0] + if c, ok := arg.(string); ok { + return float64(utf8.RuneCountInString(c)), nil + } else if isSliceType(arg) { + v := reflect.ValueOf(arg) + return float64(v.Len()), nil + } else if c, ok := arg.(map[string]interface{}); ok { + return float64(len(c)), nil + } + return nil, errors.New("could not compute length()") +} + +func jpfStartsWith(arguments []interface{}) (interface{}, error) { + search := arguments[0].(string) + prefix := arguments[1].(string) + return strings.HasPrefix(search, prefix), nil +} + +func jpfAvg(arguments []interface{}) (interface{}, error) { + // We've already type checked the value so we can safely use + // type assertions. + args := arguments[0].([]interface{}) + length := float64(len(args)) + numerator := 0.0 + for _, n := range args { + numerator += n.(float64) + } + return numerator / length, nil +} +func jpfCeil(arguments []interface{}) (interface{}, error) { + val := arguments[0].(float64) + return math.Ceil(val), nil +} +func jpfContains(arguments []interface{}) (interface{}, error) { + search := arguments[0] + el := arguments[1] + if searchStr, ok := search.(string); ok { + if elStr, ok := el.(string); ok { + return strings.Index(searchStr, elStr) != -1, nil + } + return false, nil + } + // Otherwise this is a generic contains for []interface{} + general := search.([]interface{}) + for _, item := range general { + if item == el { + return true, nil + } + } + return false, nil +} +func jpfEndsWith(arguments []interface{}) (interface{}, error) { + search := arguments[0].(string) + suffix := arguments[1].(string) + return strings.HasSuffix(search, suffix), nil +} +func jpfFloor(arguments []interface{}) (interface{}, error) { + val := arguments[0].(float64) + return math.Floor(val), nil +} +func jpfMap(arguments []interface{}) (interface{}, error) { + intr := arguments[0].(*treeInterpreter) + exp := arguments[1].(expRef) + node := exp.ref + arr := arguments[2].([]interface{}) + mapped := make([]interface{}, 0, len(arr)) + for _, value := range arr { + current, err := intr.Execute(node, value) + if err != nil { + return nil, err + } + mapped = append(mapped, current) + } + return mapped, nil +} +func jpfMax(arguments []interface{}) (interface{}, error) { + if items, ok := toArrayNum(arguments[0]); ok { + if len(items) == 0 { + return nil, nil + } + if len(items) == 1 { + return items[0], nil + } + best := items[0] + for _, item := range items[1:] { + if item > best { + best = item + } + } + return best, nil + } + // Otherwise we're dealing with a max() of strings. + items, _ := toArrayStr(arguments[0]) + if len(items) == 0 { + return nil, nil + } + if len(items) == 1 { + return items[0], nil + } + best := items[0] + for _, item := range items[1:] { + if item > best { + best = item + } + } + return best, nil +} +func jpfMerge(arguments []interface{}) (interface{}, error) { + final := make(map[string]interface{}) + for _, m := range arguments { + mapped := m.(map[string]interface{}) + for key, value := range mapped { + final[key] = value + } + } + return final, nil +} +func jpfMaxBy(arguments []interface{}) (interface{}, error) { + intr := arguments[0].(*treeInterpreter) + arr := arguments[1].([]interface{}) + exp := arguments[2].(expRef) + node := exp.ref + if len(arr) == 0 { + return nil, nil + } else if len(arr) == 1 { + return arr[0], nil + } + start, err := intr.Execute(node, arr[0]) + if err != nil { + return nil, err + } + switch t := start.(type) { + case float64: + bestVal := t + bestItem := arr[0] + for _, item := range arr[1:] { + result, err := intr.Execute(node, item) + if err != nil { + return nil, err + } + current, ok := result.(float64) + if !ok { + return nil, errors.New("invalid type, must be number") + } + if current > bestVal { + bestVal = current + bestItem = item + } + } + return bestItem, nil + case string: + bestVal := t + bestItem := arr[0] + for _, item := range arr[1:] { + result, err := intr.Execute(node, item) + if err != nil { + return nil, err + } + current, ok := result.(string) + if !ok { + return nil, errors.New("invalid type, must be string") + } + if current > bestVal { + bestVal = current + bestItem = item + } + } + return bestItem, nil + default: + return nil, errors.New("invalid type, must be number of string") + } +} +func jpfSum(arguments []interface{}) (interface{}, error) { + items, _ := toArrayNum(arguments[0]) + sum := 0.0 + for _, item := range items { + sum += item + } + return sum, nil +} + +func jpfMin(arguments []interface{}) (interface{}, error) { + if items, ok := toArrayNum(arguments[0]); ok { + if len(items) == 0 { + return nil, nil + } + if len(items) == 1 { + return items[0], nil + } + best := items[0] + for _, item := range items[1:] { + if item < best { + best = item + } + } + return best, nil + } + items, _ := toArrayStr(arguments[0]) + if len(items) == 0 { + return nil, nil + } + if len(items) == 1 { + return items[0], nil + } + best := items[0] + for _, item := range items[1:] { + if item < best { + best = item + } + } + return best, nil +} + +func jpfMinBy(arguments []interface{}) (interface{}, error) { + intr := arguments[0].(*treeInterpreter) + arr := arguments[1].([]interface{}) + exp := arguments[2].(expRef) + node := exp.ref + if len(arr) == 0 { + return nil, nil + } else if len(arr) == 1 { + return arr[0], nil + } + start, err := intr.Execute(node, arr[0]) + if err != nil { + return nil, err + } + if t, ok := start.(float64); ok { + bestVal := t + bestItem := arr[0] + for _, item := range arr[1:] { + result, err := intr.Execute(node, item) + if err != nil { + return nil, err + } + current, ok := result.(float64) + if !ok { + return nil, errors.New("invalid type, must be number") + } + if current < bestVal { + bestVal = current + bestItem = item + } + } + return bestItem, nil + } else if t, ok := start.(string); ok { + bestVal := t + bestItem := arr[0] + for _, item := range arr[1:] { + result, err := intr.Execute(node, item) + if err != nil { + return nil, err + } + current, ok := result.(string) + if !ok { + return nil, errors.New("invalid type, must be string") + } + if current < bestVal { + bestVal = current + bestItem = item + } + } + return bestItem, nil + } else { + return nil, errors.New("invalid type, must be number of string") + } +} +func jpfType(arguments []interface{}) (interface{}, error) { + arg := arguments[0] + if _, ok := arg.(float64); ok { + return "number", nil + } + if _, ok := arg.(string); ok { + return "string", nil + } + if _, ok := arg.([]interface{}); ok { + return "array", nil + } + if _, ok := arg.(map[string]interface{}); ok { + return "object", nil + } + if arg == nil { + return "null", nil + } + if arg == true || arg == false { + return "boolean", nil + } + return nil, errors.New("unknown type") +} +func jpfKeys(arguments []interface{}) (interface{}, error) { + arg := arguments[0].(map[string]interface{}) + collected := make([]interface{}, 0, len(arg)) + for key := range arg { + collected = append(collected, key) + } + return collected, nil +} +func jpfValues(arguments []interface{}) (interface{}, error) { + arg := arguments[0].(map[string]interface{}) + collected := make([]interface{}, 0, len(arg)) + for _, value := range arg { + collected = append(collected, value) + } + return collected, nil +} +func jpfSort(arguments []interface{}) (interface{}, error) { + if items, ok := toArrayNum(arguments[0]); ok { + d := sort.Float64Slice(items) + sort.Stable(d) + final := make([]interface{}, len(d)) + for i, val := range d { + final[i] = val + } + return final, nil + } + // Otherwise we're dealing with sort()'ing strings. + items, _ := toArrayStr(arguments[0]) + d := sort.StringSlice(items) + sort.Stable(d) + final := make([]interface{}, len(d)) + for i, val := range d { + final[i] = val + } + return final, nil +} +func jpfSortBy(arguments []interface{}) (interface{}, error) { + intr := arguments[0].(*treeInterpreter) + arr := arguments[1].([]interface{}) + exp := arguments[2].(expRef) + node := exp.ref + if len(arr) == 0 { + return arr, nil + } else if len(arr) == 1 { + return arr, nil + } + start, err := intr.Execute(node, arr[0]) + if err != nil { + return nil, err + } + if _, ok := start.(float64); ok { + sortable := &byExprFloat{intr, node, arr, false} + sort.Stable(sortable) + if sortable.hasError { + return nil, errors.New("error in sort_by comparison") + } + return arr, nil + } else if _, ok := start.(string); ok { + sortable := &byExprString{intr, node, arr, false} + sort.Stable(sortable) + if sortable.hasError { + return nil, errors.New("error in sort_by comparison") + } + return arr, nil + } else { + return nil, errors.New("invalid type, must be number of string") + } +} +func jpfJoin(arguments []interface{}) (interface{}, error) { + sep := arguments[0].(string) + // We can't just do arguments[1].([]string), we have to + // manually convert each item to a string. + arrayStr := []string{} + for _, item := range arguments[1].([]interface{}) { + arrayStr = append(arrayStr, item.(string)) + } + return strings.Join(arrayStr, sep), nil +} +func jpfReverse(arguments []interface{}) (interface{}, error) { + if s, ok := arguments[0].(string); ok { + r := []rune(s) + for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 { + r[i], r[j] = r[j], r[i] + } + return string(r), nil + } + items := arguments[0].([]interface{}) + length := len(items) + reversed := make([]interface{}, length) + for i, item := range items { + reversed[length-(i+1)] = item + } + return reversed, nil +} +func jpfToArray(arguments []interface{}) (interface{}, error) { + if _, ok := arguments[0].([]interface{}); ok { + return arguments[0], nil + } + return arguments[:1:1], nil +} +func jpfToString(arguments []interface{}) (interface{}, error) { + if v, ok := arguments[0].(string); ok { + return v, nil + } + result, err := json.Marshal(arguments[0]) + if err != nil { + return nil, err + } + return string(result), nil +} +func jpfToNumber(arguments []interface{}) (interface{}, error) { + arg := arguments[0] + if v, ok := arg.(float64); ok { + return v, nil + } + if v, ok := arg.(string); ok { + conv, err := strconv.ParseFloat(v, 64) + if err != nil { + return nil, nil + } + return conv, nil + } + if _, ok := arg.([]interface{}); ok { + return nil, nil + } + if _, ok := arg.(map[string]interface{}); ok { + return nil, nil + } + if arg == nil { + return nil, nil + } + if arg == true || arg == false { + return nil, nil + } + return nil, errors.New("unknown type") +} +func jpfNotNull(arguments []interface{}) (interface{}, error) { + for _, arg := range arguments { + if arg != nil { + return arg, nil + } + } + return nil, nil +} diff --git a/vendor/github.com/jmespath/go-jmespath/interpreter.go b/vendor/github.com/jmespath/go-jmespath/interpreter.go new file mode 100644 index 0000000..13c7460 --- /dev/null +++ b/vendor/github.com/jmespath/go-jmespath/interpreter.go @@ -0,0 +1,418 @@ +package jmespath + +import ( + "errors" + "reflect" + "unicode" + "unicode/utf8" +) + +/* This is a tree based interpreter. It walks the AST and directly + interprets the AST to search through a JSON document. +*/ + +type treeInterpreter struct { + fCall *functionCaller +} + +func newInterpreter() *treeInterpreter { + interpreter := treeInterpreter{} + interpreter.fCall = newFunctionCaller() + return &interpreter +} + +type expRef struct { + ref ASTNode +} + +// Execute takes an ASTNode and input data and interprets the AST directly. +// It will produce the result of applying the JMESPath expression associated +// with the ASTNode to the input data "value". +func (intr *treeInterpreter) Execute(node ASTNode, value interface{}) (interface{}, error) { + switch node.nodeType { + case ASTComparator: + left, err := intr.Execute(node.children[0], value) + if err != nil { + return nil, err + } + right, err := intr.Execute(node.children[1], value) + if err != nil { + return nil, err + } + switch node.value { + case tEQ: + return objsEqual(left, right), nil + case tNE: + return !objsEqual(left, right), nil + } + leftNum, ok := left.(float64) + if !ok { + return nil, nil + } + rightNum, ok := right.(float64) + if !ok { + return nil, nil + } + switch node.value { + case tGT: + return leftNum > rightNum, nil + case tGTE: + return leftNum >= rightNum, nil + case tLT: + return leftNum < rightNum, nil + case tLTE: + return leftNum <= rightNum, nil + } + case ASTExpRef: + return expRef{ref: node.children[0]}, nil + case ASTFunctionExpression: + resolvedArgs := []interface{}{} + for _, arg := range node.children { + current, err := intr.Execute(arg, value) + if err != nil { + return nil, err + } + resolvedArgs = append(resolvedArgs, current) + } + return intr.fCall.CallFunction(node.value.(string), resolvedArgs, intr) + case ASTField: + if m, ok := value.(map[string]interface{}); ok { + key := node.value.(string) + return m[key], nil + } + return intr.fieldFromStruct(node.value.(string), value) + case ASTFilterProjection: + left, err := intr.Execute(node.children[0], value) + if err != nil { + return nil, nil + } + sliceType, ok := left.([]interface{}) + if !ok { + if isSliceType(left) { + return intr.filterProjectionWithReflection(node, left) + } + return nil, nil + } + compareNode := node.children[2] + collected := []interface{}{} + for _, element := range sliceType { + result, err := intr.Execute(compareNode, element) + if err != nil { + return nil, err + } + if !isFalse(result) { + current, err := intr.Execute(node.children[1], element) + if err != nil { + return nil, err + } + if current != nil { + collected = append(collected, current) + } + } + } + return collected, nil + case ASTFlatten: + left, err := intr.Execute(node.children[0], value) + if err != nil { + return nil, nil + } + sliceType, ok := left.([]interface{}) + if !ok { + // If we can't type convert to []interface{}, there's + // a chance this could still work via reflection if we're + // dealing with user provided types. + if isSliceType(left) { + return intr.flattenWithReflection(left) + } + return nil, nil + } + flattened := []interface{}{} + for _, element := range sliceType { + if elementSlice, ok := element.([]interface{}); ok { + flattened = append(flattened, elementSlice...) + } else if isSliceType(element) { + reflectFlat := []interface{}{} + v := reflect.ValueOf(element) + for i := 0; i < v.Len(); i++ { + reflectFlat = append(reflectFlat, v.Index(i).Interface()) + } + flattened = append(flattened, reflectFlat...) + } else { + flattened = append(flattened, element) + } + } + return flattened, nil + case ASTIdentity, ASTCurrentNode: + return value, nil + case ASTIndex: + if sliceType, ok := value.([]interface{}); ok { + index := node.value.(int) + if index < 0 { + index += len(sliceType) + } + if index < len(sliceType) && index >= 0 { + return sliceType[index], nil + } + return nil, nil + } + // Otherwise try via reflection. + rv := reflect.ValueOf(value) + if rv.Kind() == reflect.Slice { + index := node.value.(int) + if index < 0 { + index += rv.Len() + } + if index < rv.Len() && index >= 0 { + v := rv.Index(index) + return v.Interface(), nil + } + } + return nil, nil + case ASTKeyValPair: + return intr.Execute(node.children[0], value) + case ASTLiteral: + return node.value, nil + case ASTMultiSelectHash: + if value == nil { + return nil, nil + } + collected := make(map[string]interface{}) + for _, child := range node.children { + current, err := intr.Execute(child, value) + if err != nil { + return nil, err + } + key := child.value.(string) + collected[key] = current + } + return collected, nil + case ASTMultiSelectList: + if value == nil { + return nil, nil + } + collected := []interface{}{} + for _, child := range node.children { + current, err := intr.Execute(child, value) + if err != nil { + return nil, err + } + collected = append(collected, current) + } + return collected, nil + case ASTOrExpression: + matched, err := intr.Execute(node.children[0], value) + if err != nil { + return nil, err + } + if isFalse(matched) { + matched, err = intr.Execute(node.children[1], value) + if err != nil { + return nil, err + } + } + return matched, nil + case ASTAndExpression: + matched, err := intr.Execute(node.children[0], value) + if err != nil { + return nil, err + } + if isFalse(matched) { + return matched, nil + } + return intr.Execute(node.children[1], value) + case ASTNotExpression: + matched, err := intr.Execute(node.children[0], value) + if err != nil { + return nil, err + } + if isFalse(matched) { + return true, nil + } + return false, nil + case ASTPipe: + result := value + var err error + for _, child := range node.children { + result, err = intr.Execute(child, result) + if err != nil { + return nil, err + } + } + return result, nil + case ASTProjection: + left, err := intr.Execute(node.children[0], value) + if err != nil { + return nil, err + } + sliceType, ok := left.([]interface{}) + if !ok { + if isSliceType(left) { + return intr.projectWithReflection(node, left) + } + return nil, nil + } + collected := []interface{}{} + var current interface{} + for _, element := range sliceType { + current, err = intr.Execute(node.children[1], element) + if err != nil { + return nil, err + } + if current != nil { + collected = append(collected, current) + } + } + return collected, nil + case ASTSubexpression, ASTIndexExpression: + left, err := intr.Execute(node.children[0], value) + if err != nil { + return nil, err + } + return intr.Execute(node.children[1], left) + case ASTSlice: + sliceType, ok := value.([]interface{}) + if !ok { + if isSliceType(value) { + return intr.sliceWithReflection(node, value) + } + return nil, nil + } + parts := node.value.([]*int) + sliceParams := make([]sliceParam, 3) + for i, part := range parts { + if part != nil { + sliceParams[i].Specified = true + sliceParams[i].N = *part + } + } + return slice(sliceType, sliceParams) + case ASTValueProjection: + left, err := intr.Execute(node.children[0], value) + if err != nil { + return nil, nil + } + mapType, ok := left.(map[string]interface{}) + if !ok { + return nil, nil + } + values := make([]interface{}, len(mapType)) + for _, value := range mapType { + values = append(values, value) + } + collected := []interface{}{} + for _, element := range values { + current, err := intr.Execute(node.children[1], element) + if err != nil { + return nil, err + } + if current != nil { + collected = append(collected, current) + } + } + return collected, nil + } + return nil, errors.New("Unknown AST node: " + node.nodeType.String()) +} + +func (intr *treeInterpreter) fieldFromStruct(key string, value interface{}) (interface{}, error) { + rv := reflect.ValueOf(value) + first, n := utf8.DecodeRuneInString(key) + fieldName := string(unicode.ToUpper(first)) + key[n:] + if rv.Kind() == reflect.Struct { + v := rv.FieldByName(fieldName) + if !v.IsValid() { + return nil, nil + } + return v.Interface(), nil + } else if rv.Kind() == reflect.Ptr { + // Handle multiple levels of indirection? + if rv.IsNil() { + return nil, nil + } + rv = rv.Elem() + v := rv.FieldByName(fieldName) + if !v.IsValid() { + return nil, nil + } + return v.Interface(), nil + } + return nil, nil +} + +func (intr *treeInterpreter) flattenWithReflection(value interface{}) (interface{}, error) { + v := reflect.ValueOf(value) + flattened := []interface{}{} + for i := 0; i < v.Len(); i++ { + element := v.Index(i).Interface() + if reflect.TypeOf(element).Kind() == reflect.Slice { + // Then insert the contents of the element + // slice into the flattened slice, + // i.e flattened = append(flattened, mySlice...) + elementV := reflect.ValueOf(element) + for j := 0; j < elementV.Len(); j++ { + flattened = append( + flattened, elementV.Index(j).Interface()) + } + } else { + flattened = append(flattened, element) + } + } + return flattened, nil +} + +func (intr *treeInterpreter) sliceWithReflection(node ASTNode, value interface{}) (interface{}, error) { + v := reflect.ValueOf(value) + parts := node.value.([]*int) + sliceParams := make([]sliceParam, 3) + for i, part := range parts { + if part != nil { + sliceParams[i].Specified = true + sliceParams[i].N = *part + } + } + final := []interface{}{} + for i := 0; i < v.Len(); i++ { + element := v.Index(i).Interface() + final = append(final, element) + } + return slice(final, sliceParams) +} + +func (intr *treeInterpreter) filterProjectionWithReflection(node ASTNode, value interface{}) (interface{}, error) { + compareNode := node.children[2] + collected := []interface{}{} + v := reflect.ValueOf(value) + for i := 0; i < v.Len(); i++ { + element := v.Index(i).Interface() + result, err := intr.Execute(compareNode, element) + if err != nil { + return nil, err + } + if !isFalse(result) { + current, err := intr.Execute(node.children[1], element) + if err != nil { + return nil, err + } + if current != nil { + collected = append(collected, current) + } + } + } + return collected, nil +} + +func (intr *treeInterpreter) projectWithReflection(node ASTNode, value interface{}) (interface{}, error) { + collected := []interface{}{} + v := reflect.ValueOf(value) + for i := 0; i < v.Len(); i++ { + element := v.Index(i).Interface() + result, err := intr.Execute(node.children[1], element) + if err != nil { + return nil, err + } + if result != nil { + collected = append(collected, result) + } + } + return collected, nil +} diff --git a/vendor/github.com/jmespath/go-jmespath/lexer.go b/vendor/github.com/jmespath/go-jmespath/lexer.go new file mode 100644 index 0000000..817900c --- /dev/null +++ b/vendor/github.com/jmespath/go-jmespath/lexer.go @@ -0,0 +1,420 @@ +package jmespath + +import ( + "bytes" + "encoding/json" + "fmt" + "strconv" + "strings" + "unicode/utf8" +) + +type token struct { + tokenType tokType + value string + position int + length int +} + +type tokType int + +const eof = -1 + +// Lexer contains information about the expression being tokenized. +type Lexer struct { + expression string // The expression provided by the user. + currentPos int // The current position in the string. + lastWidth int // The width of the current rune. This + buf bytes.Buffer // Internal buffer used for building up values. +} + +// SyntaxError is the main error used whenever a lexing or parsing error occurs. +type SyntaxError struct { + msg string // Error message displayed to user + Expression string // Expression that generated a SyntaxError + Offset int // The location in the string where the error occurred +} + +func (e SyntaxError) Error() string { + // In the future, it would be good to underline the specific + // location where the error occurred. + return "SyntaxError: " + e.msg +} + +// HighlightLocation will show where the syntax error occurred. +// It will place a "^" character on a line below the expression +// at the point where the syntax error occurred. +func (e SyntaxError) HighlightLocation() string { + return e.Expression + "\n" + strings.Repeat(" ", e.Offset) + "^" +} + +//go:generate stringer -type=tokType +const ( + tUnknown tokType = iota + tStar + tDot + tFilter + tFlatten + tLparen + tRparen + tLbracket + tRbracket + tLbrace + tRbrace + tOr + tPipe + tNumber + tUnquotedIdentifier + tQuotedIdentifier + tComma + tColon + tLT + tLTE + tGT + tGTE + tEQ + tNE + tJSONLiteral + tStringLiteral + tCurrent + tExpref + tAnd + tNot + tEOF +) + +var basicTokens = map[rune]tokType{ + '.': tDot, + '*': tStar, + ',': tComma, + ':': tColon, + '{': tLbrace, + '}': tRbrace, + ']': tRbracket, // tLbracket not included because it could be "[]" + '(': tLparen, + ')': tRparen, + '@': tCurrent, +} + +// Bit mask for [a-zA-Z_] shifted down 64 bits to fit in a single uint64. +// When using this bitmask just be sure to shift the rune down 64 bits +// before checking against identifierStartBits. +const identifierStartBits uint64 = 576460745995190270 + +// Bit mask for [a-zA-Z0-9], 128 bits -> 2 uint64s. +var identifierTrailingBits = [2]uint64{287948901175001088, 576460745995190270} + +var whiteSpace = map[rune]bool{ + ' ': true, '\t': true, '\n': true, '\r': true, +} + +func (t token) String() string { + return fmt.Sprintf("Token{%+v, %s, %d, %d}", + t.tokenType, t.value, t.position, t.length) +} + +// NewLexer creates a new JMESPath lexer. +func NewLexer() *Lexer { + lexer := Lexer{} + return &lexer +} + +func (lexer *Lexer) next() rune { + if lexer.currentPos >= len(lexer.expression) { + lexer.lastWidth = 0 + return eof + } + r, w := utf8.DecodeRuneInString(lexer.expression[lexer.currentPos:]) + lexer.lastWidth = w + lexer.currentPos += w + return r +} + +func (lexer *Lexer) back() { + lexer.currentPos -= lexer.lastWidth +} + +func (lexer *Lexer) peek() rune { + t := lexer.next() + lexer.back() + return t +} + +// tokenize takes an expression and returns corresponding tokens. +func (lexer *Lexer) tokenize(expression string) ([]token, error) { + var tokens []token + lexer.expression = expression + lexer.currentPos = 0 + lexer.lastWidth = 0 +loop: + for { + r := lexer.next() + if identifierStartBits&(1<<(uint64(r)-64)) > 0 { + t := lexer.consumeUnquotedIdentifier() + tokens = append(tokens, t) + } else if val, ok := basicTokens[r]; ok { + // Basic single char token. + t := token{ + tokenType: val, + value: string(r), + position: lexer.currentPos - lexer.lastWidth, + length: 1, + } + tokens = append(tokens, t) + } else if r == '-' || (r >= '0' && r <= '9') { + t := lexer.consumeNumber() + tokens = append(tokens, t) + } else if r == '[' { + t := lexer.consumeLBracket() + tokens = append(tokens, t) + } else if r == '"' { + t, err := lexer.consumeQuotedIdentifier() + if err != nil { + return tokens, err + } + tokens = append(tokens, t) + } else if r == '\'' { + t, err := lexer.consumeRawStringLiteral() + if err != nil { + return tokens, err + } + tokens = append(tokens, t) + } else if r == '`' { + t, err := lexer.consumeLiteral() + if err != nil { + return tokens, err + } + tokens = append(tokens, t) + } else if r == '|' { + t := lexer.matchOrElse(r, '|', tOr, tPipe) + tokens = append(tokens, t) + } else if r == '<' { + t := lexer.matchOrElse(r, '=', tLTE, tLT) + tokens = append(tokens, t) + } else if r == '>' { + t := lexer.matchOrElse(r, '=', tGTE, tGT) + tokens = append(tokens, t) + } else if r == '!' { + t := lexer.matchOrElse(r, '=', tNE, tNot) + tokens = append(tokens, t) + } else if r == '=' { + t := lexer.matchOrElse(r, '=', tEQ, tUnknown) + tokens = append(tokens, t) + } else if r == '&' { + t := lexer.matchOrElse(r, '&', tAnd, tExpref) + tokens = append(tokens, t) + } else if r == eof { + break loop + } else if _, ok := whiteSpace[r]; ok { + // Ignore whitespace + } else { + return tokens, lexer.syntaxError(fmt.Sprintf("Unknown char: %s", strconv.QuoteRuneToASCII(r))) + } + } + tokens = append(tokens, token{tEOF, "", len(lexer.expression), 0}) + return tokens, nil +} + +// Consume characters until the ending rune "r" is reached. +// If the end of the expression is reached before seeing the +// terminating rune "r", then an error is returned. +// If no error occurs then the matching substring is returned. +// The returned string will not include the ending rune. +func (lexer *Lexer) consumeUntil(end rune) (string, error) { + start := lexer.currentPos + current := lexer.next() + for current != end && current != eof { + if current == '\\' && lexer.peek() != eof { + lexer.next() + } + current = lexer.next() + } + if lexer.lastWidth == 0 { + // Then we hit an EOF so we never reached the closing + // delimiter. + return "", SyntaxError{ + msg: "Unclosed delimiter: " + string(end), + Expression: lexer.expression, + Offset: len(lexer.expression), + } + } + return lexer.expression[start : lexer.currentPos-lexer.lastWidth], nil +} + +func (lexer *Lexer) consumeLiteral() (token, error) { + start := lexer.currentPos + value, err := lexer.consumeUntil('`') + if err != nil { + return token{}, err + } + value = strings.Replace(value, "\\`", "`", -1) + return token{ + tokenType: tJSONLiteral, + value: value, + position: start, + length: len(value), + }, nil +} + +func (lexer *Lexer) consumeRawStringLiteral() (token, error) { + start := lexer.currentPos + currentIndex := start + current := lexer.next() + for current != '\'' && lexer.peek() != eof { + if current == '\\' && lexer.peek() == '\'' { + chunk := lexer.expression[currentIndex : lexer.currentPos-1] + lexer.buf.WriteString(chunk) + lexer.buf.WriteString("'") + lexer.next() + currentIndex = lexer.currentPos + } + current = lexer.next() + } + if lexer.lastWidth == 0 { + // Then we hit an EOF so we never reached the closing + // delimiter. + return token{}, SyntaxError{ + msg: "Unclosed delimiter: '", + Expression: lexer.expression, + Offset: len(lexer.expression), + } + } + if currentIndex < lexer.currentPos { + lexer.buf.WriteString(lexer.expression[currentIndex : lexer.currentPos-1]) + } + value := lexer.buf.String() + // Reset the buffer so it can reused again. + lexer.buf.Reset() + return token{ + tokenType: tStringLiteral, + value: value, + position: start, + length: len(value), + }, nil +} + +func (lexer *Lexer) syntaxError(msg string) SyntaxError { + return SyntaxError{ + msg: msg, + Expression: lexer.expression, + Offset: lexer.currentPos - 1, + } +} + +// Checks for a two char token, otherwise matches a single character +// token. This is used whenever a two char token overlaps a single +// char token, e.g. "||" -> tPipe, "|" -> tOr. +func (lexer *Lexer) matchOrElse(first rune, second rune, matchedType tokType, singleCharType tokType) token { + start := lexer.currentPos - lexer.lastWidth + nextRune := lexer.next() + var t token + if nextRune == second { + t = token{ + tokenType: matchedType, + value: string(first) + string(second), + position: start, + length: 2, + } + } else { + lexer.back() + t = token{ + tokenType: singleCharType, + value: string(first), + position: start, + length: 1, + } + } + return t +} + +func (lexer *Lexer) consumeLBracket() token { + // There's three options here: + // 1. A filter expression "[?" + // 2. A flatten operator "[]" + // 3. A bare rbracket "[" + start := lexer.currentPos - lexer.lastWidth + nextRune := lexer.next() + var t token + if nextRune == '?' { + t = token{ + tokenType: tFilter, + value: "[?", + position: start, + length: 2, + } + } else if nextRune == ']' { + t = token{ + tokenType: tFlatten, + value: "[]", + position: start, + length: 2, + } + } else { + t = token{ + tokenType: tLbracket, + value: "[", + position: start, + length: 1, + } + lexer.back() + } + return t +} + +func (lexer *Lexer) consumeQuotedIdentifier() (token, error) { + start := lexer.currentPos + value, err := lexer.consumeUntil('"') + if err != nil { + return token{}, err + } + var decoded string + asJSON := []byte("\"" + value + "\"") + if err := json.Unmarshal([]byte(asJSON), &decoded); err != nil { + return token{}, err + } + return token{ + tokenType: tQuotedIdentifier, + value: decoded, + position: start - 1, + length: len(decoded), + }, nil +} + +func (lexer *Lexer) consumeUnquotedIdentifier() token { + // Consume runes until we reach the end of an unquoted + // identifier. + start := lexer.currentPos - lexer.lastWidth + for { + r := lexer.next() + if r < 0 || r > 128 || identifierTrailingBits[uint64(r)/64]&(1<<(uint64(r)%64)) == 0 { + lexer.back() + break + } + } + value := lexer.expression[start:lexer.currentPos] + return token{ + tokenType: tUnquotedIdentifier, + value: value, + position: start, + length: lexer.currentPos - start, + } +} + +func (lexer *Lexer) consumeNumber() token { + // Consume runes until we reach something that's not a number. + start := lexer.currentPos - lexer.lastWidth + for { + r := lexer.next() + if r < '0' || r > '9' { + lexer.back() + break + } + } + value := lexer.expression[start:lexer.currentPos] + return token{ + tokenType: tNumber, + value: value, + position: start, + length: lexer.currentPos - start, + } +} diff --git a/vendor/github.com/jmespath/go-jmespath/parser.go b/vendor/github.com/jmespath/go-jmespath/parser.go new file mode 100644 index 0000000..1240a17 --- /dev/null +++ b/vendor/github.com/jmespath/go-jmespath/parser.go @@ -0,0 +1,603 @@ +package jmespath + +import ( + "encoding/json" + "fmt" + "strconv" + "strings" +) + +type astNodeType int + +//go:generate stringer -type astNodeType +const ( + ASTEmpty astNodeType = iota + ASTComparator + ASTCurrentNode + ASTExpRef + ASTFunctionExpression + ASTField + ASTFilterProjection + ASTFlatten + ASTIdentity + ASTIndex + ASTIndexExpression + ASTKeyValPair + ASTLiteral + ASTMultiSelectHash + ASTMultiSelectList + ASTOrExpression + ASTAndExpression + ASTNotExpression + ASTPipe + ASTProjection + ASTSubexpression + ASTSlice + ASTValueProjection +) + +// ASTNode represents the abstract syntax tree of a JMESPath expression. +type ASTNode struct { + nodeType astNodeType + value interface{} + children []ASTNode +} + +func (node ASTNode) String() string { + return node.PrettyPrint(0) +} + +// PrettyPrint will pretty print the parsed AST. +// The AST is an implementation detail and this pretty print +// function is provided as a convenience method to help with +// debugging. You should not rely on its output as the internal +// structure of the AST may change at any time. +func (node ASTNode) PrettyPrint(indent int) string { + spaces := strings.Repeat(" ", indent) + output := fmt.Sprintf("%s%s {\n", spaces, node.nodeType) + nextIndent := indent + 2 + if node.value != nil { + if converted, ok := node.value.(fmt.Stringer); ok { + // Account for things like comparator nodes + // that are enums with a String() method. + output += fmt.Sprintf("%svalue: %s\n", strings.Repeat(" ", nextIndent), converted.String()) + } else { + output += fmt.Sprintf("%svalue: %#v\n", strings.Repeat(" ", nextIndent), node.value) + } + } + lastIndex := len(node.children) + if lastIndex > 0 { + output += fmt.Sprintf("%schildren: {\n", strings.Repeat(" ", nextIndent)) + childIndent := nextIndent + 2 + for _, elem := range node.children { + output += elem.PrettyPrint(childIndent) + } + } + output += fmt.Sprintf("%s}\n", spaces) + return output +} + +var bindingPowers = map[tokType]int{ + tEOF: 0, + tUnquotedIdentifier: 0, + tQuotedIdentifier: 0, + tRbracket: 0, + tRparen: 0, + tComma: 0, + tRbrace: 0, + tNumber: 0, + tCurrent: 0, + tExpref: 0, + tColon: 0, + tPipe: 1, + tOr: 2, + tAnd: 3, + tEQ: 5, + tLT: 5, + tLTE: 5, + tGT: 5, + tGTE: 5, + tNE: 5, + tFlatten: 9, + tStar: 20, + tFilter: 21, + tDot: 40, + tNot: 45, + tLbrace: 50, + tLbracket: 55, + tLparen: 60, +} + +// Parser holds state about the current expression being parsed. +type Parser struct { + expression string + tokens []token + index int +} + +// NewParser creates a new JMESPath parser. +func NewParser() *Parser { + p := Parser{} + return &p +} + +// Parse will compile a JMESPath expression. +func (p *Parser) Parse(expression string) (ASTNode, error) { + lexer := NewLexer() + p.expression = expression + p.index = 0 + tokens, err := lexer.tokenize(expression) + if err != nil { + return ASTNode{}, err + } + p.tokens = tokens + parsed, err := p.parseExpression(0) + if err != nil { + return ASTNode{}, err + } + if p.current() != tEOF { + return ASTNode{}, p.syntaxError(fmt.Sprintf( + "Unexpected token at the end of the expresssion: %s", p.current())) + } + return parsed, nil +} + +func (p *Parser) parseExpression(bindingPower int) (ASTNode, error) { + var err error + leftToken := p.lookaheadToken(0) + p.advance() + leftNode, err := p.nud(leftToken) + if err != nil { + return ASTNode{}, err + } + currentToken := p.current() + for bindingPower < bindingPowers[currentToken] { + p.advance() + leftNode, err = p.led(currentToken, leftNode) + if err != nil { + return ASTNode{}, err + } + currentToken = p.current() + } + return leftNode, nil +} + +func (p *Parser) parseIndexExpression() (ASTNode, error) { + if p.lookahead(0) == tColon || p.lookahead(1) == tColon { + return p.parseSliceExpression() + } + indexStr := p.lookaheadToken(0).value + parsedInt, err := strconv.Atoi(indexStr) + if err != nil { + return ASTNode{}, err + } + indexNode := ASTNode{nodeType: ASTIndex, value: parsedInt} + p.advance() + if err := p.match(tRbracket); err != nil { + return ASTNode{}, err + } + return indexNode, nil +} + +func (p *Parser) parseSliceExpression() (ASTNode, error) { + parts := []*int{nil, nil, nil} + index := 0 + current := p.current() + for current != tRbracket && index < 3 { + if current == tColon { + index++ + p.advance() + } else if current == tNumber { + parsedInt, err := strconv.Atoi(p.lookaheadToken(0).value) + if err != nil { + return ASTNode{}, err + } + parts[index] = &parsedInt + p.advance() + } else { + return ASTNode{}, p.syntaxError( + "Expected tColon or tNumber" + ", received: " + p.current().String()) + } + current = p.current() + } + if err := p.match(tRbracket); err != nil { + return ASTNode{}, err + } + return ASTNode{ + nodeType: ASTSlice, + value: parts, + }, nil +} + +func (p *Parser) match(tokenType tokType) error { + if p.current() == tokenType { + p.advance() + return nil + } + return p.syntaxError("Expected " + tokenType.String() + ", received: " + p.current().String()) +} + +func (p *Parser) led(tokenType tokType, node ASTNode) (ASTNode, error) { + switch tokenType { + case tDot: + if p.current() != tStar { + right, err := p.parseDotRHS(bindingPowers[tDot]) + return ASTNode{ + nodeType: ASTSubexpression, + children: []ASTNode{node, right}, + }, err + } + p.advance() + right, err := p.parseProjectionRHS(bindingPowers[tDot]) + return ASTNode{ + nodeType: ASTValueProjection, + children: []ASTNode{node, right}, + }, err + case tPipe: + right, err := p.parseExpression(bindingPowers[tPipe]) + return ASTNode{nodeType: ASTPipe, children: []ASTNode{node, right}}, err + case tOr: + right, err := p.parseExpression(bindingPowers[tOr]) + return ASTNode{nodeType: ASTOrExpression, children: []ASTNode{node, right}}, err + case tAnd: + right, err := p.parseExpression(bindingPowers[tAnd]) + return ASTNode{nodeType: ASTAndExpression, children: []ASTNode{node, right}}, err + case tLparen: + name := node.value + var args []ASTNode + for p.current() != tRparen { + expression, err := p.parseExpression(0) + if err != nil { + return ASTNode{}, err + } + if p.current() == tComma { + if err := p.match(tComma); err != nil { + return ASTNode{}, err + } + } + args = append(args, expression) + } + if err := p.match(tRparen); err != nil { + return ASTNode{}, err + } + return ASTNode{ + nodeType: ASTFunctionExpression, + value: name, + children: args, + }, nil + case tFilter: + return p.parseFilter(node) + case tFlatten: + left := ASTNode{nodeType: ASTFlatten, children: []ASTNode{node}} + right, err := p.parseProjectionRHS(bindingPowers[tFlatten]) + return ASTNode{ + nodeType: ASTProjection, + children: []ASTNode{left, right}, + }, err + case tEQ, tNE, tGT, tGTE, tLT, tLTE: + right, err := p.parseExpression(bindingPowers[tokenType]) + if err != nil { + return ASTNode{}, err + } + return ASTNode{ + nodeType: ASTComparator, + value: tokenType, + children: []ASTNode{node, right}, + }, nil + case tLbracket: + tokenType := p.current() + var right ASTNode + var err error + if tokenType == tNumber || tokenType == tColon { + right, err = p.parseIndexExpression() + if err != nil { + return ASTNode{}, err + } + return p.projectIfSlice(node, right) + } + // Otherwise this is a projection. + if err := p.match(tStar); err != nil { + return ASTNode{}, err + } + if err := p.match(tRbracket); err != nil { + return ASTNode{}, err + } + right, err = p.parseProjectionRHS(bindingPowers[tStar]) + if err != nil { + return ASTNode{}, err + } + return ASTNode{ + nodeType: ASTProjection, + children: []ASTNode{node, right}, + }, nil + } + return ASTNode{}, p.syntaxError("Unexpected token: " + tokenType.String()) +} + +func (p *Parser) nud(token token) (ASTNode, error) { + switch token.tokenType { + case tJSONLiteral: + var parsed interface{} + err := json.Unmarshal([]byte(token.value), &parsed) + if err != nil { + return ASTNode{}, err + } + return ASTNode{nodeType: ASTLiteral, value: parsed}, nil + case tStringLiteral: + return ASTNode{nodeType: ASTLiteral, value: token.value}, nil + case tUnquotedIdentifier: + return ASTNode{ + nodeType: ASTField, + value: token.value, + }, nil + case tQuotedIdentifier: + node := ASTNode{nodeType: ASTField, value: token.value} + if p.current() == tLparen { + return ASTNode{}, p.syntaxErrorToken("Can't have quoted identifier as function name.", token) + } + return node, nil + case tStar: + left := ASTNode{nodeType: ASTIdentity} + var right ASTNode + var err error + if p.current() == tRbracket { + right = ASTNode{nodeType: ASTIdentity} + } else { + right, err = p.parseProjectionRHS(bindingPowers[tStar]) + } + return ASTNode{nodeType: ASTValueProjection, children: []ASTNode{left, right}}, err + case tFilter: + return p.parseFilter(ASTNode{nodeType: ASTIdentity}) + case tLbrace: + return p.parseMultiSelectHash() + case tFlatten: + left := ASTNode{ + nodeType: ASTFlatten, + children: []ASTNode{{nodeType: ASTIdentity}}, + } + right, err := p.parseProjectionRHS(bindingPowers[tFlatten]) + if err != nil { + return ASTNode{}, err + } + return ASTNode{nodeType: ASTProjection, children: []ASTNode{left, right}}, nil + case tLbracket: + tokenType := p.current() + //var right ASTNode + if tokenType == tNumber || tokenType == tColon { + right, err := p.parseIndexExpression() + if err != nil { + return ASTNode{}, nil + } + return p.projectIfSlice(ASTNode{nodeType: ASTIdentity}, right) + } else if tokenType == tStar && p.lookahead(1) == tRbracket { + p.advance() + p.advance() + right, err := p.parseProjectionRHS(bindingPowers[tStar]) + if err != nil { + return ASTNode{}, err + } + return ASTNode{ + nodeType: ASTProjection, + children: []ASTNode{{nodeType: ASTIdentity}, right}, + }, nil + } else { + return p.parseMultiSelectList() + } + case tCurrent: + return ASTNode{nodeType: ASTCurrentNode}, nil + case tExpref: + expression, err := p.parseExpression(bindingPowers[tExpref]) + if err != nil { + return ASTNode{}, err + } + return ASTNode{nodeType: ASTExpRef, children: []ASTNode{expression}}, nil + case tNot: + expression, err := p.parseExpression(bindingPowers[tNot]) + if err != nil { + return ASTNode{}, err + } + return ASTNode{nodeType: ASTNotExpression, children: []ASTNode{expression}}, nil + case tLparen: + expression, err := p.parseExpression(0) + if err != nil { + return ASTNode{}, err + } + if err := p.match(tRparen); err != nil { + return ASTNode{}, err + } + return expression, nil + case tEOF: + return ASTNode{}, p.syntaxErrorToken("Incomplete expression", token) + } + + return ASTNode{}, p.syntaxErrorToken("Invalid token: "+token.tokenType.String(), token) +} + +func (p *Parser) parseMultiSelectList() (ASTNode, error) { + var expressions []ASTNode + for { + expression, err := p.parseExpression(0) + if err != nil { + return ASTNode{}, err + } + expressions = append(expressions, expression) + if p.current() == tRbracket { + break + } + err = p.match(tComma) + if err != nil { + return ASTNode{}, err + } + } + err := p.match(tRbracket) + if err != nil { + return ASTNode{}, err + } + return ASTNode{ + nodeType: ASTMultiSelectList, + children: expressions, + }, nil +} + +func (p *Parser) parseMultiSelectHash() (ASTNode, error) { + var children []ASTNode + for { + keyToken := p.lookaheadToken(0) + if err := p.match(tUnquotedIdentifier); err != nil { + if err := p.match(tQuotedIdentifier); err != nil { + return ASTNode{}, p.syntaxError("Expected tQuotedIdentifier or tUnquotedIdentifier") + } + } + keyName := keyToken.value + err := p.match(tColon) + if err != nil { + return ASTNode{}, err + } + value, err := p.parseExpression(0) + if err != nil { + return ASTNode{}, err + } + node := ASTNode{ + nodeType: ASTKeyValPair, + value: keyName, + children: []ASTNode{value}, + } + children = append(children, node) + if p.current() == tComma { + err := p.match(tComma) + if err != nil { + return ASTNode{}, nil + } + } else if p.current() == tRbrace { + err := p.match(tRbrace) + if err != nil { + return ASTNode{}, nil + } + break + } + } + return ASTNode{ + nodeType: ASTMultiSelectHash, + children: children, + }, nil +} + +func (p *Parser) projectIfSlice(left ASTNode, right ASTNode) (ASTNode, error) { + indexExpr := ASTNode{ + nodeType: ASTIndexExpression, + children: []ASTNode{left, right}, + } + if right.nodeType == ASTSlice { + right, err := p.parseProjectionRHS(bindingPowers[tStar]) + return ASTNode{ + nodeType: ASTProjection, + children: []ASTNode{indexExpr, right}, + }, err + } + return indexExpr, nil +} +func (p *Parser) parseFilter(node ASTNode) (ASTNode, error) { + var right, condition ASTNode + var err error + condition, err = p.parseExpression(0) + if err != nil { + return ASTNode{}, err + } + if err := p.match(tRbracket); err != nil { + return ASTNode{}, err + } + if p.current() == tFlatten { + right = ASTNode{nodeType: ASTIdentity} + } else { + right, err = p.parseProjectionRHS(bindingPowers[tFilter]) + if err != nil { + return ASTNode{}, err + } + } + + return ASTNode{ + nodeType: ASTFilterProjection, + children: []ASTNode{node, right, condition}, + }, nil +} + +func (p *Parser) parseDotRHS(bindingPower int) (ASTNode, error) { + lookahead := p.current() + if tokensOneOf([]tokType{tQuotedIdentifier, tUnquotedIdentifier, tStar}, lookahead) { + return p.parseExpression(bindingPower) + } else if lookahead == tLbracket { + if err := p.match(tLbracket); err != nil { + return ASTNode{}, err + } + return p.parseMultiSelectList() + } else if lookahead == tLbrace { + if err := p.match(tLbrace); err != nil { + return ASTNode{}, err + } + return p.parseMultiSelectHash() + } + return ASTNode{}, p.syntaxError("Expected identifier, lbracket, or lbrace") +} + +func (p *Parser) parseProjectionRHS(bindingPower int) (ASTNode, error) { + current := p.current() + if bindingPowers[current] < 10 { + return ASTNode{nodeType: ASTIdentity}, nil + } else if current == tLbracket { + return p.parseExpression(bindingPower) + } else if current == tFilter { + return p.parseExpression(bindingPower) + } else if current == tDot { + err := p.match(tDot) + if err != nil { + return ASTNode{}, err + } + return p.parseDotRHS(bindingPower) + } else { + return ASTNode{}, p.syntaxError("Error") + } +} + +func (p *Parser) lookahead(number int) tokType { + return p.lookaheadToken(number).tokenType +} + +func (p *Parser) current() tokType { + return p.lookahead(0) +} + +func (p *Parser) lookaheadToken(number int) token { + return p.tokens[p.index+number] +} + +func (p *Parser) advance() { + p.index++ +} + +func tokensOneOf(elements []tokType, token tokType) bool { + for _, elem := range elements { + if elem == token { + return true + } + } + return false +} + +func (p *Parser) syntaxError(msg string) SyntaxError { + return SyntaxError{ + msg: msg, + Expression: p.expression, + Offset: p.lookaheadToken(0).position, + } +} + +// Create a SyntaxError based on the provided token. +// This differs from syntaxError() which creates a SyntaxError +// based on the current lookahead token. +func (p *Parser) syntaxErrorToken(msg string, t token) SyntaxError { + return SyntaxError{ + msg: msg, + Expression: p.expression, + Offset: t.position, + } +} diff --git a/vendor/github.com/jmespath/go-jmespath/toktype_string.go b/vendor/github.com/jmespath/go-jmespath/toktype_string.go new file mode 100644 index 0000000..dae79cb --- /dev/null +++ b/vendor/github.com/jmespath/go-jmespath/toktype_string.go @@ -0,0 +1,16 @@ +// generated by stringer -type=tokType; DO NOT EDIT + +package jmespath + +import "fmt" + +const _tokType_name = "tUnknowntStartDottFiltertFlattentLparentRparentLbrackettRbrackettLbracetRbracetOrtPipetNumbertUnquotedIdentifiertQuotedIdentifiertCommatColontLTtLTEtGTtGTEtEQtNEtJSONLiteraltStringLiteraltCurrenttExpreftAndtNottEOF" + +var _tokType_index = [...]uint8{0, 8, 13, 17, 24, 32, 39, 46, 55, 64, 71, 78, 81, 86, 93, 112, 129, 135, 141, 144, 148, 151, 155, 158, 161, 173, 187, 195, 202, 206, 210, 214} + +func (i tokType) String() string { + if i < 0 || i >= tokType(len(_tokType_index)-1) { + return fmt.Sprintf("tokType(%d)", i) + } + return _tokType_name[_tokType_index[i]:_tokType_index[i+1]] +} diff --git a/vendor/github.com/jmespath/go-jmespath/util.go b/vendor/github.com/jmespath/go-jmespath/util.go new file mode 100644 index 0000000..ddc1b7d --- /dev/null +++ b/vendor/github.com/jmespath/go-jmespath/util.go @@ -0,0 +1,185 @@ +package jmespath + +import ( + "errors" + "reflect" +) + +// IsFalse determines if an object is false based on the JMESPath spec. +// JMESPath defines false values to be any of: +// - An empty string array, or hash. +// - The boolean value false. +// - nil +func isFalse(value interface{}) bool { + switch v := value.(type) { + case bool: + return !v + case []interface{}: + return len(v) == 0 + case map[string]interface{}: + return len(v) == 0 + case string: + return len(v) == 0 + case nil: + return true + } + // Try the reflection cases before returning false. + rv := reflect.ValueOf(value) + switch rv.Kind() { + case reflect.Struct: + // A struct type will never be false, even if + // all of its values are the zero type. + return false + case reflect.Slice, reflect.Map: + return rv.Len() == 0 + case reflect.Ptr: + if rv.IsNil() { + return true + } + // If it's a pointer type, we'll try to deref the pointer + // and evaluate the pointer value for isFalse. + element := rv.Elem() + return isFalse(element.Interface()) + } + return false +} + +// ObjsEqual is a generic object equality check. +// It will take two arbitrary objects and recursively determine +// if they are equal. +func objsEqual(left interface{}, right interface{}) bool { + return reflect.DeepEqual(left, right) +} + +// SliceParam refers to a single part of a slice. +// A slice consists of a start, a stop, and a step, similar to +// python slices. +type sliceParam struct { + N int + Specified bool +} + +// Slice supports [start:stop:step] style slicing that's supported in JMESPath. +func slice(slice []interface{}, parts []sliceParam) ([]interface{}, error) { + computed, err := computeSliceParams(len(slice), parts) + if err != nil { + return nil, err + } + start, stop, step := computed[0], computed[1], computed[2] + result := []interface{}{} + if step > 0 { + for i := start; i < stop; i += step { + result = append(result, slice[i]) + } + } else { + for i := start; i > stop; i += step { + result = append(result, slice[i]) + } + } + return result, nil +} + +func computeSliceParams(length int, parts []sliceParam) ([]int, error) { + var start, stop, step int + if !parts[2].Specified { + step = 1 + } else if parts[2].N == 0 { + return nil, errors.New("Invalid slice, step cannot be 0") + } else { + step = parts[2].N + } + var stepValueNegative bool + if step < 0 { + stepValueNegative = true + } else { + stepValueNegative = false + } + + if !parts[0].Specified { + if stepValueNegative { + start = length - 1 + } else { + start = 0 + } + } else { + start = capSlice(length, parts[0].N, step) + } + + if !parts[1].Specified { + if stepValueNegative { + stop = -1 + } else { + stop = length + } + } else { + stop = capSlice(length, parts[1].N, step) + } + return []int{start, stop, step}, nil +} + +func capSlice(length int, actual int, step int) int { + if actual < 0 { + actual += length + if actual < 0 { + if step < 0 { + actual = -1 + } else { + actual = 0 + } + } + } else if actual >= length { + if step < 0 { + actual = length - 1 + } else { + actual = length + } + } + return actual +} + +// ToArrayNum converts an empty interface type to a slice of float64. +// If any element in the array cannot be converted, then nil is returned +// along with a second value of false. +func toArrayNum(data interface{}) ([]float64, bool) { + // Is there a better way to do this with reflect? + if d, ok := data.([]interface{}); ok { + result := make([]float64, len(d)) + for i, el := range d { + item, ok := el.(float64) + if !ok { + return nil, false + } + result[i] = item + } + return result, true + } + return nil, false +} + +// ToArrayStr converts an empty interface type to a slice of strings. +// If any element in the array cannot be converted, then nil is returned +// along with a second value of false. If the input data could be entirely +// converted, then the converted data, along with a second value of true, +// will be returned. +func toArrayStr(data interface{}) ([]string, bool) { + // Is there a better way to do this with reflect? + if d, ok := data.([]interface{}); ok { + result := make([]string, len(d)) + for i, el := range d { + item, ok := el.(string) + if !ok { + return nil, false + } + result[i] = item + } + return result, true + } + return nil, false +} + +func isSliceType(v interface{}) bool { + if v == nil { + return false + } + return reflect.TypeOf(v).Kind() == reflect.Slice +} diff --git a/vendor/github.com/matryer/moq/main.go b/vendor/github.com/matryer/moq/main.go index e9a17d9..04cd2c8 100644 --- a/vendor/github.com/matryer/moq/main.go +++ b/vendor/github.com/matryer/moq/main.go @@ -2,12 +2,12 @@ package main import ( "bytes" - "errors" "flag" "fmt" "io" "io/ioutil" "os" + "errors" "github.com/matryer/moq/pkg/moq" ) diff --git a/vendor/github.com/matryer/moq/pkg/moq/moq.go b/vendor/github.com/matryer/moq/pkg/moq/moq.go index c2a27ee..d2ad06e 100644 --- a/vendor/github.com/matryer/moq/pkg/moq/moq.go +++ b/vendor/github.com/matryer/moq/pkg/moq/moq.go @@ -10,7 +10,6 @@ import ( "go/token" "go/types" "io" - "io/ioutil" "os" "path" "path/filepath" @@ -172,10 +171,6 @@ func (m *Mocker) Mock(w io.Writer, name ...string) error { doc.Imports = append(doc.Imports, stripVendorPath(pkgToImport)) } - if tpkg.Name() != m.pkgName { - doc.SourcePackagePrefix = tpkg.Name() + "." - } - var buf bytes.Buffer err = m.tmpl.Execute(&buf, doc) if err != nil { @@ -239,19 +234,7 @@ func pkgInfoFromPath(src string) (*loader.PackageInfo, error) { ParserMode: parser.SpuriousErrors, Cwd: src, } - if strings.HasPrefix(pkgFull, string(filepath.Separator)) { - files, err := ioutil.ReadDir(pkgFull) - if err != nil { - return nil, err - } - for _, file := range files { - if !file.IsDir() && strings.HasSuffix(file.Name(), ".go") && !strings.HasSuffix(file.Name(), "_test.go") { - conf.CreateFromFilenames(abs, file.Name()) - } - } - } else { - conf.Import(pkgFull) - } + conf.Import(pkgFull) lprog, err := conf.Load() if err != nil { return nil, err @@ -266,10 +249,9 @@ func pkgInfoFromPath(src string) (*loader.PackageInfo, error) { } type doc struct { - PackageName string - SourcePackagePrefix string - Objects []obj - Imports []string + PackageName string + Objects []obj + Imports []string } type obj struct { diff --git a/vendor/github.com/matryer/moq/pkg/moq/template.go b/vendor/github.com/matryer/moq/pkg/moq/template.go index a3b1984..31a6c60 100644 --- a/vendor/github.com/matryer/moq/pkg/moq/template.go +++ b/vendor/github.com/matryer/moq/pkg/moq/template.go @@ -8,7 +8,6 @@ var moqTemplate = `// Code generated by moq; DO NOT EDIT. // github.com/matryer/moq package {{.PackageName}} -{{- $sourcePackagePrefix := .SourcePackagePrefix}} import ( {{- range .Imports }} @@ -23,10 +22,6 @@ var ( {{- end }} ) -// Ensure, that {{.InterfaceName}}Mock does implement {{.InterfaceName}}. -// If this is not the case, regenerate this file with moq. -var _ {{$sourcePackagePrefix}}{{.InterfaceName}} = &{{.InterfaceName}}Mock{} - // {{.InterfaceName}}Mock is a mock implementation of {{.InterfaceName}}. // // func TestSomethingThatUses{{.InterfaceName}}(t *testing.T) { diff --git a/vendor/github.com/onsi/gomega/gstruct/elements.go b/vendor/github.com/onsi/gomega/gstruct/elements.go new file mode 100644 index 0000000..a315fa1 --- /dev/null +++ b/vendor/github.com/onsi/gomega/gstruct/elements.go @@ -0,0 +1,145 @@ +package gstruct + +import ( + "errors" + "fmt" + "reflect" + "runtime/debug" + + "github.com/onsi/gomega/format" + errorsutil "github.com/onsi/gomega/gstruct/errors" + "github.com/onsi/gomega/types" +) + +//MatchAllElements succeeds if every element of a slice matches the element matcher it maps to +//through the id function, and every element matcher is matched. +// Expect([]string{"a", "b"}).To(MatchAllElements(idFn, matchers.Elements{ +// "a": BeEqual("a"), +// "b": BeEqual("b"), +// }) +func MatchAllElements(identifier Identifier, elements Elements) types.GomegaMatcher { + return &ElementsMatcher{ + Identifier: identifier, + Elements: elements, + } +} + +//MatchElements succeeds if each element of a slice matches the element matcher it maps to +//through the id function. It can ignore extra elements and/or missing elements. +// Expect([]string{"a", "c"}).To(MatchElements(idFn, IgnoreMissing|IgnoreExtra, matchers.Elements{ +// "a": BeEqual("a") +// "b": BeEqual("b"), +// }) +func MatchElements(identifier Identifier, options Options, elements Elements) types.GomegaMatcher { + return &ElementsMatcher{ + Identifier: identifier, + Elements: elements, + IgnoreExtras: options&IgnoreExtras != 0, + IgnoreMissing: options&IgnoreMissing != 0, + AllowDuplicates: options&AllowDuplicates != 0, + } +} + +// ElementsMatcher is a NestingMatcher that applies custom matchers to each element of a slice mapped +// by the Identifier function. +// TODO: Extend this to work with arrays & maps (map the key) as well. +type ElementsMatcher struct { + // Matchers for each element. + Elements Elements + // Function mapping an element to the string key identifying its matcher. + Identifier Identifier + + // Whether to ignore extra elements or consider it an error. + IgnoreExtras bool + // Whether to ignore missing elements or consider it an error. + IgnoreMissing bool + // Whether to key duplicates when matching IDs. + AllowDuplicates bool + + // State. + failures []error +} + +// Element ID to matcher. +type Elements map[string]types.GomegaMatcher + +// Function for identifying (mapping) elements. +type Identifier func(element interface{}) string + +func (m *ElementsMatcher) Match(actual interface{}) (success bool, err error) { + if reflect.TypeOf(actual).Kind() != reflect.Slice { + return false, fmt.Errorf("%v is type %T, expected slice", actual, actual) + } + + m.failures = m.matchElements(actual) + if len(m.failures) > 0 { + return false, nil + } + return true, nil +} + +func (m *ElementsMatcher) matchElements(actual interface{}) (errs []error) { + // Provide more useful error messages in the case of a panic. + defer func() { + if err := recover(); err != nil { + errs = append(errs, fmt.Errorf("panic checking %+v: %v\n%s", actual, err, debug.Stack())) + } + }() + + val := reflect.ValueOf(actual) + elements := map[string]bool{} + for i := 0; i < val.Len(); i++ { + element := val.Index(i).Interface() + id := m.Identifier(element) + if elements[id] { + if !m.AllowDuplicates { + errs = append(errs, fmt.Errorf("found duplicate element ID %s", id)) + continue + } + } + elements[id] = true + + matcher, expected := m.Elements[id] + if !expected { + if !m.IgnoreExtras { + errs = append(errs, fmt.Errorf("unexpected element %s", id)) + } + continue + } + + match, err := matcher.Match(element) + if match { + continue + } + + if err == nil { + if nesting, ok := matcher.(errorsutil.NestingMatcher); ok { + err = errorsutil.AggregateError(nesting.Failures()) + } else { + err = errors.New(matcher.FailureMessage(element)) + } + } + errs = append(errs, errorsutil.Nest(fmt.Sprintf("[%s]", id), err)) + } + + for id := range m.Elements { + if !elements[id] && !m.IgnoreMissing { + errs = append(errs, fmt.Errorf("missing expected element %s", id)) + } + } + + return errs +} + +func (m *ElementsMatcher) FailureMessage(actual interface{}) (message string) { + failure := errorsutil.AggregateError(m.failures) + return format.Message(actual, fmt.Sprintf("to match elements: %v", failure)) +} + +func (m *ElementsMatcher) NegatedFailureMessage(actual interface{}) (message string) { + return format.Message(actual, "not to match elements") +} + +func (m *ElementsMatcher) Failures() []error { + return m.failures +} diff --git a/vendor/github.com/onsi/gomega/gstruct/errors/nested_types.go b/vendor/github.com/onsi/gomega/gstruct/errors/nested_types.go new file mode 100644 index 0000000..188492b --- /dev/null +++ b/vendor/github.com/onsi/gomega/gstruct/errors/nested_types.go @@ -0,0 +1,72 @@ +package errors + +import ( + "fmt" + "strings" + + "github.com/onsi/gomega/types" +) + +// A stateful matcher that nests other matchers within it and preserves the error types of the +// nested matcher failures. +type NestingMatcher interface { + types.GomegaMatcher + + // Returns the failures of nested matchers. + Failures() []error +} + +// An error type for labeling errors on deeply nested matchers. +type NestedError struct { + Path string + Err error +} + +func (e *NestedError) Error() string { + // Indent Errors. + indented := strings.Replace(e.Err.Error(), "\n", "\n\t", -1) + return fmt.Sprintf("%s:\n\t%v", e.Path, indented) +} + +// Create a NestedError with the given path. +// If err is a NestedError, prepend the path to it. +// If err is an AggregateError, recursively Nest each error. +func Nest(path string, err error) error { + if ag, ok := err.(AggregateError); ok { + var errs AggregateError + for _, e := range ag { + errs = append(errs, Nest(path, e)) + } + return errs + } + if ne, ok := err.(*NestedError); ok { + return &NestedError{ + Path: path + ne.Path, + Err: ne.Err, + } + } + return &NestedError{ + Path: path, + Err: err, + } +} + +// An error type for treating multiple errors as a single error. +type AggregateError []error + +// Error is part of the error interface. +func (err AggregateError) Error() string { + if len(err) == 0 { + // This should never happen, really. + return "" + } + if len(err) == 1 { + return err[0].Error() + } + result := fmt.Sprintf("[%s", err[0].Error()) + for i := 1; i < len(err); i++ { + result += fmt.Sprintf(", %s", err[i].Error()) + } + result += "]" + return result +} diff --git a/vendor/github.com/onsi/gomega/gstruct/fields.go b/vendor/github.com/onsi/gomega/gstruct/fields.go new file mode 100644 index 0000000..0020b87 --- /dev/null +++ b/vendor/github.com/onsi/gomega/gstruct/fields.go @@ -0,0 +1,141 @@ +package gstruct + +import ( + "errors" + "fmt" + "reflect" + "runtime/debug" + "strings" + + "github.com/onsi/gomega/format" + errorsutil "github.com/onsi/gomega/gstruct/errors" + "github.com/onsi/gomega/types" +) + +//MatchAllFields succeeds if every field of a struct matches the field matcher associated with +//it, and every element matcher is matched. +// Expect([]string{"a", "b"}).To(MatchAllFields(gstruct.Fields{ +// "a": BeEqual("a"), +// "b": BeEqual("b"), +// }) +func MatchAllFields(fields Fields) types.GomegaMatcher { + return &FieldsMatcher{ + Fields: fields, + } +} + +//MatchFields succeeds if each element of a struct matches the field matcher associated with +//it. It can ignore extra fields and/or missing fields. +// Expect([]string{"a", "c"}).To(MatchFields(IgnoreMissing|IgnoreExtra, gstruct.Fields{ +// "a": BeEqual("a") +// "b": BeEqual("b"), +// }) +func MatchFields(options Options, fields Fields) types.GomegaMatcher { + return &FieldsMatcher{ + Fields: fields, + IgnoreExtras: options&IgnoreExtras != 0, + IgnoreMissing: options&IgnoreMissing != 0, + } +} + +type FieldsMatcher struct { + // Matchers for each field. + Fields Fields + + // Whether to ignore extra elements or consider it an error. + IgnoreExtras bool + // Whether to ignore missing elements or consider it an error. + IgnoreMissing bool + + // State. + failures []error +} + +// Field name to matcher. +type Fields map[string]types.GomegaMatcher + +func (m *FieldsMatcher) Match(actual interface{}) (success bool, err error) { + if reflect.TypeOf(actual).Kind() != reflect.Struct { + return false, fmt.Errorf("%v is type %T, expected struct", actual, actual) + } + + m.failures = m.matchFields(actual) + if len(m.failures) > 0 { + return false, nil + } + return true, nil +} + +func (m *FieldsMatcher) matchFields(actual interface{}) (errs []error) { + val := reflect.ValueOf(actual) + typ := val.Type() + fields := map[string]bool{} + for i := 0; i < val.NumField(); i++ { + fieldName := typ.Field(i).Name + fields[fieldName] = true + + err := func() (err error) { + // This test relies heavily on reflect, which tends to panic. + // Recover here to provide more useful error messages in that case. + defer func() { + if r := recover(); r != nil { + err = fmt.Errorf("panic checking %+v: %v\n%s", actual, r, debug.Stack()) + } + }() + + matcher, expected := m.Fields[fieldName] + if !expected { + if !m.IgnoreExtras { + return fmt.Errorf("unexpected field %s: %+v", fieldName, actual) + } + return nil + } + + var field interface{} + if val.Field(i).IsValid() { + field = val.Field(i).Interface() + } else { + field = reflect.Zero(typ.Field(i).Type) + } + + match, err := matcher.Match(field) + if err != nil { + return err + } else if !match { + if nesting, ok := matcher.(errorsutil.NestingMatcher); ok { + return errorsutil.AggregateError(nesting.Failures()) + } + return errors.New(matcher.FailureMessage(field)) + } + return nil + }() + if err != nil { + errs = append(errs, errorsutil.Nest("."+fieldName, err)) + } + } + + for field := range m.Fields { + if !fields[field] && !m.IgnoreMissing { + errs = append(errs, fmt.Errorf("missing expected field %s", field)) + } + } + + return errs +} + +func (m *FieldsMatcher) FailureMessage(actual interface{}) (message string) { + failures := make([]string, len(m.failures)) + for i := range m.failures { + failures[i] = m.failures[i].Error() + } + return format.Message(reflect.TypeOf(actual).Name(), + fmt.Sprintf("to match fields: {\n%v\n}\n", strings.Join(failures, "\n"))) +} + +func (m *FieldsMatcher) NegatedFailureMessage(actual interface{}) (message string) { + return format.Message(actual, "not to match fields") +} + +func (m *FieldsMatcher) Failures() []error { + return m.failures +} diff --git a/vendor/github.com/onsi/gomega/gstruct/ignore.go b/vendor/github.com/onsi/gomega/gstruct/ignore.go new file mode 100644 index 0000000..0365f32 --- /dev/null +++ b/vendor/github.com/onsi/gomega/gstruct/ignore.go @@ -0,0 +1,37 @@ +package gstruct + +import ( + "github.com/onsi/gomega/types" +) + +//Ignore ignores the actual value and always succeeds. +// Expect(nil).To(Ignore()) +// Expect(true).To(Ignore()) +func Ignore() types.GomegaMatcher { + return &IgnoreMatcher{true} +} + +//Reject ignores the actual value and always fails. It can be used in conjunction with IgnoreMissing +//to catch problematic elements, or to verify tests are running. +// Expect(nil).NotTo(Reject()) +// Expect(true).NotTo(Reject()) +func Reject() types.GomegaMatcher { + return &IgnoreMatcher{false} +} + +// A matcher that either always succeeds or always fails. +type IgnoreMatcher struct { + Succeed bool +} + +func (m *IgnoreMatcher) Match(actual interface{}) (bool, error) { + return m.Succeed, nil +} + +func (m *IgnoreMatcher) FailureMessage(_ interface{}) (message string) { + return "Unconditional failure" +} + +func (m *IgnoreMatcher) NegatedFailureMessage(_ interface{}) (message string) { + return "Unconditional success" +} diff --git a/vendor/github.com/onsi/gomega/gstruct/pointer.go b/vendor/github.com/onsi/gomega/gstruct/pointer.go new file mode 100644 index 0000000..0a2f35d --- /dev/null +++ b/vendor/github.com/onsi/gomega/gstruct/pointer.go @@ -0,0 +1,56 @@ +package gstruct + +import ( + "fmt" + "reflect" + + "github.com/onsi/gomega/format" + "github.com/onsi/gomega/types" +) + +//PointTo applies the given matcher to the value pointed to by actual. It fails if the pointer is +//nil. +// actual := 5 +// Expect(&actual).To(PointTo(Equal(5))) +func PointTo(matcher types.GomegaMatcher) types.GomegaMatcher { + return &PointerMatcher{ + Matcher: matcher, + } +} + +type PointerMatcher struct { + Matcher types.GomegaMatcher + + // Failure message. + failure string +} + +func (m *PointerMatcher) Match(actual interface{}) (bool, error) { + val := reflect.ValueOf(actual) + + // return error if actual type is not a pointer + if val.Kind() != reflect.Ptr { + return false, fmt.Errorf("PointerMatcher expects a pointer but we have '%s'", val.Kind()) + } + + if !val.IsValid() || val.IsNil() { + m.failure = format.Message(actual, "not to be ") + return false, nil + } + + // Forward the value. + elem := val.Elem().Interface() + match, err := m.Matcher.Match(elem) + if !match { + m.failure = m.Matcher.FailureMessage(elem) + } + return match, err +} + +func (m *PointerMatcher) FailureMessage(_ interface{}) (message string) { + return m.failure +} + +func (m *PointerMatcher) NegatedFailureMessage(actual interface{}) (message string) { + return m.Matcher.NegatedFailureMessage(actual) +} diff --git a/vendor/github.com/onsi/gomega/gstruct/types.go b/vendor/github.com/onsi/gomega/gstruct/types.go new file mode 100644 index 0000000..48cbbe8 --- /dev/null +++ b/vendor/github.com/onsi/gomega/gstruct/types.go @@ -0,0 +1,15 @@ +package gstruct + +//Options is the type for options passed to some matchers. +type Options int + +const ( + //IgnoreExtras tells the matcher to ignore extra elements or fields, rather than triggering a failure. + IgnoreExtras Options = 1 << iota + //IgnoreMissing tells the matcher to ignore missing elements or fields, rather than triggering a failure. + IgnoreMissing + //AllowDuplicates tells the matcher to permit multiple members of the slice to produce the same ID when + //considered by the indentifier function. All members that map to a given key must still match successfully + //with the matcher that is provided for that key. + AllowDuplicates +)