-
Notifications
You must be signed in to change notification settings - Fork 70
/
Copy pathsigner.go
168 lines (146 loc) · 3.95 KB
/
signer.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
package edgegrid
import (
"bytes"
"crypto/sha256"
"encoding/base64"
"fmt"
"io"
"net/http"
"sort"
"strings"
"time"
"github.com/google/uuid"
"go.uber.org/ratelimit"
)
type (
// Signer is the request signer interface
Signer interface {
SignRequest(r *http.Request)
CheckRequestLimit(requestLimit int)
}
authHeader struct {
authType string
clientToken string
accessToken string
timestamp string
nonce string
signature string
}
)
const (
authType = "EG1-HMAC-SHA256"
)
var (
// rateLimit represents the maximum number of API requests per second the provider can make
requestLimit ratelimit.Limiter
)
// SignRequest adds a signed authorization header to the http request
func (c Config) SignRequest(r *http.Request) {
if r.URL.Host == "" {
r.URL.Host = c.Host
}
if r.URL.Scheme == "" {
r.URL.Scheme = "https"
}
r.URL.RawQuery = c.addAccountSwitchKey(r)
r.Header.Set("Authorization", c.createAuthHeader(r).String())
}
// CheckRequestLimit waits if necessary to ensure that OpenAPI's request limit is not exceeded
func (c Config) CheckRequestLimit(limit int) {
if limit > 0 {
if requestLimit == nil {
requestLimit = ratelimit.New(limit)
}
requestLimit.Take()
}
}
func (c Config) createAuthHeader(r *http.Request) authHeader {
timestamp := Timestamp(time.Now())
auth := authHeader{
authType: authType,
clientToken: c.ClientToken,
accessToken: c.AccessToken,
timestamp: timestamp,
nonce: uuid.New().String(),
}
msgPath := r.URL.EscapedPath()
if r.URL.RawQuery != "" {
msgPath = fmt.Sprintf("%s?%s", msgPath, r.URL.RawQuery)
}
// create the message to be signed
msgData := []string{
r.Method,
r.URL.Scheme,
r.URL.Host,
msgPath,
canonicalizeHeaders(r.Header, c.HeaderToSign),
createContentHash(r, c.MaxBody),
auth.String(),
}
msg := strings.Join(msgData, "\t")
key := createSignature(timestamp, c.ClientSecret)
auth.signature = createSignature(msg, key)
return auth
}
func canonicalizeHeaders(requestHeaders http.Header, headersToSign []string) string {
var unsortedHeader []string
var sortedHeader []string
for k := range requestHeaders {
unsortedHeader = append(unsortedHeader, k)
}
sort.Strings(unsortedHeader)
for _, k := range unsortedHeader {
for _, sign := range headersToSign {
if sign == k {
v := strings.TrimSpace(requestHeaders.Get(k))
sortedHeader = append(sortedHeader, fmt.Sprintf("%s:%s", strings.ToLower(k), strings.ToLower(stringMinifier(v))))
}
}
}
return strings.Join(sortedHeader, "\t")
}
// The content hash is the base64-encoded SHA–256 hash of the POST body.
// For any other request methods, this field is empty. But the tab separator (\t) must be included.
// The size of the POST body must be less than or equal to the value specified by the service.
// Any request that does not meet this criteria SHOULD be rejected during the signing process,
// as the request will be rejected by EdgeGrid.
func createContentHash(r *http.Request, maxBody int) string {
var (
contentHash string
preparedBody string
bodyBytes []byte
)
if r.Body != nil {
bodyBytes, _ = io.ReadAll(r.Body)
r.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))
preparedBody = string(bodyBytes)
}
if r.Method == http.MethodPost && len(preparedBody) > 0 {
if len(preparedBody) > maxBody {
preparedBody = preparedBody[0:maxBody]
}
sum := sha256.Sum256([]byte(preparedBody))
contentHash = base64.StdEncoding.EncodeToString(sum[:])
}
return contentHash
}
func (a authHeader) String() string {
auth := fmt.Sprintf("%s client_token=%s;access_token=%s;timestamp=%s;nonce=%s;",
a.authType,
a.clientToken,
a.accessToken,
a.timestamp,
a.nonce)
if a.signature != "" {
auth += fmt.Sprintf("signature=%s", a.signature)
}
return auth
}
func (c Config) addAccountSwitchKey(r *http.Request) string {
if c.AccountKey != "" {
values := r.URL.Query()
values.Add("accountSwitchKey", c.AccountKey)
r.URL.RawQuery = values.Encode()
}
return r.URL.RawQuery
}