-
Notifications
You must be signed in to change notification settings - Fork 63
/
credentials.go
269 lines (235 loc) · 6.3 KB
/
credentials.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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
package auth
import (
"context"
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"fmt"
"net/http"
"net/textproto"
"sort"
"strings"
api "github.com/qiniu/go-sdk/v7"
"github.com/qiniu/go-sdk/v7/conf"
internal_io "github.com/qiniu/go-sdk/v7/internal/io"
"github.com/qiniu/go-sdk/v7/storagev2/defaults"
)
const (
IAMKeyLen = 33
IAMKeyPrefix = "IAM-"
AuthorizationPrefixQiniu = "Qiniu "
AuthorizationPrefixQBox = "QBox "
)
// 七牛鉴权类,用于生成Qbox, Qiniu, Upload签名
//
// AK/SK可以从 https://portal.qiniu.com/user/key 获取
type Credentials struct {
AccessKey string
SecretKey []byte
}
// New 构建一个Credentials对象
func New(accessKey, secretKey string) *Credentials {
return &Credentials{accessKey, []byte(secretKey)}
}
// Default 构建默认的 Credentials 对象
func Default() *Credentials {
accessKey, secretKey, err := defaults.Credentials()
if err == nil && accessKey != "" && secretKey != "" {
return New(accessKey, secretKey)
}
return nil
}
// Sign 对数据进行签名,一般用于私有空间下载用途
func (ath *Credentials) Sign(data []byte) (token string) {
var (
accessKey string
secretKey []byte
)
if ath == nil {
if cred := Default(); cred != nil {
accessKey = cred.AccessKey
secretKey = cred.SecretKey
}
} else {
accessKey, secretKey = ath.AccessKey, ath.SecretKey
}
h := hmac.New(sha1.New, secretKey)
h.Write(data)
sign := base64.URLEncoding.EncodeToString(h.Sum(nil))
return fmt.Sprintf("%s:%s", accessKey, sign)
}
// SignToken 根据t的类型对请求进行签名,并把token加入req中
func (ath *Credentials) AddToken(t TokenType, req *http.Request) error {
switch t {
case TokenQiniu:
token, sErr := ath.SignRequestV2(req)
if sErr != nil {
return sErr
}
req.Header.Add("Authorization", AuthorizationPrefixQiniu+token)
default:
token, err := ath.SignRequest(req)
if err != nil {
return err
}
req.Header.Add("Authorization", AuthorizationPrefixQBox+token)
}
return nil
}
// SignWithData 对数据进行签名,一般用于上传凭证的生成用途
func (ath *Credentials) SignWithData(b []byte) (token string) {
encodedData := base64.URLEncoding.EncodeToString(b)
sign := ath.Sign([]byte(encodedData))
return fmt.Sprintf("%s:%s", sign, encodedData)
}
// IsIAMKey 判断AccessKey是否为IAM的Key
func (ath *Credentials) IsIAMKey() bool {
var accessKey string
if ath == nil {
if cred := Default(); cred != nil {
accessKey = cred.AccessKey
}
} else {
accessKey = ath.AccessKey
}
return len(accessKey) == IAMKeyLen*4/3 &&
strings.HasPrefix(accessKey, IAMKeyPrefix)
}
func collectData(req *http.Request) (data []byte, err error) {
u := req.URL
s := u.Path
if u.RawQuery != "" {
s += "?"
s += u.RawQuery
}
s += "\n"
data = []byte(s)
if incBody(req) {
s2, rErr := api.BytesFromRequest(req)
if rErr != nil {
err = rErr
return
}
req.Body = internal_io.NewBytesNopCloser(s2)
data = append(data, s2...)
}
return
}
type (
xQiniuHeaderItem struct {
HeaderName string
HeaderValue string
}
xQiniuHeaders []xQiniuHeaderItem
)
func (headers xQiniuHeaders) Len() int {
return len(headers)
}
func (headers xQiniuHeaders) Less(i, j int) bool {
if headers[i].HeaderName < headers[j].HeaderName {
return true
} else if headers[i].HeaderName > headers[j].HeaderName {
return false
} else {
return headers[i].HeaderValue < headers[j].HeaderValue
}
}
func (headers xQiniuHeaders) Swap(i, j int) {
headers[i], headers[j] = headers[j], headers[i]
}
func collectDataV2(req *http.Request) (data []byte, err error) {
u := req.URL
//write method path?query
s := fmt.Sprintf("%s %s", req.Method, u.Path)
if u.RawQuery != "" {
s += "?"
s += u.RawQuery
}
//write host and post
s += "\nHost: " + req.Host + "\n"
//write content type
contentType := req.Header.Get("Content-Type")
if contentType == "" {
contentType = "application/x-www-form-urlencoded"
req.Header.Set("Content-Type", contentType)
}
s += fmt.Sprintf("Content-Type: %s\n", contentType)
xQiniuHeaders := make(xQiniuHeaders, 0, len(req.Header))
for headerName := range req.Header {
if len(headerName) > len("X-Qiniu-") && strings.HasPrefix(headerName, "X-Qiniu-") {
xQiniuHeaders = append(xQiniuHeaders, xQiniuHeaderItem{
HeaderName: textproto.CanonicalMIMEHeaderKey(headerName),
HeaderValue: req.Header.Get(headerName),
})
}
}
if len(xQiniuHeaders) > 0 {
sort.Sort(xQiniuHeaders)
for _, xQiniuHeader := range xQiniuHeaders {
s += fmt.Sprintf("%s: %s\n", xQiniuHeader.HeaderName, xQiniuHeader.HeaderValue)
}
}
s += "\n"
data = []byte(s)
//write body
if incBodyV2(req) {
s2, rErr := api.BytesFromRequest(req)
if rErr != nil {
err = rErr
return
}
req.Body = internal_io.NewBytesNopCloser(s2)
data = append(data, s2...)
}
return
}
// SignRequest 对数据进行签名,一般用于管理凭证的生成
func (ath *Credentials) SignRequest(req *http.Request) (token string, err error) {
data, err := collectData(req)
if err != nil {
return
}
token = ath.Sign(data)
return
}
// SignRequestV2 对数据进行签名,一般用于高级管理凭证的生成
func (ath *Credentials) SignRequestV2(req *http.Request) (token string, err error) {
data, err := collectDataV2(req)
if err != nil {
return
}
token = ath.Sign(data)
return
}
// 管理凭证生成时,是否同时对request body进行签名
func incBody(req *http.Request) bool {
return req.Body != nil && req.Header.Get("Content-Type") == conf.CONTENT_TYPE_FORM
}
func incBodyV2(req *http.Request) bool {
contentType := req.Header.Get("Content-Type")
return req.Body != nil && (contentType == conf.CONTENT_TYPE_FORM || contentType == conf.CONTENT_TYPE_JSON)
}
// VerifyCallback 验证上传回调请求是否来自七牛
func (ath *Credentials) VerifyCallback(req *http.Request) (bool, error) {
auth := req.Header.Get("Authorization")
if auth == "" {
return false, nil
}
if strings.HasPrefix(auth, AuthorizationPrefixQiniu) {
token, err := ath.SignRequestV2(req)
if err != nil {
return false, err
}
return auth == AuthorizationPrefixQiniu+token, nil
} else {
token, err := ath.SignRequest(req)
if err != nil {
return false, err
}
return auth == AuthorizationPrefixQBox+token, nil
}
}
// Get 实现 CredentialsProvider 接口
func (c *Credentials) Get(ctx context.Context) (*Credentials, error) {
return c, nil
}