service.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  1. // This file is auto-generated, don't edit it. Thanks.
  2. /**
  3. * This is for OpenApi Util
  4. */
  5. package service
  6. import (
  7. "bytes"
  8. "crypto"
  9. "crypto/hmac"
  10. "crypto/rand"
  11. "crypto/rsa"
  12. "crypto/sha1"
  13. "crypto/sha256"
  14. "crypto/x509"
  15. "encoding/base64"
  16. "encoding/hex"
  17. "encoding/json"
  18. "encoding/pem"
  19. "errors"
  20. "fmt"
  21. "hash"
  22. "io"
  23. "net/http"
  24. "net/textproto"
  25. "net/url"
  26. "reflect"
  27. "sort"
  28. "strconv"
  29. "strings"
  30. "time"
  31. util "github.com/alibabacloud-go/tea-utils/service"
  32. "github.com/alibabacloud-go/tea/tea"
  33. "github.com/tjfoc/gmsm/sm3"
  34. )
  35. const (
  36. PEM_BEGIN = "-----BEGIN RSA PRIVATE KEY-----\n"
  37. PEM_END = "\n-----END RSA PRIVATE KEY-----"
  38. )
  39. type Sorter struct {
  40. Keys []string
  41. Vals []string
  42. }
  43. func newSorter(m map[string]string) *Sorter {
  44. hs := &Sorter{
  45. Keys: make([]string, 0, len(m)),
  46. Vals: make([]string, 0, len(m)),
  47. }
  48. for k, v := range m {
  49. hs.Keys = append(hs.Keys, k)
  50. hs.Vals = append(hs.Vals, v)
  51. }
  52. return hs
  53. }
  54. // Sort is an additional function for function SignHeader.
  55. func (hs *Sorter) Sort() {
  56. sort.Sort(hs)
  57. }
  58. // Len is an additional function for function SignHeader.
  59. func (hs *Sorter) Len() int {
  60. return len(hs.Vals)
  61. }
  62. // Less is an additional function for function SignHeader.
  63. func (hs *Sorter) Less(i, j int) bool {
  64. return bytes.Compare([]byte(hs.Keys[i]), []byte(hs.Keys[j])) < 0
  65. }
  66. // Swap is an additional function for function SignHeader.
  67. func (hs *Sorter) Swap(i, j int) {
  68. hs.Vals[i], hs.Vals[j] = hs.Vals[j], hs.Vals[i]
  69. hs.Keys[i], hs.Keys[j] = hs.Keys[j], hs.Keys[i]
  70. }
  71. /**
  72. * Convert all params of body other than type of readable into content
  73. * @param body source Model
  74. * @param content target Model
  75. * @return void
  76. */
  77. func Convert(body interface{}, content interface{}) {
  78. res := make(map[string]interface{})
  79. val := reflect.ValueOf(body).Elem()
  80. dataType := val.Type()
  81. for i := 0; i < dataType.NumField(); i++ {
  82. field := dataType.Field(i)
  83. name, _ := field.Tag.Lookup("json")
  84. name = strings.Split(name, ",omitempty")[0]
  85. _, ok := val.Field(i).Interface().(io.Reader)
  86. if !ok {
  87. res[name] = val.Field(i).Interface()
  88. }
  89. }
  90. byt, _ := json.Marshal(res)
  91. json.Unmarshal(byt, content)
  92. }
  93. /**
  94. * Get the string to be signed according to request
  95. * @param request which contains signed messages
  96. * @return the signed string
  97. */
  98. func GetStringToSign(request *tea.Request) (_result *string) {
  99. return tea.String(getStringToSign(request))
  100. }
  101. func getStringToSign(request *tea.Request) string {
  102. resource := tea.StringValue(request.Pathname)
  103. queryParams := request.Query
  104. // sort QueryParams by key
  105. var queryKeys []string
  106. for key := range queryParams {
  107. queryKeys = append(queryKeys, key)
  108. }
  109. sort.Strings(queryKeys)
  110. tmp := ""
  111. for i := 0; i < len(queryKeys); i++ {
  112. queryKey := queryKeys[i]
  113. v := tea.StringValue(queryParams[queryKey])
  114. if v != "" {
  115. tmp = tmp + "&" + queryKey + "=" + v
  116. } else {
  117. tmp = tmp + "&" + queryKey
  118. }
  119. }
  120. if tmp != "" {
  121. tmp = strings.TrimLeft(tmp, "&")
  122. resource = resource + "?" + tmp
  123. }
  124. return getSignedStr(request, resource)
  125. }
  126. func getSignedStr(req *tea.Request, canonicalizedResource string) string {
  127. temp := make(map[string]string)
  128. for k, v := range req.Headers {
  129. if strings.HasPrefix(strings.ToLower(k), "x-acs-") {
  130. temp[strings.ToLower(k)] = tea.StringValue(v)
  131. }
  132. }
  133. hs := newSorter(temp)
  134. // Sort the temp by the ascending order
  135. hs.Sort()
  136. // Get the canonicalizedOSSHeaders
  137. canonicalizedOSSHeaders := ""
  138. for i := range hs.Keys {
  139. canonicalizedOSSHeaders += hs.Keys[i] + ":" + hs.Vals[i] + "\n"
  140. }
  141. // Give other parameters values
  142. // when sign URL, date is expires
  143. date := tea.StringValue(req.Headers["date"])
  144. accept := tea.StringValue(req.Headers["accept"])
  145. contentType := tea.StringValue(req.Headers["content-type"])
  146. contentMd5 := tea.StringValue(req.Headers["content-md5"])
  147. signStr := tea.StringValue(req.Method) + "\n" + accept + "\n" + contentMd5 + "\n" + contentType + "\n" + date + "\n" + canonicalizedOSSHeaders + canonicalizedResource
  148. return signStr
  149. }
  150. /**
  151. * Get signature according to stringToSign, secret
  152. * @param stringToSign the signed string
  153. * @param secret accesskey secret
  154. * @return the signature
  155. */
  156. func GetROASignature(stringToSign *string, secret *string) (_result *string) {
  157. h := hmac.New(func() hash.Hash { return sha1.New() }, []byte(tea.StringValue(secret)))
  158. io.WriteString(h, tea.StringValue(stringToSign))
  159. signedStr := base64.StdEncoding.EncodeToString(h.Sum(nil))
  160. return tea.String(signedStr)
  161. }
  162. func GetEndpoint(endpoint *string, server *bool, endpointType *string) *string {
  163. if tea.StringValue(endpointType) == "internal" {
  164. strs := strings.Split(tea.StringValue(endpoint), ".")
  165. strs[0] += "-internal"
  166. endpoint = tea.String(strings.Join(strs, "."))
  167. }
  168. if tea.BoolValue(server) && tea.StringValue(endpointType) == "accelerate" {
  169. return tea.String("oss-accelerate.aliyuncs.com")
  170. }
  171. return endpoint
  172. }
  173. func HexEncode(raw []byte) *string {
  174. return tea.String(hex.EncodeToString(raw))
  175. }
  176. func Hash(raw []byte, signatureAlgorithm *string) []byte {
  177. signType := tea.StringValue(signatureAlgorithm)
  178. if signType == "ACS3-HMAC-SHA256" || signType == "ACS3-RSA-SHA256" {
  179. h := sha256.New()
  180. h.Write(raw)
  181. return h.Sum(nil)
  182. } else if signType == "ACS3-HMAC-SM3" {
  183. h := sm3.New()
  184. h.Write(raw)
  185. return h.Sum(nil)
  186. }
  187. return nil
  188. }
  189. func GetEncodePath(path *string) *string {
  190. uri := tea.StringValue(path)
  191. strs := strings.Split(uri, "/")
  192. for i, v := range strs {
  193. strs[i] = url.QueryEscape(v)
  194. }
  195. uri = strings.Join(strs, "/")
  196. uri = strings.Replace(uri, "+", "%20", -1)
  197. uri = strings.Replace(uri, "*", "%2A", -1)
  198. uri = strings.Replace(uri, "%7E", "~", -1)
  199. return tea.String(uri)
  200. }
  201. func GetAuthorization(request *tea.Request, signatureAlgorithm, payload, acesskey, secret *string) *string {
  202. canonicalURI := tea.StringValue(request.Pathname)
  203. if canonicalURI == "" {
  204. canonicalURI = "/"
  205. }
  206. canonicalURI = strings.Replace(canonicalURI, "+", "%20", -1)
  207. canonicalURI = strings.Replace(canonicalURI, "*", "%2A", -1)
  208. canonicalURI = strings.Replace(canonicalURI, "%7E", "~", -1)
  209. method := tea.StringValue(request.Method)
  210. canonicalQueryString := getCanonicalQueryString(request.Query)
  211. canonicalheaders, signedHeaders := getCanonicalHeaders(request.Headers)
  212. canonicalRequest := method + "\n" + canonicalURI + "\n" + canonicalQueryString + "\n" + canonicalheaders + "\n" +
  213. strings.Join(signedHeaders, ";") + "\n" + tea.StringValue(payload)
  214. signType := tea.StringValue(signatureAlgorithm)
  215. StringToSign := signType + "\n" + tea.StringValue(HexEncode(Hash([]byte(canonicalRequest), signatureAlgorithm)))
  216. signature := tea.StringValue(HexEncode(SignatureMethod(tea.StringValue(secret), StringToSign, signType)))
  217. auth := signType + " Credential=" + tea.StringValue(acesskey) + ",SignedHeaders=" +
  218. strings.Join(signedHeaders, ";") + ",Signature=" + signature
  219. return tea.String(auth)
  220. }
  221. func SignatureMethod(secret, source, signatureAlgorithm string) []byte {
  222. if signatureAlgorithm == "ACS3-HMAC-SHA256" {
  223. h := hmac.New(sha256.New, []byte(secret))
  224. h.Write([]byte(source))
  225. return h.Sum(nil)
  226. } else if signatureAlgorithm == "ACS3-HMAC-SM3" {
  227. h := hmac.New(sm3.New, []byte(secret))
  228. h.Write([]byte(source))
  229. return h.Sum(nil)
  230. } else if signatureAlgorithm == "ACS3-RSA-SHA256" {
  231. return rsaSign(source, secret)
  232. }
  233. return nil
  234. }
  235. func rsaSign(content, secret string) []byte {
  236. h := crypto.SHA256.New()
  237. h.Write([]byte(content))
  238. hashed := h.Sum(nil)
  239. priv, err := parsePrivateKey(secret)
  240. if err != nil {
  241. return nil
  242. }
  243. sign, err := rsa.SignPKCS1v15(rand.Reader, priv, crypto.SHA256, hashed)
  244. if err != nil {
  245. return nil
  246. }
  247. return sign
  248. }
  249. func parsePrivateKey(privateKey string) (*rsa.PrivateKey, error) {
  250. privateKey = formatPrivateKey(privateKey)
  251. block, _ := pem.Decode([]byte(privateKey))
  252. if block == nil {
  253. return nil, errors.New("PrivateKey is invalid")
  254. }
  255. priKey, err := x509.ParsePKCS8PrivateKey(block.Bytes)
  256. if err != nil {
  257. return nil, err
  258. }
  259. switch priKey.(type) {
  260. case *rsa.PrivateKey:
  261. return priKey.(*rsa.PrivateKey), nil
  262. default:
  263. return nil, nil
  264. }
  265. }
  266. func formatPrivateKey(privateKey string) string {
  267. if !strings.HasPrefix(privateKey, PEM_BEGIN) {
  268. privateKey = PEM_BEGIN + privateKey
  269. }
  270. if !strings.HasSuffix(privateKey, PEM_END) {
  271. privateKey += PEM_END
  272. }
  273. return privateKey
  274. }
  275. func getCanonicalHeaders(headers map[string]*string) (string, []string) {
  276. tmp := make(map[string]string)
  277. tmpHeader := http.Header{}
  278. for k, v := range headers {
  279. if strings.HasPrefix(strings.ToLower(k), "x-acs-") || strings.ToLower(k) == "host" ||
  280. strings.ToLower(k) == "content-type" {
  281. tmp[strings.ToLower(k)] = strings.TrimSpace(tea.StringValue(v))
  282. tmpHeader.Add(strings.ToLower(k), strings.TrimSpace(tea.StringValue(v)))
  283. }
  284. }
  285. hs := newSorter(tmp)
  286. // Sort the temp by the ascending order
  287. hs.Sort()
  288. canonicalheaders := ""
  289. for _, key := range hs.Keys {
  290. vals := tmpHeader[textproto.CanonicalMIMEHeaderKey(key)]
  291. sort.Strings(vals)
  292. canonicalheaders += key + ":" + strings.Join(vals, ",") + "\n"
  293. }
  294. return canonicalheaders, hs.Keys
  295. }
  296. func getCanonicalQueryString(query map[string]*string) string {
  297. tmp := make(map[string]string)
  298. for k, v := range query {
  299. tmp[k] = tea.StringValue(v)
  300. }
  301. hs := newSorter(tmp)
  302. // Sort the temp by the ascending order
  303. hs.Sort()
  304. canonicalQueryString := ""
  305. for i := range hs.Keys {
  306. if hs.Vals[i] != "" {
  307. canonicalQueryString += "&" + hs.Keys[i] + "=" + url.QueryEscape(hs.Vals[i])
  308. } else {
  309. canonicalQueryString += "&" + hs.Keys[i] + "="
  310. }
  311. }
  312. canonicalQueryString = strings.Replace(canonicalQueryString, "+", "%20", -1)
  313. canonicalQueryString = strings.Replace(canonicalQueryString, "*", "%2A", -1)
  314. canonicalQueryString = strings.Replace(canonicalQueryString, "%7E", "~", -1)
  315. if canonicalQueryString != "" {
  316. canonicalQueryString = strings.TrimLeft(canonicalQueryString, "&")
  317. }
  318. return canonicalQueryString
  319. }
  320. /**
  321. * Parse filter into a form string
  322. * @param filter object
  323. * @return the string
  324. */
  325. func ToForm(filter map[string]interface{}) (_result *string) {
  326. tmp := make(map[string]interface{})
  327. byt, _ := json.Marshal(filter)
  328. d := json.NewDecoder(bytes.NewReader(byt))
  329. d.UseNumber()
  330. _ = d.Decode(&tmp)
  331. result := make(map[string]*string)
  332. for key, value := range tmp {
  333. filterValue := reflect.ValueOf(value)
  334. flatRepeatedList(filterValue, result, key)
  335. }
  336. m := util.AnyifyMapValue(result)
  337. return util.ToFormString(m)
  338. }
  339. func flatRepeatedList(dataValue reflect.Value, result map[string]*string, prefix string) {
  340. if !dataValue.IsValid() {
  341. return
  342. }
  343. dataType := dataValue.Type()
  344. if dataType.Kind().String() == "slice" {
  345. handleRepeatedParams(dataValue, result, prefix)
  346. } else if dataType.Kind().String() == "map" {
  347. handleMap(dataValue, result, prefix)
  348. } else {
  349. result[prefix] = tea.String(fmt.Sprintf("%v", dataValue.Interface()))
  350. }
  351. }
  352. func handleRepeatedParams(repeatedFieldValue reflect.Value, result map[string]*string, prefix string) {
  353. if repeatedFieldValue.IsValid() && !repeatedFieldValue.IsNil() {
  354. for m := 0; m < repeatedFieldValue.Len(); m++ {
  355. elementValue := repeatedFieldValue.Index(m)
  356. key := prefix + "." + strconv.Itoa(m+1)
  357. fieldValue := reflect.ValueOf(elementValue.Interface())
  358. if fieldValue.Kind().String() == "map" {
  359. handleMap(fieldValue, result, key)
  360. } else {
  361. result[key] = tea.String(fmt.Sprintf("%v", fieldValue.Interface()))
  362. }
  363. }
  364. }
  365. }
  366. func handleMap(valueField reflect.Value, result map[string]*string, prefix string) {
  367. if valueField.IsValid() && valueField.String() != "" {
  368. valueFieldType := valueField.Type()
  369. if valueFieldType.Kind().String() == "map" {
  370. var byt []byte
  371. byt, _ = json.Marshal(valueField.Interface())
  372. cache := make(map[string]interface{})
  373. d := json.NewDecoder(bytes.NewReader(byt))
  374. d.UseNumber()
  375. _ = d.Decode(&cache)
  376. for key, value := range cache {
  377. pre := ""
  378. if prefix != "" {
  379. pre = prefix + "." + key
  380. } else {
  381. pre = key
  382. }
  383. fieldValue := reflect.ValueOf(value)
  384. flatRepeatedList(fieldValue, result, pre)
  385. }
  386. }
  387. }
  388. }
  389. /**
  390. * Get timestamp
  391. * @return the timestamp string
  392. */
  393. func GetTimestamp() (_result *string) {
  394. gmt := time.FixedZone("GMT", 0)
  395. return tea.String(time.Now().In(gmt).Format("2006-01-02T15:04:05Z"))
  396. }
  397. /**
  398. * Parse filter into a object which's type is map[string]string
  399. * @param filter query param
  400. * @return the object
  401. */
  402. func Query(filter map[string]interface{}) (_result map[string]*string) {
  403. tmp := make(map[string]interface{})
  404. byt, _ := json.Marshal(filter)
  405. d := json.NewDecoder(bytes.NewReader(byt))
  406. d.UseNumber()
  407. _ = d.Decode(&tmp)
  408. result := make(map[string]*string)
  409. for key, value := range tmp {
  410. filterValue := reflect.ValueOf(value)
  411. flatRepeatedList(filterValue, result, key)
  412. }
  413. return result
  414. }
  415. /**
  416. * Get signature according to signedParams, method and secret
  417. * @param signedParams params which need to be signed
  418. * @param method http method e.g. GET
  419. * @param secret AccessKeySecret
  420. * @return the signature
  421. */
  422. func GetRPCSignature(signedParams map[string]*string, method *string, secret *string) (_result *string) {
  423. stringToSign := buildRpcStringToSign(signedParams, tea.StringValue(method))
  424. signature := sign(stringToSign, tea.StringValue(secret), "&")
  425. return tea.String(signature)
  426. }
  427. /**
  428. * Parse array into a string with specified style
  429. * @param array the array
  430. * @param prefix the prefix string
  431. * @style specified style e.g. repeatList
  432. * @return the string
  433. */
  434. func ArrayToStringWithSpecifiedStyle(array interface{}, prefix *string, style *string) (_result *string) {
  435. if tea.BoolValue(util.IsUnset(array)) {
  436. return tea.String("")
  437. }
  438. sty := tea.StringValue(style)
  439. if sty == "repeatList" {
  440. tmp := map[string]interface{}{
  441. tea.StringValue(prefix): array,
  442. }
  443. return flatRepeatList(tmp)
  444. } else if sty == "simple" || sty == "spaceDelimited" || sty == "pipeDelimited" {
  445. return flatArray(array, sty)
  446. } else if sty == "json" {
  447. return util.ToJSONString(array)
  448. }
  449. return tea.String("")
  450. }
  451. func ParseToMap(in interface{}) map[string]interface{} {
  452. if tea.BoolValue(util.IsUnset(in)) {
  453. return nil
  454. }
  455. tmp := make(map[string]interface{})
  456. byt, _ := json.Marshal(in)
  457. d := json.NewDecoder(bytes.NewReader(byt))
  458. d.UseNumber()
  459. err := d.Decode(&tmp)
  460. if err != nil {
  461. return nil
  462. }
  463. return tmp
  464. }
  465. func flatRepeatList(filter map[string]interface{}) (_result *string) {
  466. tmp := make(map[string]interface{})
  467. byt, _ := json.Marshal(filter)
  468. d := json.NewDecoder(bytes.NewReader(byt))
  469. d.UseNumber()
  470. _ = d.Decode(&tmp)
  471. result := make(map[string]*string)
  472. for key, value := range tmp {
  473. filterValue := reflect.ValueOf(value)
  474. flatRepeatedList(filterValue, result, key)
  475. }
  476. res := make(map[string]string)
  477. for k, v := range result {
  478. res[k] = tea.StringValue(v)
  479. }
  480. hs := newSorter(res)
  481. hs.Sort()
  482. // Get the canonicalizedOSSHeaders
  483. t := ""
  484. for i := range hs.Keys {
  485. if i == len(hs.Keys)-1 {
  486. t += hs.Keys[i] + "=" + hs.Vals[i]
  487. } else {
  488. t += hs.Keys[i] + "=" + hs.Vals[i] + "&&"
  489. }
  490. }
  491. return tea.String(t)
  492. }
  493. func flatArray(array interface{}, sty string) *string {
  494. t := reflect.ValueOf(array)
  495. strs := make([]string, 0)
  496. for i := 0; i < t.Len(); i++ {
  497. tmp := t.Index(i)
  498. if tmp.Kind() == reflect.Ptr || tmp.Kind() == reflect.Interface {
  499. tmp = tmp.Elem()
  500. }
  501. if tmp.Kind() == reflect.Ptr {
  502. tmp = tmp.Elem()
  503. }
  504. if tmp.Kind() == reflect.String {
  505. strs = append(strs, tmp.String())
  506. } else {
  507. inter := tmp.Interface()
  508. byt, _ := json.Marshal(inter)
  509. strs = append(strs, string(byt))
  510. }
  511. }
  512. str := ""
  513. if sty == "simple" {
  514. str = strings.Join(strs, ",")
  515. } else if sty == "spaceDelimited" {
  516. str = strings.Join(strs, " ")
  517. } else if sty == "pipeDelimited" {
  518. str = strings.Join(strs, "|")
  519. }
  520. return tea.String(str)
  521. }
  522. func buildRpcStringToSign(signedParam map[string]*string, method string) (stringToSign string) {
  523. signParams := make(map[string]string)
  524. for key, value := range signedParam {
  525. signParams[key] = tea.StringValue(value)
  526. }
  527. stringToSign = getUrlFormedMap(signParams)
  528. stringToSign = strings.Replace(stringToSign, "+", "%20", -1)
  529. stringToSign = strings.Replace(stringToSign, "*", "%2A", -1)
  530. stringToSign = strings.Replace(stringToSign, "%7E", "~", -1)
  531. stringToSign = url.QueryEscape(stringToSign)
  532. stringToSign = method + "&%2F&" + stringToSign
  533. return
  534. }
  535. func getUrlFormedMap(source map[string]string) (urlEncoded string) {
  536. urlEncoder := url.Values{}
  537. for key, value := range source {
  538. urlEncoder.Add(key, value)
  539. }
  540. urlEncoded = urlEncoder.Encode()
  541. return
  542. }
  543. func sign(stringToSign, accessKeySecret, secretSuffix string) string {
  544. secret := accessKeySecret + secretSuffix
  545. signedBytes := shaHmac1(stringToSign, secret)
  546. signedString := base64.StdEncoding.EncodeToString(signedBytes)
  547. return signedString
  548. }
  549. func shaHmac1(source, secret string) []byte {
  550. key := []byte(secret)
  551. hmac := hmac.New(sha1.New, key)
  552. hmac.Write([]byte(source))
  553. return hmac.Sum(nil)
  554. }