-
Notifications
You must be signed in to change notification settings - Fork 5
/
apiauth.go
190 lines (155 loc) · 4.81 KB
/
apiauth.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
package apiauth
import (
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"fmt"
"log"
"net/http"
"strings"
"time"
)
var gmt *time.Location
func init() {
loc, err := time.LoadLocation("Etc/GMT")
if err != nil {
log.Fatalf("Failed to load apiauth - Can not load timezone Etc/GMT: %s. See https://golang.org/pkg/time/#LoadLocation", err.Error())
}
gmt = loc
}
// Sign computes the signature for the given HTTP request, and
// adds the resulting Authorization header value to it. If any
// of the prerequisite headers are absent, an error is returned.
func Sign(r *http.Request, accessID, secret string) error {
if err := sufficientHeaders(r); err != nil {
return err
}
preexisting := r.Header.Get("Authorization")
if preexisting != "" {
return fmt.Errorf("Authorization header already present")
}
sig := Compute(CanonicalString(r), secret)
r.Header.Set("Authorization", fmt.Sprintf("APIAuth %s:%s", accessID, sig))
return nil
}
// SignWithMethod computs the signature of the given HTTP request
// as in Sign except that the canonical string includes the HTTP
// request method.
func SignWithMethod(r *http.Request, accessID, secret string) error {
if err := sufficientHeaders(r); err != nil {
return err
}
preexisting := r.Header.Get("Authorization")
if preexisting != "" {
return fmt.Errorf("Authorization header already present")
}
sig := Compute(CanonicalStringWithMethod(r), secret)
r.Header.Set("Authorization", fmt.Sprintf("APIAuth %s:%s", accessID, sig))
return nil
}
// Verify checks a request for validity: all required headers
// are present and the signature matches.
func Verify(r *http.Request, secret string) error {
if err := sufficientHeaders(r); err != nil {
return err
}
auth := r.Header.Get("Authorization")
if auth == "" {
return fmt.Errorf("Authorization header not set")
}
_, sig, err := Parse(auth)
if err != nil {
return err
}
if VerifySignature(sig, CanonicalString(r), secret) || VerifySignature(sig, CanonicalStringWithMethod(r), secret) {
return nil
}
return fmt.Errorf("Signature mismatch")
}
// VerifySignature computes the expected signature for a given
// canonical string and secret key pair, and returns true if the
// given signature matches.
func VerifySignature(sig, canonicalString, secret string) bool {
expected := Compute(canonicalString, secret)
return expected == sig
}
// Parse returns the access ID and signature present in the
// given string, presumably taken from a request's Authorization
// header. If the header does not match the expected `APIAuth access_id:signature`
// format, an error is returned.
func Parse(header string) (id, sig string, err error) {
var tokens []string
if !strings.HasPrefix(header, "APIAuth ") {
goto malformed
}
tokens = strings.Split(header[8:], ":")
if len(tokens) != 2 || tokens[0] == "" || tokens[1] == "" {
goto malformed
}
return tokens[0], tokens[1], nil
malformed:
return "", "", fmt.Errorf("Malformed header: %s", header)
}
// Date returns a suitable value for a request's Date header,
// based on the current time in GMT in RFC1123 format.
func Date() string {
return DateForTime(time.Now())
}
// DateForTime converts the given time to GMT, and returns it
// in RFC1123 format. I would rather this use UTC, but Ruby's
// `Time#httpdate` spits out GMT, and I need to maintain
// fairly rigid compatibility.
func DateForTime(t time.Time) string {
return t.In(gmt).Format(time.RFC1123)
}
// CanonicalString returns the canonical string used for the signature
// based on the headers in the given request.
func CanonicalString(r *http.Request) string {
uri := r.URL.EscapedPath()
if uri == "" {
uri = "/"
}
if r.URL.RawQuery != "" {
uri = uri + "?" + r.URL.RawQuery
}
header := r.Header
return strings.Join([]string{
header.Get("Content-Type"),
header.Get("Content-MD5"),
uri,
header.Get("Date"),
}, ",")
}
// CanonicalStringWithMethod returns a canonical string as in CanonicalString
// but also includes the request method
func CanonicalStringWithMethod(r *http.Request) string {
return strings.Join([]string{
strings.ToUpper(r.Method),
CanonicalString(r),
}, ",")
}
// Compute computes the signature for a given canonical string, using
// the HMAC-SHA1.
func Compute(canonicalString, secret string) string {
mac := hmac.New(sha1.New, []byte(secret))
mac.Write([]byte(canonicalString))
return base64.StdEncoding.EncodeToString(mac.Sum(nil))
}
func sufficientHeaders(r *http.Request) error {
date := r.Header.Get("Date")
if date == "" {
return fmt.Errorf("No Date header present")
}
if r.Body == nil || r.Body == http.NoBody {
return nil
}
contentType := r.Header.Get("Content-Type")
if contentType == "" {
return fmt.Errorf("No Content-Type header present")
}
contentMD5 := r.Header.Get("Content-MD5")
if contentMD5 == "" {
return fmt.Errorf("No Content-MD5 header present")
}
return nil
}