signer.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package baidu
  15. import (
  16. "bytes"
  17. "crypto/hmac"
  18. "crypto/sha256"
  19. "encoding/hex"
  20. "fmt"
  21. "net/http"
  22. "net/url"
  23. "sort"
  24. "strings"
  25. "time"
  26. "yunion.io/x/pkg/errors"
  27. )
  28. func uriEncode(uri string, encodeSlash bool) string {
  29. var byte_buf bytes.Buffer
  30. for _, b := range []byte(uri) {
  31. if (b >= 'A' && b <= 'Z') || (b >= 'a' && b <= 'z') || (b >= '0' && b <= '9') ||
  32. b == '-' || b == '_' || b == '.' || b == '~' || (b == '/' && !encodeSlash) {
  33. byte_buf.WriteByte(b)
  34. } else {
  35. byte_buf.WriteString(fmt.Sprintf("%%%02X", b))
  36. }
  37. }
  38. return byte_buf.String()
  39. }
  40. func getCanonicalURIPath(path string) string {
  41. if len(path) == 0 {
  42. return "/"
  43. }
  44. canonical_path := path
  45. if strings.HasPrefix(path, "/") {
  46. canonical_path = path[1:]
  47. }
  48. canonical_path = uriEncode(canonical_path, false)
  49. return "/" + canonical_path
  50. }
  51. func getCanonicalQueryString(params url.Values) string {
  52. if len(params) == 0 {
  53. return ""
  54. }
  55. result := make([]string, 0, len(params))
  56. for k, v := range params {
  57. if strings.EqualFold(k, "authorization") {
  58. continue
  59. }
  60. item := ""
  61. if len(v) == 0 {
  62. item = fmt.Sprintf("%s=", uriEncode(k, true))
  63. } else {
  64. item = fmt.Sprintf("%s=%s", uriEncode(k, true), uriEncode(params.Get(k), true))
  65. }
  66. result = append(result, item)
  67. }
  68. sort.Strings(result)
  69. return strings.Join(result, "&")
  70. }
  71. func getCanonicalHeaders(headers http.Header,
  72. headersToSign map[string]bool) (string, []string) {
  73. canonicalHeaders := make([]string, 0, len(headers))
  74. signHeaders := make([]string, 0, len(headersToSign))
  75. for k := range headers {
  76. headKey := strings.ToLower(k)
  77. if headKey == strings.ToLower("authorization") {
  78. continue
  79. }
  80. _, headExists := headersToSign[headKey]
  81. if headExists ||
  82. (strings.HasPrefix(headKey, "x-bce-") &&
  83. (headKey != "x-bce-request-id")) {
  84. headVal := strings.TrimSpace(headers.Get(k))
  85. encoded := uriEncode(headKey, true) + ":" + uriEncode(headVal, true)
  86. canonicalHeaders = append(canonicalHeaders, encoded)
  87. signHeaders = append(signHeaders, headKey)
  88. }
  89. }
  90. sort.Strings(canonicalHeaders)
  91. sort.Strings(signHeaders)
  92. return strings.Join(canonicalHeaders, "\n"), signHeaders
  93. }
  94. func (cli *SBaiduClient) sign(uri *url.URL, method string, headers http.Header) (string, error) {
  95. return cli._sign(uri, method, headers, 1800)
  96. }
  97. func (cli *SBaiduClient) _sign(uri *url.URL, method string, headers http.Header, expired int) (string, error) {
  98. signKeyInfo := fmt.Sprintf("%s/%s/%s/%d",
  99. "bce-auth-v1",
  100. cli.accessKeyId,
  101. time.Now().UTC().Format(ISO8601),
  102. expired)
  103. hasher := hmac.New(sha256.New, []byte(cli.accessKeySecret))
  104. hasher.Write([]byte(signKeyInfo))
  105. signKey := hex.EncodeToString(hasher.Sum(nil))
  106. canonicalUri := getCanonicalURIPath(uri.Path)
  107. params, err := url.ParseQuery(uri.RawQuery)
  108. if err != nil {
  109. return "", errors.Wrapf(err, "ParseQuery")
  110. }
  111. canonicalQueryString := getCanonicalQueryString(params)
  112. canonicalHeaders, signedHeadersArr := getCanonicalHeaders(headers, map[string]bool{
  113. "host": true,
  114. "Content-Length": true,
  115. "Content-Type": true,
  116. "Content-Md5": true,
  117. })
  118. signedHeaders := ""
  119. if len(signedHeadersArr) > 0 {
  120. sort.Strings(signedHeadersArr)
  121. signedHeaders = strings.Join(signedHeadersArr, ";")
  122. }
  123. canonicalParts := []string{method, canonicalUri, canonicalQueryString, canonicalHeaders}
  124. canonicalReq := strings.Join(canonicalParts, "\n")
  125. hasher = hmac.New(sha256.New, []byte(signKey))
  126. hasher.Write([]byte(canonicalReq))
  127. signature := hex.EncodeToString(hasher.Sum(nil))
  128. return signKeyInfo + "/" + signedHeaders + "/" + signature, nil
  129. }