authorizer.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package alibaba
  2. import (
  3. "fmt"
  4. "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth"
  5. "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials"
  6. "github.com/opencost/opencost/core/pkg/util/json"
  7. "github.com/opencost/opencost/pkg/cloud"
  8. )
  9. const AccessKeyAuthorizerType = "AlibabaAccessKey"
  10. // Authorizer provide *bssopenapi.Client for Alibaba cloud BOS for Billing related SDK calls
  11. type Authorizer interface {
  12. cloud.Authorizer
  13. GetCredentials() (auth.Credential, error)
  14. }
  15. // SelectAuthorizerByType is an implementation of AuthorizerSelectorFn and acts as a register for Authorizer types
  16. func SelectAuthorizerByType(typeStr string) (Authorizer, error) {
  17. switch typeStr {
  18. case AccessKeyAuthorizerType:
  19. return &AccessKey{}, nil
  20. default:
  21. return nil, fmt.Errorf("alibaba: provider authorizer type '%s' is not valid", typeStr)
  22. }
  23. }
  24. // AccessKey holds Alibaba credentials parsing from the service-key.json file.
  25. type AccessKey struct {
  26. AccessKeyID string `json:"accessKeyID"`
  27. AccessKeySecret string `json:"accessKeySecret"`
  28. }
  29. // MarshalJSON custom json marshalling functions, sets properties as tagged in struct and sets the authorizer type property
  30. func (ak *AccessKey) MarshalJSON() ([]byte, error) {
  31. fmap := make(map[string]any, 3)
  32. fmap[cloud.AuthorizerTypeProperty] = AccessKeyAuthorizerType
  33. fmap["accessKeyID"] = ak.AccessKeyID
  34. fmap["accessKeySecret"] = ak.AccessKeySecret
  35. return json.Marshal(fmap)
  36. }
  37. func (ak *AccessKey) Validate() error {
  38. if ak.AccessKeyID == "" {
  39. return fmt.Errorf("AccessKey: missing Access key ID")
  40. }
  41. if ak.AccessKeySecret == "" {
  42. return fmt.Errorf("AccessKey: missing Access Key secret")
  43. }
  44. return nil
  45. }
  46. func (ak *AccessKey) Equals(config cloud.Config) bool {
  47. if config == nil {
  48. return false
  49. }
  50. thatConfig, ok := config.(*AccessKey)
  51. if !ok {
  52. return false
  53. }
  54. if ak.AccessKeyID != thatConfig.AccessKeyID {
  55. return false
  56. }
  57. if ak.AccessKeySecret != thatConfig.AccessKeySecret {
  58. return false
  59. }
  60. return true
  61. }
  62. func (ak *AccessKey) Sanitize() cloud.Config {
  63. return &AccessKey{
  64. AccessKeyID: ak.AccessKeyID,
  65. AccessKeySecret: cloud.Redacted,
  66. }
  67. }
  68. // GetCredentials creates a credentials object to authorize the use of service sdk calls
  69. func (ak *AccessKey) GetCredentials() (auth.Credential, error) {
  70. err := ak.Validate()
  71. if err != nil {
  72. return nil, err
  73. }
  74. return &credentials.AccessKeyCredential{AccessKeyId: ak.AccessKeyID, AccessKeySecret: ak.AccessKeySecret}, nil
  75. }