/
presigner.go
237 lines (187 loc) · 6.25 KB
/
presigner.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
package utils
import (
"context"
"encoding/xml"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"time"
v4 "github.com/aws/aws-sdk-go-v2/aws/signer/v4"
"github.com/aws/aws-sdk-go-v2/config"
backoff "github.com/cenkalti/backoff/v4"
"github.com/golang/glog"
utils "github.com/bolt-observer/go_common/utils"
"github.com/ReneKroon/ttlcache"
)
// We use AWS pre-signed URLs here which can be used as an effective way to use IAM authentication for a custom app,
// read https://ahermosilla.com/cloud/2020/11/17/leveraging-aws-signed-requests.html for more details.
const (
// PresignHeader - HTTP Header for pre-signed requests
PresignHeader = "X-Amazon-Presigned-Getcalleridentity"
// EmptyBodyHash - Hash of empty body
EmptyBodyHash = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
)
// GetCallerIdentityResponse struct
type GetCallerIdentityResponse struct {
GetCallerIdentityResult GetCallerIdentityResult
}
// GetCallerIdentityResult struct
type GetCallerIdentityResult struct {
Arn string `xml:"Arn"`
UserID string `xml:"UserId"`
Account string `xml:"Account"`
}
const (
// DefaultCacheTime should be lower than token validity
DefaultCacheTime = 2 * time.Minute
// DefaultValidity is the default for new tokens
DefaultValidity = 5 * time.Minute
// HTTPRetryTime for doing the check on AWS STS
HTTPRetryTime = 3 * time.Second
)
var (
region string
service string
endpoint string
// token cache is used to cache AWS STS responses (VerifyGetCallerIdentity), if we are on server-side
tokenCache *ttlcache.Cache
// identity cache is used to cache token (PresignGetCallerIdentity), if we are the client
identityCache *ttlcache.Cache
)
func init() {
region = utils.GetEnvWithDefault("AWS_DEFAULT_REGION", "us-east-1")
service = "sts"
endpoint = fmt.Sprintf("https://%s.%s.amazonaws.com/", service, region)
tokenCache = ttlcache.NewCache()
tokenCache.SetTTL(DefaultCacheTime)
tokenCache.SkipTtlExtensionOnHit(true)
identityCache = ttlcache.NewCache()
identityCache.SetTTL(DefaultCacheTime)
identityCache.SkipTtlExtensionOnHit(true)
}
// VerifyGetCallerIdentity will verify that query string received is actually a presigned URL
// to sts/GetCallerIdentity.
// Returns:
// - ARN of the identity when successful
// - error else
func VerifyGetCallerIdentity(query string, timeout time.Duration) (string, error) {
var identity GetCallerIdentityResponse
val, cached := tokenCache.Get(query)
if cached {
return val.(string), nil
}
if strings.ContainsAny(query, "@?/") || strings.HasPrefix(query, "http") {
return "", fmt.Errorf("invalid query string")
}
req, err := http.NewRequest(http.MethodPost, endpoint, nil)
if err != nil {
return "", fmt.Errorf("unable to create request, %v", err)
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
req.URL.RawQuery = query
for key := range req.URL.Query() {
lowKey := strings.ToLower(key)
if lowKey == "action" || lowKey == "redirect" || lowKey == "version" {
return "", fmt.Errorf("action trickery detected")
}
}
req.URL.RawQuery = "Action=GetCallerIdentity&Version=2011-06-15&" + query
if int64(timeout) <= 0 {
timeout = DefaultValidity
}
client := &http.Client{
Timeout: timeout,
}
if !strings.HasSuffix(req.URL.Hostname(), ".amazonaws.com") {
return "", fmt.Errorf("hostname trickery detected, %s", req.URL.Hostname())
}
back := backoff.NewExponentialBackOff()
back.MaxElapsedTime = HTTPRetryTime
resp, err := backoff.RetryNotifyWithData(func() (*http.Response, error) {
return client.Do(req)
}, back, func(err error, d time.Duration) {
glog.Warningf("Error calling VerifyGetCallerIdentity")
})
if err != nil {
return "", fmt.Errorf("unable to make request, %v", err)
}
if resp.StatusCode == 401 || resp.StatusCode == 403 {
return "", fmt.Errorf("got unauthorized, %v", resp.StatusCode)
}
defer resp.Body.Close()
b, err := io.ReadAll(resp.Body)
if err != nil {
return "", fmt.Errorf("unable to read response body: %v", err)
}
err = xml.Unmarshal(b, &identity)
if err != nil {
return "", fmt.Errorf("unable to deserialize response, %v", err)
}
if identity.GetCallerIdentityResult.Arn == "" {
return "", fmt.Errorf("empty result")
}
tokenCache.Set(query, identity.GetCallerIdentityResult.Arn)
return identity.GetCallerIdentityResult.Arn, nil
}
// PresignGetCallerIdentity will sign a query string
// to retrieve my caller identity by third party.
// Returns:
// - the query string
// - error (when not successful)
func PresignGetCallerIdentity(validity time.Duration) (string, error) {
ctx := context.Background()
val, cached := identityCache.Get(validity.String())
if cached {
return val.(string), nil
}
cfg, err := config.LoadDefaultConfig(ctx, config.WithRegion(region))
if err != nil {
return "", fmt.Errorf("unable to load SDK config, %v", err)
}
creds, err := cfg.Credentials.Retrieve(ctx)
if err != nil {
return "", fmt.Errorf("unable to retrieve credentials, %v", err)
}
if creds.Expired() {
return "", fmt.Errorf("credentials expired")
}
req, err := http.NewRequest("POST", endpoint, nil)
if err != nil {
return "", fmt.Errorf("unable to create request, %v", err)
}
query := req.URL.Query()
query.Set("Action", "GetCallerIdentity")
query.Set("Version", "2011-06-15")
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
if int64(validity) <= 0 {
validity = DefaultValidity
}
query.Set("X-Amz-Expires", strconv.FormatInt(int64(validity/time.Second), 10))
req.URL.RawQuery = query.Encode()
signer := v4.NewSigner()
u, _, err := signer.PresignHTTP(ctx, creds, req, EmptyBodyHash, service, region, time.Now())
if err != nil {
return "", fmt.Errorf("unable to sign request, %v", err)
}
gu, err := url.Parse(u)
if err != nil {
return "", fmt.Errorf("unable to parse, %v", err)
}
nq := gu.Query()
nq.Del("Action")
nq.Del("Version")
gu.RawQuery = nq.Encode()
if validity != DefaultValidity {
cacheValidity := validity - 1*time.Minute // we just want a bit faster expiration than the validity of the token
if cacheValidity > 0 {
identityCache.SetWithTTL(validity.String(), gu.RawQuery, cacheValidity)
}
// if validity less than 1 minute it does not even make sense to cache token
} else {
identityCache.Set(validity.String(), gu.RawQuery)
}
return gu.RawQuery, nil
}