provider.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  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 secretmanager
  14. import (
  15. "context"
  16. "errors"
  17. "fmt"
  18. "sync"
  19. secretmanager "cloud.google.com/go/secretmanager/apiv1"
  20. "golang.org/x/oauth2"
  21. "google.golang.org/api/option"
  22. kclient "sigs.k8s.io/controller-runtime/pkg/client"
  23. "sigs.k8s.io/controller-runtime/pkg/webhook/admission"
  24. esv1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1"
  25. "github.com/external-secrets/external-secrets/runtime/esutils"
  26. )
  27. // Provider is a secrets provider for GCP Secret Manager.
  28. // It implements the necessary NewClient() and ValidateStore() funcs.
  29. type Provider struct{}
  30. // https://github.com/external-secrets/external-secrets/issues/644
  31. var _ esv1.SecretsClient = &Client{}
  32. var _ esv1.Provider = &Provider{}
  33. /*
  34. Currently, GCPSM client has a limitation around how concurrent connections work
  35. This limitation causes memory leaks due to random disconnects from living clients
  36. and also payload switches when sending a call (such as using a credential from one
  37. thread to ask secrets from another thread).
  38. A Mutex was implemented to make sure only one connection can be in place at a time.
  39. */
  40. var useMu = sync.Mutex{}
  41. // Capabilities returns the provider's capabilities to read/write secrets.
  42. func (p *Provider) Capabilities() esv1.SecretStoreCapabilities {
  43. return esv1.SecretStoreReadWrite
  44. }
  45. // NewClient constructs a GCP Provider.
  46. func (p *Provider) NewClient(ctx context.Context, store esv1.GenericStore, kube kclient.Client, namespace string) (esv1.SecretsClient, error) {
  47. storeSpec := store.GetSpec()
  48. if storeSpec == nil || storeSpec.Provider == nil || storeSpec.Provider.GCPSM == nil {
  49. return nil, errors.New(errGCPSMStore)
  50. }
  51. gcpStore := storeSpec.Provider.GCPSM
  52. useMu.Lock()
  53. client := &Client{
  54. kube: kube,
  55. store: gcpStore,
  56. storeKind: store.GetKind(),
  57. namespace: namespace,
  58. }
  59. defer func() {
  60. if client.smClient == nil {
  61. _ = client.Close(ctx)
  62. }
  63. }()
  64. // this project ID is used for authentication (currently only relevant for workload identity)
  65. clusterProjectID, err := clusterProjectID(storeSpec)
  66. if err != nil {
  67. return nil, err
  68. }
  69. isClusterKind := store.GetObjectKind().GroupVersionKind().Kind == esv1.ClusterSecretStoreKind
  70. // allow SecretStore controller validation to pass
  71. // when using referent namespace.
  72. if namespace == "" && isClusterKind && isReferentSpec(gcpStore) {
  73. // placeholder smClient to prevent closing the client twice
  74. client.smClient, _ = secretmanager.NewClient(ctx, option.WithTokenSource(oauth2.StaticTokenSource(&oauth2.Token{})))
  75. return client, nil
  76. }
  77. ts, err := NewTokenSource(ctx, gcpStore.Auth, clusterProjectID, store.GetKind(), kube, namespace)
  78. if err != nil {
  79. return nil, fmt.Errorf(errUnableCreateGCPSMClient, err)
  80. }
  81. // check if we can get credentials
  82. _, err = ts.Token()
  83. if err != nil {
  84. return nil, fmt.Errorf(errUnableGetCredentials, err)
  85. }
  86. var clientGCPSM *secretmanager.Client
  87. if gcpStore.Location != "" {
  88. ep := fmt.Sprintf("secretmanager.%s.rep.googleapis.com:443", gcpStore.Location)
  89. regional := option.WithEndpoint(ep)
  90. clientGCPSM, err = secretmanager.NewClient(ctx, option.WithTokenSource(ts), regional)
  91. if err != nil {
  92. return nil, fmt.Errorf(errUnableCreateGCPSMClient, err)
  93. }
  94. } else {
  95. clientGCPSM, err = secretmanager.NewClient(ctx, option.WithTokenSource(ts))
  96. if err != nil {
  97. return nil, fmt.Errorf(errUnableCreateGCPSMClient, err)
  98. }
  99. }
  100. client.smClient = clientGCPSM
  101. return client, nil
  102. }
  103. // ValidateStore validates the configuration of the secret store.
  104. func (p *Provider) ValidateStore(store esv1.GenericStore) (admission.Warnings, error) {
  105. if store == nil {
  106. return nil, errors.New(errInvalidStore)
  107. }
  108. spc := store.GetSpec()
  109. if spc == nil {
  110. return nil, errors.New(errInvalidStoreSpec)
  111. }
  112. if spc.Provider == nil {
  113. return nil, errors.New(errInvalidStoreProv)
  114. }
  115. g := spc.Provider.GCPSM
  116. if p == nil {
  117. return nil, errors.New(errInvalidGCPProv)
  118. }
  119. if g.Auth.SecretRef != nil {
  120. if err := esutils.ValidateReferentSecretSelector(store, g.Auth.SecretRef.SecretAccessKey); err != nil {
  121. return nil, fmt.Errorf(errInvalidAuthSecretRef, err)
  122. }
  123. }
  124. if g.Auth.WorkloadIdentity != nil {
  125. if err := esutils.ValidateReferentServiceAccountSelector(store, g.Auth.WorkloadIdentity.ServiceAccountRef); err != nil {
  126. return nil, fmt.Errorf(errInvalidWISARef, err)
  127. }
  128. }
  129. return nil, nil
  130. }
  131. func clusterProjectID(spec *esv1.SecretStoreSpec) (string, error) {
  132. if spec.Provider.GCPSM.Auth.WorkloadIdentity != nil && spec.Provider.GCPSM.Auth.WorkloadIdentity.ClusterProjectID != "" {
  133. return spec.Provider.GCPSM.Auth.WorkloadIdentity.ClusterProjectID, nil
  134. }
  135. if spec.Provider.GCPSM.ProjectID != "" {
  136. return spec.Provider.GCPSM.ProjectID, nil
  137. }
  138. return "", errors.New(errNoProjectID)
  139. }
  140. func isReferentSpec(prov *esv1.GCPSMProvider) bool {
  141. if prov.Auth.SecretRef != nil &&
  142. prov.Auth.SecretRef.SecretAccessKey.Namespace == nil {
  143. return true
  144. }
  145. if prov.Auth.WorkloadIdentity != nil &&
  146. prov.Auth.WorkloadIdentity.ServiceAccountRef.Namespace == nil {
  147. return true
  148. }
  149. return false
  150. }
  151. // NewProvider creates a new Provider instance.
  152. func NewProvider() esv1.Provider {
  153. return &Provider{}
  154. }
  155. // ProviderSpec returns the provider specification for registration.
  156. func ProviderSpec() *esv1.SecretStoreProvider {
  157. return &esv1.SecretStoreProvider{
  158. GCPSM: &esv1.GCPSMProvider{},
  159. }
  160. }
  161. // MaintenanceStatus returns the maintenance status of the provider.
  162. func MaintenanceStatus() esv1.MaintenanceStatus {
  163. return esv1.MaintenanceStatusMaintained
  164. }