ecr.go 6.2 KB

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