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.

305 lines
8.4 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. formatHeaders := *new(string)
  115. signedHeaderList := *new([]string)
  116. formatHeaders, signedHeaderList = genFormatHeaders(req.Header)
  117. formatParameters, signedParameterList := genFormatParameters(req.URL.Query())
  118. formatString := genFormatString(req.Method, *req.URL, formatParameters, formatHeaders)
  119. stringToSign := calStringToSign(sha1SignAlgorithm, keyTime, formatString)
  120. signature := calSignature(signKey, stringToSign)
  121. return genAuthorization(
  122. secretID, signTime, keyTime, signature, signedHeaderList,
  123. signedParameterList,
  124. )
  125. }
  126. // AddAuthorizationHeader 给 req 增加签名信息
  127. func AddAuthorizationHeader(secretID, secretKey string, sessionToken string, req *http.Request, authTime *AuthTime) {
  128. if secretID == "" {
  129. return
  130. }
  131. auth := newAuthorization(secretID, secretKey, req,
  132. authTime,
  133. )
  134. if len(sessionToken) > 0 {
  135. req.Header.Set("x-cos-security-token", sessionToken)
  136. }
  137. req.Header.Set("Authorization", auth)
  138. }
  139. // calSignKey 计算 SignKey
  140. func calSignKey(secretKey, keyTime string) string {
  141. digest := calHMACDigest(secretKey, keyTime, sha1SignAlgorithm)
  142. return fmt.Sprintf("%x", digest)
  143. }
  144. // calStringToSign 计算 StringToSign
  145. func calStringToSign(signAlgorithm, signTime, formatString string) string {
  146. h := sha1.New()
  147. h.Write([]byte(formatString))
  148. return fmt.Sprintf("%s\n%s\n%x\n", signAlgorithm, signTime, h.Sum(nil))
  149. }
  150. // calSignature 计算 Signature
  151. func calSignature(signKey, stringToSign string) string {
  152. digest := calHMACDigest(signKey, stringToSign, sha1SignAlgorithm)
  153. return fmt.Sprintf("%x", digest)
  154. }
  155. // genAuthorization 生成 Authorization
  156. func genAuthorization(secretID, signTime, keyTime, signature string, signedHeaderList, signedParameterList []string) string {
  157. return strings.Join([]string{
  158. "q-sign-algorithm=" + sha1SignAlgorithm,
  159. "q-ak=" + secretID,
  160. "q-sign-time=" + signTime,
  161. "q-key-time=" + keyTime,
  162. "q-header-list=" + strings.Join(signedHeaderList, ";"),
  163. "q-url-param-list=" + strings.Join(signedParameterList, ";"),
  164. "q-signature=" + signature,
  165. }, "&")
  166. }
  167. // genFormatString 生成 FormatString
  168. func genFormatString(method string, uri url.URL, formatParameters, formatHeaders string) string {
  169. formatMethod := strings.ToLower(method)
  170. formatURI := uri.Path
  171. return fmt.Sprintf("%s\n%s\n%s\n%s\n", formatMethod, formatURI,
  172. formatParameters, formatHeaders,
  173. )
  174. }
  175. // genFormatParameters 生成 FormatParameters 和 SignedParameterList
  176. // instead of the url.Values{}
  177. func genFormatParameters(parameters url.Values) (formatParameters string, signedParameterList []string) {
  178. ps := valuesSignMap{}
  179. for key, values := range parameters {
  180. key = strings.ToLower(key)
  181. for _, value := range values {
  182. ps.Add(key, value)
  183. signedParameterList = append(signedParameterList, key)
  184. }
  185. }
  186. //formatParameters = strings.ToLower(ps.Encode())
  187. formatParameters = ps.Encode()
  188. sort.Strings(signedParameterList)
  189. return
  190. }
  191. // genFormatHeaders 生成 FormatHeaders 和 SignedHeaderList
  192. func genFormatHeaders(headers http.Header) (formatHeaders string, signedHeaderList []string) {
  193. hs := valuesSignMap{}
  194. for key, values := range headers {
  195. key = strings.ToLower(key)
  196. for _, value := range values {
  197. if isSignHeader(key) {
  198. hs.Add(key, value)
  199. signedHeaderList = append(signedHeaderList, key)
  200. }
  201. }
  202. }
  203. formatHeaders = hs.Encode()
  204. sort.Strings(signedHeaderList)
  205. return
  206. }
  207. // HMAC 签名
  208. func calHMACDigest(key, msg, signMethod string) []byte {
  209. var hashFunc func() hash.Hash
  210. switch signMethod {
  211. case "sha1":
  212. hashFunc = sha1.New
  213. default:
  214. hashFunc = sha1.New
  215. }
  216. h := hmac.New(hashFunc, []byte(key))
  217. h.Write([]byte(msg))
  218. return h.Sum(nil)
  219. }
  220. func isSignHeader(key string) bool {
  221. for k, v := range needSignHeaders {
  222. if key == k && v {
  223. return true
  224. }
  225. }
  226. return strings.HasPrefix(key, privateHeaderPrefix)
  227. }
  228. // AuthorizationTransport 给请求增加 Authorization header
  229. type AuthorizationTransport struct {
  230. SecretID string
  231. SecretKey string
  232. SessionToken string
  233. rwLocker sync.RWMutex
  234. // 签名多久过期
  235. Expire time.Duration
  236. Transport http.RoundTripper
  237. }
  238. // SetCredential update the SecretID(ak), SercretKey(sk), sessiontoken
  239. func (t *AuthorizationTransport) SetCredential(ak, sk, token string) {
  240. t.rwLocker.Lock()
  241. defer t.rwLocker.Unlock()
  242. t.SecretID = ak
  243. t.SecretKey = sk
  244. t.SessionToken = token
  245. }
  246. // GetCredential get the ak, sk, token
  247. func (t *AuthorizationTransport) GetCredential() (string, string, string) {
  248. t.rwLocker.RLock()
  249. defer t.rwLocker.RUnlock()
  250. return t.SecretID, t.SecretKey, t.SessionToken
  251. }
  252. // RoundTrip implements the RoundTripper interface.
  253. func (t *AuthorizationTransport) RoundTrip(req *http.Request) (*http.Response, error) {
  254. req = cloneRequest(req) // per RoundTrip contract
  255. if t.Expire == time.Duration(0) {
  256. t.Expire = defaultAuthExpire
  257. }
  258. ak, sk, token := t.GetCredential()
  259. // 增加 Authorization header
  260. authTime := NewAuthTime(t.Expire)
  261. AddAuthorizationHeader(ak, sk, token, req, authTime)
  262. resp, err := t.transport().RoundTrip(req)
  263. return resp, err
  264. }
  265. func (t *AuthorizationTransport) transport() http.RoundTripper {
  266. if t.Transport != nil {
  267. return t.Transport
  268. }
  269. return http.DefaultTransport
  270. }