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.

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