ecr.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  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. http://www.apache.org/licenses/LICENSE-2.0
  6. Unless required by applicable law or agreed to in writing, software
  7. distributed under the License is distributed on an "AS IS" BASIS,
  8. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. See the License for the specific language governing permissions and
  10. limitations under the License.
  11. */
  12. package ecr
  13. import (
  14. "context"
  15. "encoding/base64"
  16. "errors"
  17. "fmt"
  18. "strconv"
  19. "strings"
  20. "github.com/aws/aws-sdk-go-v2/aws"
  21. "github.com/aws/aws-sdk-go-v2/service/ecr"
  22. "github.com/aws/aws-sdk-go-v2/service/ecrpublic"
  23. apiextensions "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
  24. "sigs.k8s.io/controller-runtime/pkg/client"
  25. "sigs.k8s.io/yaml"
  26. esv1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1"
  27. genv1alpha1 "github.com/external-secrets/external-secrets/apis/generators/v1alpha1"
  28. awsauth "github.com/external-secrets/external-secrets/pkg/provider/aws/auth"
  29. )
  30. type ecrAPI interface {
  31. GetAuthorizationToken(ctx context.Context, params *ecr.GetAuthorizationTokenInput, optFuncs ...func(*ecr.Options)) (*ecr.GetAuthorizationTokenOutput, error)
  32. }
  33. type ecrPublicAPI interface {
  34. GetAuthorizationToken(ctx context.Context, params *ecrpublic.GetAuthorizationTokenInput, optFuncs ...func(*ecrpublic.Options)) (*ecrpublic.GetAuthorizationTokenOutput, error)
  35. }
  36. type Generator struct{}
  37. const (
  38. errNoSpec = "no config spec provided"
  39. errParseSpec = "unable to parse spec: %w"
  40. errCreateSess = "unable to create aws session: %w"
  41. errGetPrivateToken = "unable to get authorization token: %w"
  42. errGetPublicToken = "unable to get public authorization token: %w"
  43. )
  44. func (g *Generator) Generate(ctx context.Context, jsonSpec *apiextensions.JSON, kube client.Client, namespace string) (map[string][]byte, genv1alpha1.GeneratorProviderState, error) {
  45. return g.generate(ctx, jsonSpec, kube, namespace, ecrPrivateFactory, ecrPublicFactory)
  46. }
  47. func (g *Generator) Cleanup(ctx context.Context, jsonSpec *apiextensions.JSON, _ genv1alpha1.GeneratorProviderState, crClient client.Client, namespace string) error {
  48. return nil
  49. }
  50. func (g *Generator) generate(
  51. ctx context.Context,
  52. jsonSpec *apiextensions.JSON,
  53. kube client.Client,
  54. namespace string,
  55. ecrPrivateFunc ecrPrivateFactoryFunc,
  56. ecrPublicFunc ecrPublicFactoryFunc,
  57. ) (map[string][]byte, genv1alpha1.GeneratorProviderState, error) {
  58. if jsonSpec == nil {
  59. return nil, nil, errors.New(errNoSpec)
  60. }
  61. res, err := parseSpec(jsonSpec.Raw)
  62. if err != nil {
  63. return nil, nil, fmt.Errorf(errParseSpec, err)
  64. }
  65. cfg, err := awsauth.NewGeneratorSession(
  66. ctx,
  67. esv1.AWSAuth{
  68. SecretRef: (*esv1.AWSAuthSecretRef)(res.Spec.Auth.SecretRef),
  69. JWTAuth: (*esv1.AWSJWTAuth)(res.Spec.Auth.JWTAuth),
  70. },
  71. res.Spec.Role,
  72. res.Spec.Region,
  73. kube,
  74. namespace,
  75. awsauth.DefaultSTSProvider,
  76. awsauth.DefaultJWTProvider)
  77. if err != nil {
  78. return nil, nil, fmt.Errorf(errCreateSess, err)
  79. }
  80. if res.Spec.Scope == "public" {
  81. return fetchECRPublicToken(ctx, cfg, ecrPublicFunc)
  82. }
  83. return fetchECRPrivateToken(ctx, cfg, ecrPrivateFunc)
  84. }
  85. func fetchECRPrivateToken(ctx context.Context, cfg *aws.Config, ecrPrivateFunc ecrPrivateFactoryFunc) (map[string][]byte, genv1alpha1.GeneratorProviderState, error) {
  86. client := ecrPrivateFunc(cfg)
  87. out, err := client.GetAuthorizationToken(ctx, &ecr.GetAuthorizationTokenInput{})
  88. if err != nil {
  89. return nil, nil, fmt.Errorf(errGetPrivateToken, err)
  90. }
  91. if len(out.AuthorizationData) != 1 {
  92. return nil, nil, fmt.Errorf("unexpected number of authorization tokens. expected 1, found %d", len(out.AuthorizationData))
  93. }
  94. // AuthorizationToken is base64 encoded {username}:{password} string
  95. decodedToken, err := base64.StdEncoding.DecodeString(*out.AuthorizationData[0].AuthorizationToken)
  96. if err != nil {
  97. return nil, nil, err
  98. }
  99. parts := strings.Split(string(decodedToken), ":")
  100. if len(parts) != 2 {
  101. return nil, nil, errors.New("unexpected token format")
  102. }
  103. exp := out.AuthorizationData[0].ExpiresAt.UTC().Unix()
  104. return map[string][]byte{
  105. "username": []byte(parts[0]),
  106. "password": []byte(parts[1]),
  107. "proxy_endpoint": []byte(*out.AuthorizationData[0].ProxyEndpoint),
  108. "expires_at": []byte(strconv.FormatInt(exp, 10)),
  109. }, nil, nil
  110. }
  111. func fetchECRPublicToken(ctx context.Context, cfg *aws.Config, ecrPublicFunc ecrPublicFactoryFunc) (map[string][]byte, genv1alpha1.GeneratorProviderState, error) {
  112. client := ecrPublicFunc(cfg)
  113. out, err := client.GetAuthorizationToken(ctx, &ecrpublic.GetAuthorizationTokenInput{})
  114. if err != nil {
  115. return nil, nil, fmt.Errorf(errGetPublicToken, err)
  116. }
  117. decodedToken, err := base64.StdEncoding.DecodeString(*out.AuthorizationData.AuthorizationToken)
  118. if err != nil {
  119. return nil, nil, err
  120. }
  121. parts := strings.Split(string(decodedToken), ":")
  122. if len(parts) != 2 {
  123. return nil, nil, errors.New("unexpected token format")
  124. }
  125. exp := out.AuthorizationData.ExpiresAt.UTC().Unix()
  126. return map[string][]byte{
  127. "username": []byte(parts[0]),
  128. "password": []byte(parts[1]),
  129. "expires_at": []byte(strconv.FormatInt(exp, 10)),
  130. }, nil, nil
  131. }
  132. type ecrPrivateFactoryFunc func(aws *aws.Config) ecrAPI
  133. type ecrPublicFactoryFunc func(aws *aws.Config) ecrPublicAPI
  134. func ecrPrivateFactory(cfg *aws.Config) ecrAPI {
  135. return ecr.NewFromConfig(*cfg, func(o *ecr.Options) {
  136. o.EndpointResolverV2 = ecrCustomEndpointResolver{}
  137. })
  138. }
  139. func ecrPublicFactory(cfg *aws.Config) ecrPublicAPI {
  140. return ecrpublic.NewFromConfig(*cfg, func(o *ecrpublic.Options) {
  141. o.EndpointResolverV2 = ecrPublicCustomEndpointResolver{}
  142. })
  143. }
  144. func parseSpec(data []byte) (*genv1alpha1.ECRAuthorizationToken, error) {
  145. var spec genv1alpha1.ECRAuthorizationToken
  146. err := yaml.Unmarshal(data, &spec)
  147. return &spec, err
  148. }
  149. func init() {
  150. genv1alpha1.Register(genv1alpha1.ECRAuthorizationTokenKind, &Generator{})
  151. }