provider.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. /*
  2. Copyright © The ESO Authors
  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. // metadataClientFactory is used to create metadata clients.
  42. // It can be overridden in tests to inject a fake client.
  43. var metadataClientFactory = newMetadataClient
  44. // Capabilities returns the provider's capabilities to read/write secrets.
  45. func (p *Provider) Capabilities() esv1.SecretStoreCapabilities {
  46. return esv1.SecretStoreReadWrite
  47. }
  48. // NewClient constructs a GCP Provider.
  49. func (p *Provider) NewClient(ctx context.Context, store esv1.GenericStore, kube kclient.Client, namespace string) (esv1.SecretsClient, error) {
  50. storeSpec := store.GetSpec()
  51. if storeSpec == nil || storeSpec.Provider == nil || storeSpec.Provider.GCPSM == nil {
  52. return nil, errors.New(errGCPSMStore)
  53. }
  54. gcpStore := storeSpec.Provider.GCPSM.DeepCopy()
  55. useMu.Lock()
  56. client := &Client{
  57. kube: kube,
  58. store: gcpStore,
  59. storeKind: store.GetKind(),
  60. namespace: namespace,
  61. }
  62. defer func() {
  63. if client.smClient == nil {
  64. _ = client.Close(ctx)
  65. }
  66. }()
  67. // this project ID is used for authentication (currently only relevant for workload identity)
  68. clusterProjectID, err := clusterProjectID(ctx, storeSpec)
  69. if err != nil {
  70. return nil, err
  71. }
  72. // If ProjectID is not explicitly set in the spec, use the clusterProjectID
  73. // This allows the client to function when ProjectID is omitted for Workload Identity,
  74. // Workload Identity Federation, or default credentials (not static credentials)
  75. if gcpStore.ProjectID == "" {
  76. gcpStore.ProjectID = clusterProjectID
  77. }
  78. isClusterKind := store.GetObjectKind().GroupVersionKind().Kind == esv1.ClusterSecretStoreKind
  79. // allow SecretStore controller validation to pass
  80. // when using referent namespace.
  81. if namespace == "" && isClusterKind && isReferentSpec(gcpStore) {
  82. // placeholder smClient to prevent closing the client twice
  83. client.smClient, _ = secretmanager.NewClient(ctx, option.WithTokenSource(oauth2.StaticTokenSource(&oauth2.Token{})))
  84. return client, nil
  85. }
  86. ts, err := NewTokenSource(ctx, gcpStore.Auth, clusterProjectID, store.GetKind(), kube, namespace)
  87. if err != nil {
  88. return nil, fmt.Errorf(errUnableCreateGCPSMClient, err)
  89. }
  90. // check if we can get credentials
  91. _, err = ts.Token()
  92. if err != nil {
  93. return nil, fmt.Errorf(errUnableGetCredentials, err)
  94. }
  95. clientGCPSM, err := newSMClient(ctx, ts, gcpStore.Location)
  96. if err != nil {
  97. return nil, fmt.Errorf(errUnableCreateGCPSMClient, err)
  98. }
  99. client.smClient = clientGCPSM
  100. return client, nil
  101. }
  102. // ValidateStore validates the configuration of the secret store.
  103. func (p *Provider) ValidateStore(store esv1.GenericStore) (admission.Warnings, error) {
  104. if store == nil {
  105. return nil, errors.New(errInvalidStore)
  106. }
  107. spc := store.GetSpec()
  108. if spc == nil {
  109. return nil, errors.New(errInvalidStoreSpec)
  110. }
  111. if spc.Provider == nil {
  112. return nil, errors.New(errInvalidStoreProv)
  113. }
  114. g := spc.Provider.GCPSM
  115. if g == nil {
  116. return nil, errors.New(errInvalidGCPProv)
  117. }
  118. if g.Auth.SecretRef != nil {
  119. if err := esutils.ValidateReferentSecretSelector(store, g.Auth.SecretRef.SecretAccessKey); err != nil {
  120. return nil, fmt.Errorf(errInvalidAuthSecretRef, err)
  121. }
  122. }
  123. if g.Auth.WorkloadIdentity != nil {
  124. if err := esutils.ValidateReferentServiceAccountSelector(store, g.Auth.WorkloadIdentity.ServiceAccountRef); err != nil {
  125. return nil, fmt.Errorf(errInvalidWISARef, err)
  126. }
  127. }
  128. return nil, nil
  129. }
  130. func newSMClient(ctx context.Context, ts oauth2.TokenSource, location string) (*secretmanager.Client, error) {
  131. if location != "" {
  132. ep := fmt.Sprintf("secretmanager.%s.rep.googleapis.com:443", location)
  133. return secretmanager.NewClient(ctx, option.WithTokenSource(ts), option.WithEndpoint(ep))
  134. }
  135. return secretmanager.NewClient(ctx, option.WithTokenSource(ts))
  136. }
  137. func clusterProjectID(ctx context.Context, spec *esv1.SecretStoreSpec) (string, error) {
  138. if spec.Provider.GCPSM.Auth.WorkloadIdentity != nil && spec.Provider.GCPSM.Auth.WorkloadIdentity.ClusterProjectID != "" {
  139. return spec.Provider.GCPSM.Auth.WorkloadIdentity.ClusterProjectID, nil
  140. }
  141. if spec.Provider.GCPSM.ProjectID != "" {
  142. return spec.Provider.GCPSM.ProjectID, nil
  143. }
  144. // If using static credentials, projectID must be explicitly set
  145. // Do NOT fall back to metadata server for static credentials
  146. if spec.Provider.GCPSM.Auth.SecretRef != nil {
  147. return "", errors.New(errNoProjectID)
  148. }
  149. // Fall back to GCP metadata server when running in GKE
  150. // This allows SecretStore/ClusterSecretStore to omit projectID
  151. // when the secrets are in the same project as the GKE cluster
  152. metadataClient := metadataClientFactory()
  153. projectID, err := metadataClient.ProjectIDWithContext(ctx)
  154. if err == nil && projectID != "" {
  155. return projectID, nil
  156. }
  157. log.V(1).Info("failed to get projectID from metadata server", "error", err)
  158. return "", errors.New(errNoProjectID)
  159. }
  160. func isReferentSpec(prov *esv1.GCPSMProvider) bool {
  161. if prov.Auth.SecretRef != nil &&
  162. prov.Auth.SecretRef.SecretAccessKey.Namespace == nil {
  163. return true
  164. }
  165. if prov.Auth.WorkloadIdentity != nil &&
  166. prov.Auth.WorkloadIdentity.ServiceAccountRef.Namespace == nil {
  167. return true
  168. }
  169. return false
  170. }
  171. // NewProvider creates a new Provider instance.
  172. func NewProvider() esv1.Provider {
  173. return &Provider{}
  174. }
  175. // ProviderSpec returns the provider specification for registration.
  176. func ProviderSpec() *esv1.SecretStoreProvider {
  177. return &esv1.SecretStoreProvider{
  178. GCPSM: &esv1.GCPSMProvider{},
  179. }
  180. }
  181. // MaintenanceStatus returns the maintenance status of the provider.
  182. func MaintenanceStatus() esv1.MaintenanceStatus {
  183. return esv1.MaintenanceStatusMaintained
  184. }