authorizer.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package ibm
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "github.com/IBM/go-sdk-core/v5/core"
  6. "github.com/opencost/opencost/pkg/cloud"
  7. )
  8. const APIKeyAuthorizerType = "IBMAPIKey"
  9. // Authorizer creates IBM Cloud SDK authenticators for Usage Reports clients.
  10. type Authorizer interface {
  11. cloud.Authorizer
  12. CreateAuthenticator() (core.Authenticator, error)
  13. }
  14. // SelectAuthorizerByType registers supported IBM authorizer types.
  15. func SelectAuthorizerByType(typeStr string) (Authorizer, error) {
  16. switch typeStr {
  17. case APIKeyAuthorizerType:
  18. return &APIKey{}, nil
  19. default:
  20. return nil, fmt.Errorf("IBM: provider authorizer type '%s' is not valid", typeStr)
  21. }
  22. }
  23. // APIKey authenticates to IBM Cloud IAM with an API key.
  24. // The key may belong to a user or service ID with billing.usage-report.read.
  25. type APIKey struct {
  26. Key string `json:"apiKey"`
  27. }
  28. func (a *APIKey) MarshalJSON() ([]byte, error) {
  29. fmap := map[string]any{
  30. cloud.AuthorizerTypeProperty: APIKeyAuthorizerType,
  31. "apiKey": a.Key,
  32. }
  33. return json.Marshal(fmap)
  34. }
  35. func (a *APIKey) Validate() error {
  36. if a.Key == "" {
  37. return fmt.Errorf("APIKey: missing apiKey")
  38. }
  39. return nil
  40. }
  41. func (a *APIKey) Equals(config cloud.Config) bool {
  42. if config == nil {
  43. return false
  44. }
  45. that, ok := config.(*APIKey)
  46. if !ok {
  47. return false
  48. }
  49. return a.Key == that.Key
  50. }
  51. func (a *APIKey) Sanitize() cloud.Config {
  52. return &APIKey{Key: cloud.Redacted}
  53. }
  54. func (a *APIKey) CreateAuthenticator() (core.Authenticator, error) {
  55. return core.NewIamAuthenticatorBuilder().SetApiKey(a.Key).Build()
  56. }