You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

306 lines
8.5 KiB

  1. package cos
  2. import (
  3. "crypto/hmac"
  4. "crypto/sha1"
  5. "fmt"
  6. "hash"
  7. "net/http"
  8. "net/url"
  9. "sort"
  10. "strings"
  11. "sync"
  12. "time"
  13. )
  14. const sha1SignAlgorithm = "sha1"
  15. const privateHeaderPrefix = "x-cos-"
  16. const defaultAuthExpire = time.Hour
  17. // 需要校验的 Headers 列表
  18. var needSignHeaders = map[string]bool{
  19. "host": true,
  20. "range": true,
  21. "x-cos-acl": true,
  22. "x-cos-grant-read": true,
  23. "x-cos-grant-write": true,
  24. "x-cos-grant-full-control": true,
  25. "response-content-type": true,
  26. "response-content-language": true,
  27. "response-expires": true,
  28. "response-cache-control": true,
  29. "response-content-disposition": true,
  30. "response-content-encoding": true,
  31. "cache-control": true,
  32. "content-disposition": true,
  33. "content-encoding": true,
  34. "content-type": true,
  35. "content-length": true,
  36. "content-md5": true,
  37. "expect": true,
  38. "expires": true,
  39. "x-cos-content-sha1": true,
  40. "x-cos-storage-class": true,
  41. "if-modified-since": true,
  42. "origin": true,
  43. "access-control-request-method": true,
  44. "access-control-request-headers": true,
  45. "x-cos-object-type": true,
  46. }
  47. func safeURLEncode(s string) string {
  48. s = encodeURIComponent(s)
  49. s = strings.Replace(s, "!", "%21", -1)
  50. s = strings.Replace(s, "'", "%27", -1)
  51. s = strings.Replace(s, "(", "%28", -1)
  52. s = strings.Replace(s, ")", "%29", -1)
  53. s = strings.Replace(s, "*", "%2A", -1)
  54. return s
  55. }
  56. type valuesSignMap map[string][]string
  57. func (vs valuesSignMap) Add(key, value string) {
  58. key = strings.ToLower(key)
  59. vs[key] = append(vs[key], value)
  60. }
  61. func (vs valuesSignMap) Encode() string {
  62. var keys []string
  63. for k := range vs {
  64. keys = append(keys, k)
  65. }
  66. sort.Strings(keys)
  67. var pairs []string
  68. for _, k := range keys {
  69. items := vs[k]
  70. sort.Strings(items)
  71. for _, val := range items {
  72. pairs = append(
  73. pairs,
  74. fmt.Sprintf("%s=%s", safeURLEncode(k), safeURLEncode(val)))
  75. }
  76. }
  77. return strings.Join(pairs, "&")
  78. }
  79. // AuthTime 用于生成签名所需的 q-sign-time 和 q-key-time 相关参数
  80. type AuthTime struct {
  81. SignStartTime time.Time
  82. SignEndTime time.Time
  83. KeyStartTime time.Time
  84. KeyEndTime time.Time
  85. }
  86. // NewAuthTime 生成 AuthTime 的便捷函数
  87. //
  88. // expire: 从现在开始多久过期.
  89. func NewAuthTime(expire time.Duration) *AuthTime {
  90. signStartTime := time.Now()
  91. keyStartTime := signStartTime
  92. signEndTime := signStartTime.Add(expire)
  93. keyEndTime := signEndTime
  94. return &AuthTime{
  95. SignStartTime: signStartTime,
  96. SignEndTime: signEndTime,
  97. KeyStartTime: keyStartTime,
  98. KeyEndTime: keyEndTime,
  99. }
  100. }
  101. // signString return q-sign-time string
  102. func (a *AuthTime) signString() string {
  103. return fmt.Sprintf("%d;%d", a.SignStartTime.Unix(), a.SignEndTime.Unix())
  104. }
  105. // keyString return q-key-time string
  106. func (a *AuthTime) keyString() string {
  107. return fmt.Sprintf("%d;%d", a.KeyStartTime.Unix(), a.KeyEndTime.Unix())
  108. }
  109. // newAuthorization 通过一系列步骤生成最终需要的 Authorization 字符串
  110. func newAuthorization(secretID, secretKey string, req *http.Request, authTime *AuthTime) string {
  111. signTime := authTime.signString()
  112. keyTime := authTime.keyString()
  113. signKey := calSignKey(secretKey, keyTime)
  114. req.Header.Set("Host", req.Host)
  115. formatHeaders := *new(string)
  116. signedHeaderList := *new([]string)
  117. formatHeaders, signedHeaderList = genFormatHeaders(req.Header)
  118. formatParameters, signedParameterList := genFormatParameters(req.URL.Query())
  119. formatString := genFormatString(req.Method, *req.URL, formatParameters, formatHeaders)
  120. stringToSign := calStringToSign(sha1SignAlgorithm, keyTime, formatString)
  121. signature := calSignature(signKey, stringToSign)
  122. return genAuthorization(
  123. secretID, signTime, keyTime, signature, signedHeaderList,
  124. signedParameterList,
  125. )
  126. }
  127. // AddAuthorizationHeader 给 req 增加签名信息
  128. func AddAuthorizationHeader(secretID, secretKey string, sessionToken string, req *http.Request, authTime *AuthTime) {
  129. if secretID == "" {
  130. return
  131. }
  132. auth := newAuthorization(secretID, secretKey, req,
  133. authTime,
  134. )
  135. if len(sessionToken) > 0 {
  136. req.Header.Set("x-cos-security-token", sessionToken)
  137. }
  138. req.Header.Set("Authorization", auth)
  139. }
  140. // calSignKey 计算 SignKey
  141. func calSignKey(secretKey, keyTime string) string {
  142. digest := calHMACDigest(secretKey, keyTime, sha1SignAlgorithm)
  143. return fmt.Sprintf("%x", digest)
  144. }
  145. // calStringToSign 计算 StringToSign
  146. func calStringToSign(signAlgorithm, signTime, formatString string) string {
  147. h := sha1.New()
  148. h.Write([]byte(formatString))
  149. return fmt.Sprintf("%s\n%s\n%x\n", signAlgorithm, signTime, h.Sum(nil))
  150. }
  151. // calSignature 计算 Signature
  152. func calSignature(signKey, stringToSign string) string {
  153. digest := calHMACDigest(signKey, stringToSign, sha1SignAlgorithm)
  154. return fmt.Sprintf("%x", digest)
  155. }
  156. // genAuthorization 生成 Authorization
  157. func genAuthorization(secretID, signTime, keyTime, signature string, signedHeaderList, signedParameterList []string) string {
  158. return strings.Join([]string{
  159. "q-sign-algorithm=" + sha1SignAlgorithm,
  160. "q-ak=" + secretID,
  161. "q-sign-time=" + signTime,
  162. "q-key-time=" + keyTime,
  163. "q-header-list=" + strings.Join(signedHeaderList, ";"),
  164. "q-url-param-list=" + strings.Join(signedParameterList, ";"),
  165. "q-signature=" + signature,
  166. }, "&")
  167. }
  168. // genFormatString 生成 FormatString
  169. func genFormatString(method string, uri url.URL, formatParameters, formatHeaders string) string {
  170. formatMethod := strings.ToLower(method)
  171. formatURI := uri.Path
  172. return fmt.Sprintf("%s\n%s\n%s\n%s\n", formatMethod, formatURI,
  173. formatParameters, formatHeaders,
  174. )
  175. }
  176. // genFormatParameters 生成 FormatParameters 和 SignedParameterList
  177. // instead of the url.Values{}
  178. func genFormatParameters(parameters url.Values) (formatParameters string, signedParameterList []string) {
  179. ps := valuesSignMap{}
  180. for key, values := range parameters {
  181. key = strings.ToLower(key)
  182. for _, value := range values {
  183. ps.Add(key, value)
  184. signedParameterList = append(signedParameterList, key)
  185. }
  186. }
  187. //formatParameters = strings.ToLower(ps.Encode())
  188. formatParameters = ps.Encode()
  189. sort.Strings(signedParameterList)
  190. return
  191. }
  192. // genFormatHeaders 生成 FormatHeaders 和 SignedHeaderList
  193. func genFormatHeaders(headers http.Header) (formatHeaders string, signedHeaderList []string) {
  194. hs := valuesSignMap{}
  195. for key, values := range headers {
  196. key = strings.ToLower(key)
  197. for _, value := range values {
  198. if isSignHeader(key) {
  199. hs.Add(key, value)
  200. signedHeaderList = append(signedHeaderList, key)
  201. }
  202. }
  203. }
  204. formatHeaders = hs.Encode()
  205. sort.Strings(signedHeaderList)
  206. return
  207. }
  208. // HMAC 签名
  209. func calHMACDigest(key, msg, signMethod string) []byte {
  210. var hashFunc func() hash.Hash
  211. switch signMethod {
  212. case "sha1":
  213. hashFunc = sha1.New
  214. default:
  215. hashFunc = sha1.New
  216. }
  217. h := hmac.New(hashFunc, []byte(key))
  218. h.Write([]byte(msg))
  219. return h.Sum(nil)
  220. }
  221. func isSignHeader(key string) bool {
  222. for k, v := range needSignHeaders {
  223. if key == k && v {
  224. return true
  225. }
  226. }
  227. return strings.HasPrefix(key, privateHeaderPrefix)
  228. }
  229. // AuthorizationTransport 给请求增加 Authorization header
  230. type AuthorizationTransport struct {
  231. SecretID string
  232. SecretKey string
  233. SessionToken string
  234. rwLocker sync.RWMutex
  235. // 签名多久过期
  236. Expire time.Duration
  237. Transport http.RoundTripper
  238. }
  239. // SetCredential update the SecretID(ak), SercretKey(sk), sessiontoken
  240. func (t *AuthorizationTransport) SetCredential(ak, sk, token string) {
  241. t.rwLocker.Lock()
  242. defer t.rwLocker.Unlock()
  243. t.SecretID = ak
  244. t.SecretKey = sk
  245. t.SessionToken = token
  246. }
  247. // GetCredential get the ak, sk, token
  248. func (t *AuthorizationTransport) GetCredential() (string, string, string) {
  249. t.rwLocker.RLock()
  250. defer t.rwLocker.RUnlock()
  251. return t.SecretID, t.SecretKey, t.SessionToken
  252. }
  253. // RoundTrip implements the RoundTripper interface.
  254. func (t *AuthorizationTransport) RoundTrip(req *http.Request) (*http.Response, error) {
  255. req = cloneRequest(req) // per RoundTrip contract
  256. if t.Expire == time.Duration(0) {
  257. t.Expire = defaultAuthExpire
  258. }
  259. ak, sk, token := t.GetCredential()
  260. // 增加 Authorization header
  261. authTime := NewAuthTime(t.Expire)
  262. AddAuthorizationHeader(ak, sk, token, req, authTime)
  263. resp, err := t.transport().RoundTrip(req)
  264. return resp, err
  265. }
  266. func (t *AuthorizationTransport) transport() http.RoundTripper {
  267. if t.Transport != nil {
  268. return t.Transport
  269. }
  270. return http.DefaultTransport
  271. }