forked from olivere/elastic
/
aws_v4.go
89 lines (81 loc) · 2.43 KB
/
aws_v4.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
// Copyright 2012-present Oliver Eilhard. All rights reserved.
// Use of this source code is governed by a MIT-license.
// See http://olivere.mit-license.org/license.txt for details.
package v4
import (
"bytes"
"io/ioutil"
"net/http"
"net/url"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/signer/v4"
)
// NewV4SigningClient returns an *http.Client that will sign all requests with AWS V4 Signing.
func NewV4SigningClient(creds *credentials.Credentials, region string) *http.Client {
return NewV4SigningClientWithHTTPClient(creds, region, http.DefaultClient)
}
// NewV4SigningClientWithHTTPClient returns an *http.Client that will sign all requests with AWS V4 Signing.
func NewV4SigningClientWithHTTPClient(creds *credentials.Credentials, region string, httpClient *http.Client) *http.Client {
return &http.Client{
Transport: Transport{
client: httpClient,
creds: creds,
signer: v4.NewSigner(creds),
region: region,
},
}
}
// Transport is a RoundTripper that will sign requests with AWS V4 Signing
type Transport struct {
client *http.Client
creds *credentials.Credentials
signer *v4.Signer
region string
}
// RoundTrip uses the underlying RoundTripper transport, but signs request first with AWS V4 Signing
func (st Transport) RoundTrip(req *http.Request) (*http.Response, error) {
if h, ok := req.Header["Authorization"]; ok && len(h) > 0 && strings.HasPrefix(h[0], "AWS4") {
// Received a signed request, just pass it on.
return st.client.Do(req)
}
req.URL.Scheme = "https"
if strings.Contains(req.URL.RawPath, "%2C") {
// Escaping path
req.URL.RawPath = url.PathEscape(req.URL.RawPath)
}
now := time.Now().UTC()
req.Header.Set("Date", now.Format(time.RFC3339))
var err error
switch req.Body {
case nil:
_, err = st.signer.Sign(req, nil, "es", st.region, now)
default:
buf, err := ioutil.ReadAll(req.Body)
if err != nil {
return nil, err
}
req.Body = ioutil.NopCloser(bytes.NewReader(buf))
_, err = st.signer.Sign(req, bytes.NewReader(buf), "es", st.region, time.Now().UTC())
}
if err != nil {
return nil, err
}
resp, err := st.client.Do(req)
if resp != nil && resp.Body != nil {
defer resp.Body.Close()
}
if err != nil {
return nil, err
}
if resp.Body != nil {
buf := new(bytes.Buffer)
_, err = buf.ReadFrom(resp.Body)
if err != nil {
return nil, err
}
resp.Body = ioutil.NopCloser(bytes.NewReader(buf.Bytes()))
}
return resp, nil
}