signer_ram_role_arn.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. /*
  2. * Licensed under the Apache License, Version 2.0 (the "License");
  3. * you may not use this file except in compliance with the License.
  4. * You may obtain a copy of the License at
  5. *
  6. * http://www.apache.org/licenses/LICENSE-2.0
  7. *
  8. * Unless required by applicable law or agreed to in writing, software
  9. * distributed under the License is distributed on an "AS IS" BASIS,
  10. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. * See the License for the specific language governing permissions and
  12. * limitations under the License.
  13. */
  14. package signers
  15. import (
  16. "encoding/json"
  17. "fmt"
  18. "net/http"
  19. "strconv"
  20. "time"
  21. "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials"
  22. "github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors"
  23. "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
  24. "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
  25. "github.com/jmespath/go-jmespath"
  26. )
  27. const (
  28. defaultDurationSeconds = 3600
  29. )
  30. type RamRoleArnSigner struct {
  31. *credentialUpdater
  32. roleSessionName string
  33. sessionCredential *SessionCredential
  34. credential *credentials.RamRoleArnCredential
  35. commonApi func(request *requests.CommonRequest, signer interface{}) (response *responses.CommonResponse, err error)
  36. }
  37. func NewRamRoleArnSigner(credential *credentials.RamRoleArnCredential, commonApi func(request *requests.CommonRequest, signer interface{}) (response *responses.CommonResponse, err error)) (signer *RamRoleArnSigner, err error) {
  38. signer = &RamRoleArnSigner{
  39. credential: credential,
  40. commonApi: commonApi,
  41. }
  42. signer.credentialUpdater = &credentialUpdater{
  43. credentialExpiration: credential.RoleSessionExpiration,
  44. buildRequestMethod: signer.buildCommonRequest,
  45. responseCallBack: signer.refreshCredential,
  46. refreshApi: signer.refreshApi,
  47. }
  48. if len(credential.RoleSessionName) > 0 {
  49. signer.roleSessionName = credential.RoleSessionName
  50. } else {
  51. signer.roleSessionName = "aliyun-go-sdk-" + strconv.FormatInt(time.Now().UnixNano()/1000, 10)
  52. }
  53. if credential.RoleSessionExpiration > 0 {
  54. if credential.RoleSessionExpiration >= 900 && credential.RoleSessionExpiration <= 3600 {
  55. signer.credentialExpiration = credential.RoleSessionExpiration
  56. } else {
  57. err = errors.NewClientError(errors.InvalidParamErrorCode, "Assume Role session duration should be in the range of 15min - 1Hr", nil)
  58. }
  59. } else {
  60. signer.credentialExpiration = defaultDurationSeconds
  61. }
  62. return
  63. }
  64. func (*RamRoleArnSigner) GetName() string {
  65. return "HMAC-SHA1"
  66. }
  67. func (*RamRoleArnSigner) GetType() string {
  68. return ""
  69. }
  70. func (*RamRoleArnSigner) GetVersion() string {
  71. return "1.0"
  72. }
  73. func (signer *RamRoleArnSigner) GetAccessKeyId() (accessKeyId string, err error) {
  74. if signer.sessionCredential == nil || signer.needUpdateCredential() {
  75. err = signer.updateCredential()
  76. if err != nil {
  77. return
  78. }
  79. }
  80. if signer.sessionCredential == nil || len(signer.sessionCredential.AccessKeyId) <= 0 {
  81. return "", err
  82. }
  83. return signer.sessionCredential.AccessKeyId, nil
  84. }
  85. func (signer *RamRoleArnSigner) GetExtraParam() map[string]string {
  86. if signer.sessionCredential == nil || signer.needUpdateCredential() {
  87. signer.updateCredential()
  88. }
  89. if signer.sessionCredential == nil || len(signer.sessionCredential.StsToken) <= 0 {
  90. return make(map[string]string)
  91. }
  92. return map[string]string{"SecurityToken": signer.sessionCredential.StsToken}
  93. }
  94. func (signer *RamRoleArnSigner) Sign(stringToSign, secretSuffix string) string {
  95. secret := signer.sessionCredential.AccessKeySecret + secretSuffix
  96. return ShaHmac1(stringToSign, secret)
  97. }
  98. func (signer *RamRoleArnSigner) buildCommonRequest() (request *requests.CommonRequest, err error) {
  99. request = requests.NewCommonRequest()
  100. request.Product = "Sts"
  101. request.Version = "2015-04-01"
  102. request.ApiName = "AssumeRole"
  103. request.Scheme = requests.HTTPS
  104. request.QueryParams["RoleArn"] = signer.credential.RoleArn
  105. request.QueryParams["RoleSessionName"] = signer.credential.RoleSessionName
  106. request.QueryParams["DurationSeconds"] = strconv.Itoa(signer.credentialExpiration)
  107. return
  108. }
  109. func (signer *RamRoleArnSigner) refreshApi(request *requests.CommonRequest) (response *responses.CommonResponse, err error) {
  110. credential := &credentials.AccessKeyCredential{
  111. AccessKeyId: signer.credential.AccessKeyId,
  112. AccessKeySecret: signer.credential.AccessKeySecret,
  113. }
  114. signerV1 := NewAccessKeySigner(credential)
  115. return signer.commonApi(request, signerV1)
  116. }
  117. func (signer *RamRoleArnSigner) refreshCredential(response *responses.CommonResponse) (err error) {
  118. if response.GetHttpStatus() != http.StatusOK {
  119. message := "refresh session token failed"
  120. err = errors.NewServerError(response.GetHttpStatus(), response.GetHttpContentString(), message)
  121. return
  122. }
  123. var data interface{}
  124. err = json.Unmarshal(response.GetHttpContentBytes(), &data)
  125. if err != nil {
  126. return fmt.Errorf("refresh RoleArn sts token err, json.Unmarshal fail: %s", err.Error())
  127. }
  128. accessKeyId, err := jmespath.Search("Credentials.AccessKeyId", data)
  129. if err != nil {
  130. return fmt.Errorf("refresh RoleArn sts token err, fail to get AccessKeyId: %s", err.Error())
  131. }
  132. accessKeySecret, err := jmespath.Search("Credentials.AccessKeySecret", data)
  133. if err != nil {
  134. return fmt.Errorf("refresh RoleArn sts token err, fail to get AccessKeySecret: %s", err.Error())
  135. }
  136. securityToken, err := jmespath.Search("Credentials.SecurityToken", data)
  137. if err != nil {
  138. return fmt.Errorf("refresh RoleArn sts token err, fail to get SecurityToken: %s", err.Error())
  139. }
  140. if accessKeyId == nil || accessKeySecret == nil || securityToken == nil {
  141. return
  142. }
  143. signer.sessionCredential = &SessionCredential{
  144. AccessKeyId: accessKeyId.(string),
  145. AccessKeySecret: accessKeySecret.(string),
  146. StsToken: securityToken.(string),
  147. }
  148. return
  149. }
  150. func (signer *RamRoleArnSigner) GetSessionCredential() *SessionCredential {
  151. return signer.sessionCredential
  152. }