forked from akamai/AkamaiOPEN-edgegrid-golang
/
edgegrid.go
249 lines (220 loc) · 7.4 KB
/
edgegrid.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
238
239
240
241
242
243
244
245
246
247
248
249
// Package edgegrid provides the Akamai {OPEN} Edgegrid Authentication scheme
package edgegrid
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"fmt"
"github.com/go-ini/ini"
log "github.com/Sirupsen/logrus"
"github.com/tuvistavie/securerandom"
"gopkg.in/mattes/go-expand-tilde.v1"
"io/ioutil"
"net/http"
"sort"
"strings"
"time"
"unicode"
)
// Config struct provides all the necessary fields to
// create authorization header, debug is optional
type Config struct {
Host string `ini:"host"`
ClientToken string `ini:"client_token"`
ClientSecret string `ini:"client_secret"`
AccessToken string `ini:"access_token"`
HeaderToSign []string `ini:"headers_to_sign"`
MaxBody int `ini:"max_body"`
Debug bool `ini:"debug"`
}
// Must be assigned the UTC time when the request is signed.
// Format of “yyyyMMddTHH:mm:ss+0000”
func makeEdgeTimeStamp() string {
local := time.FixedZone("GMT", 0)
t := time.Now().In(local)
return fmt.Sprintf("%d%02d%02dT%02d:%02d:%02d+0000",
t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second())
}
// Must be assigned a nonce (number used once) for the request.
// It is a random string used to detect replayed request messages.
// A GUID is recommended.
func createNonce() string {
uuid, err := securerandom.Uuid()
if err != nil {
log.Errorf("Generate Uuid failed, %s", err)
return ""
}
return uuid
}
func stringMinifier(in string) (out string) {
white := false
for _, c := range in {
if unicode.IsSpace(c) {
if !white {
out = out + " "
}
white = true
} else {
out = out + string(c)
white = false
}
}
return
}
func concatPathQuery(path, query string) string {
if query == "" {
return path
}
return fmt.Sprintf("%s?%s", path, query)
}
// createSignature is the base64-encoding of the SHA–256 HMAC of the data to sign with the signing key.
func createSignature(message string, secret string) string {
key := []byte(secret)
h := hmac.New(sha256.New, key)
h.Write([]byte(message))
return base64.StdEncoding.EncodeToString(h.Sum(nil))
}
func createHash(data string) string {
h := sha256.Sum256([]byte(data))
return base64.StdEncoding.EncodeToString(h[:])
}
func (c *Config) canonicalizeHeaders(req *http.Request) string {
var unsortedHeader []string
var sortedHeader []string
for k := range req.Header {
unsortedHeader = append(unsortedHeader, k)
}
sort.Strings(unsortedHeader)
for _, k := range unsortedHeader {
for _, sign := range c.HeaderToSign {
if sign == k {
v := strings.TrimSpace(req.Header.Get(k))
sortedHeader = append(sortedHeader, fmt.Sprintf("%s:%s", strings.ToLower(k), strings.ToLower(stringMinifier(v))))
}
}
}
return strings.Join(sortedHeader, "\t")
}
// signingKey is derived from the client secret.
// The signing key is computed as the base64 encoding of the SHA–256 HMAC of the timestamp string
// (the field value included in the HTTP authorization header described above) with the client secret as the key.
func (c *Config) signingKey(timestamp string) string {
key := createSignature(timestamp, c.ClientSecret)
return key
}
// 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 tac 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 (c *Config) createContentHash(req *http.Request) string {
var (
contentHash string
preparedBody string
bodyBytes []byte
)
if req.Body != nil {
bodyBytes, _ = ioutil.ReadAll(req.Body)
req.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
preparedBody = string(bodyBytes)
}
log.Debugf("Body is %s", preparedBody)
if req.Method == "POST" && len(preparedBody) > 0 {
log.Debugf("Signing content: %s", preparedBody)
if len(preparedBody) > c.MaxBody {
log.Debugf("Data length %d is larger than maximum %d",
len(preparedBody), c.MaxBody)
preparedBody = preparedBody[0:c.MaxBody]
log.Debugf("Data truncated to %d for computing the hash", len(preparedBody))
}
contentHash = createHash(preparedBody)
}
log.Debugf("Content hash is '%s'", contentHash)
return contentHash
}
// The data to sign includes the information from the HTTP request that is relevant to ensuring that the request is authentic.
// This data set comprised of the request data combined with the authorization header value (excluding the signature field,
// but including the ; right before the signature field).
func (c *Config) signingData(req *http.Request, authHeader string) string {
dataSign := []string{
req.Method,
req.URL.Scheme,
req.URL.Host,
concatPathQuery(req.URL.Path, req.URL.RawQuery),
c.canonicalizeHeaders(req),
c.createContentHash(req),
authHeader,
}
log.Debugf("Data to sign %s", strings.Join(dataSign, "\t"))
return strings.Join(dataSign, "\t")
}
func (c *Config) signingRequest(req *http.Request, authHeader string, timestamp string) string {
return createSignature(c.signingData(req, authHeader),
c.signingKey(timestamp))
}
// The Authorization header starts with the signing algorithm moniker (name of the algorithm) used to sign the request.
// The moniker below identifies EdgeGrid V1, hash message authentication code, SHA–256 as the hash standard.
// This moniker is then followed by a space and an ordered list of name value pairs with each field separated by a semicolon.
func (c *Config) createAuthHeader(req *http.Request, timestamp string, nonce string) string {
authHeader := fmt.Sprintf("EG1-HMAC-SHA256 client_token=%s;access_token=%s;timestamp=%s;nonce=%s;",
c.ClientToken,
c.AccessToken,
timestamp,
nonce,
)
log.Debugf("Unsigned authorization header: '%s'", authHeader)
signedAuthHeader := fmt.Sprintf("%ssignature=%s", authHeader, c.signingRequest(req, authHeader, timestamp))
log.Debugf("Signed authorization header: '%s'", signedAuthHeader)
return signedAuthHeader
}
// AddRequestHeader sets the authorization header to use Akamai Open API
func AddRequestHeader(c Config, req *http.Request) *http.Request {
if c.Debug {
log.SetLevel(log.DebugLevel)
}
timestamp := makeEdgeTimeStamp()
nonce := createNonce()
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", c.createAuthHeader(req, timestamp, nonce))
return req
}
// InitConfig initializes configuration file
func InitConfig(filepath string, section string) Config {
var (
c Config
requiredOptions = []string{"host", "client_token", "client_secret", "access_token"}
missing []string
)
// Check if filepath is empty
if filepath == "" {
filepath = "~/.edgerc"
}
// Check if section is empty
if section == "" {
section = "default"
}
// Tilde seems to be not working when passing ~/.edgerc as file
// Takes current user and use home dir instead
path, err := tilde.Expand(filepath)
if err != nil {
log.Panicf("Fatal could not find home dir from user: %s \n", err)
}
edgerc, err := ini.Load(path)
if err != nil {
log.Panicf("Fatal error config file: %s \n", err)
}
edgerc.Section(section).MapTo(&c)
for _, opt := range requiredOptions {
if !(edgerc.Section(section).HasKey(opt)) {
missing = append(missing, opt)
}
}
if len(missing) > 0 {
log.Panicf("Fatal missing required options: %s \n", missing)
}
if c.MaxBody == 0 {
c.MaxBody = 131072
}
return c
}