signer_ram_role_arn.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  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. jmespath "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. if signer.credential.Policy != "" {
  106. request.QueryParams["Policy"] = signer.credential.Policy
  107. }
  108. request.QueryParams["RoleSessionName"] = signer.credential.RoleSessionName
  109. request.QueryParams["DurationSeconds"] = strconv.Itoa(signer.credentialExpiration)
  110. return
  111. }
  112. func (signer *RamRoleArnSigner) refreshApi(request *requests.CommonRequest) (response *responses.CommonResponse, err error) {
  113. credential := &credentials.AccessKeyCredential{
  114. AccessKeyId: signer.credential.AccessKeyId,
  115. AccessKeySecret: signer.credential.AccessKeySecret,
  116. }
  117. signerV1 := NewAccessKeySigner(credential)
  118. return signer.commonApi(request, signerV1)
  119. }
  120. func (signer *RamRoleArnSigner) refreshCredential(response *responses.CommonResponse) (err error) {
  121. if response.GetHttpStatus() != http.StatusOK {
  122. message := "refresh session token failed"
  123. err = errors.NewServerError(response.GetHttpStatus(), response.GetHttpContentString(), message)
  124. return
  125. }
  126. var data interface{}
  127. err = json.Unmarshal(response.GetHttpContentBytes(), &data)
  128. if err != nil {
  129. return fmt.Errorf("refresh RoleArn sts token err, json.Unmarshal fail: %s", err.Error())
  130. }
  131. accessKeyId, err := jmespath.Search("Credentials.AccessKeyId", data)
  132. if err != nil {
  133. return fmt.Errorf("refresh RoleArn sts token err, fail to get AccessKeyId: %s", err.Error())
  134. }
  135. accessKeySecret, err := jmespath.Search("Credentials.AccessKeySecret", data)
  136. if err != nil {
  137. return fmt.Errorf("refresh RoleArn sts token err, fail to get AccessKeySecret: %s", err.Error())
  138. }
  139. securityToken, err := jmespath.Search("Credentials.SecurityToken", data)
  140. if err != nil {
  141. return fmt.Errorf("refresh RoleArn sts token err, fail to get SecurityToken: %s", err.Error())
  142. }
  143. if accessKeyId == nil || accessKeySecret == nil || securityToken == nil {
  144. return
  145. }
  146. signer.sessionCredential = &SessionCredential{
  147. AccessKeyId: accessKeyId.(string),
  148. AccessKeySecret: accessKeySecret.(string),
  149. StsToken: securityToken.(string),
  150. }
  151. return
  152. }
  153. func (signer *RamRoleArnSigner) GetSessionCredential() *SessionCredential {
  154. return signer.sessionCredential
  155. }