client_manager.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  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 clientmanager
  13. import (
  14. "context"
  15. "fmt"
  16. "strings"
  17. "github.com/go-logr/logr"
  18. "golang.org/x/exp/slices"
  19. v1 "k8s.io/api/core/v1"
  20. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  21. "k8s.io/apimachinery/pkg/types"
  22. ctrl "sigs.k8s.io/controller-runtime"
  23. "sigs.k8s.io/controller-runtime/pkg/client"
  24. esv1beta1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1beta1"
  25. "github.com/external-secrets/external-secrets/pkg/controllers/secretstore"
  26. )
  27. const (
  28. errGetClusterSecretStore = "could not get ClusterSecretStore %q, %w"
  29. errGetSecretStore = "could not get SecretStore %q, %w"
  30. errSecretStoreNotReady = "the desired SecretStore %s is not ready"
  31. errClusterStoreMismatch = "using cluster store %q is not allowed from namespace %q: denied by spec.condition"
  32. )
  33. // Manager stores instances of provider clients
  34. // At any given time we must have no more than one instance
  35. // of a client (due to limitations in GCP / see mutexlock there)
  36. // If the controller requests another instance of a given client
  37. // we will close the old client first and then construct a new one.
  38. type Manager struct {
  39. log logr.Logger
  40. client client.Client
  41. controllerClass string
  42. enableFloodgate bool
  43. // store clients by provider type
  44. clientMap map[clientKey]*clientVal
  45. }
  46. type clientKey struct {
  47. providerType string
  48. }
  49. type clientVal struct {
  50. client esv1beta1.SecretsClient
  51. store esv1beta1.GenericStore
  52. }
  53. // New constructs a new manager with defaults.
  54. func New(ctrlClient client.Client, controllerClass string, enableFloodgate bool) *Manager {
  55. log := ctrl.Log.WithName("clientmanager")
  56. return &Manager{
  57. log: log,
  58. client: ctrlClient,
  59. controllerClass: controllerClass,
  60. enableFloodgate: enableFloodgate,
  61. clientMap: make(map[clientKey]*clientVal),
  62. }
  63. }
  64. // Get returns a provider client from the given storeRef or sourceRef.secretStoreRef
  65. // while sourceRef.SecretStoreRef takes precedence over storeRef.
  66. // Do not close the client returned from this func, instead close
  67. // the manager once you're done with recinciling the external secret.
  68. func (m *Manager) Get(ctx context.Context, storeRef esv1beta1.SecretStoreRef, namespace string, sourceRef *esv1beta1.SourceRef) (esv1beta1.SecretsClient, error) {
  69. if sourceRef != nil && sourceRef.SecretStoreRef != nil {
  70. storeRef = *sourceRef.SecretStoreRef
  71. }
  72. store, err := m.getStore(ctx, &storeRef, namespace)
  73. if err != nil {
  74. return nil, err
  75. }
  76. // check if store should be handled by this controller instance
  77. if !secretstore.ShouldProcessStore(store, m.controllerClass) {
  78. return nil, fmt.Errorf("can not reference unmanaged store")
  79. }
  80. // when using ClusterSecretStore, validate the ClusterSecretStore namespace conditions
  81. shouldProcess, err := m.shouldProcessSecret(store, namespace)
  82. if err != nil || !shouldProcess {
  83. if err == nil && !shouldProcess {
  84. err = fmt.Errorf(errClusterStoreMismatch, store.GetName(), namespace)
  85. }
  86. return nil, err
  87. }
  88. if m.enableFloodgate {
  89. err := assertStoreIsUsable(store)
  90. if err != nil {
  91. return nil, err
  92. }
  93. }
  94. storeProvider, err := esv1beta1.GetProvider(store)
  95. if err != nil {
  96. return nil, err
  97. }
  98. secretClient := m.getStoredClient(ctx, storeProvider, store)
  99. if secretClient != nil {
  100. return secretClient, nil
  101. }
  102. m.log.V(1).Info("creating new client",
  103. "provider", fmt.Sprintf("%T", storeProvider),
  104. "store", fmt.Sprintf("%s/%s", store.GetNamespace(), store.GetName()))
  105. // secret client is created only if we are going to refresh
  106. // this skip an unnecessary check/request in the case we are not going to do anything
  107. secretClient, err = storeProvider.NewClient(ctx, store, m.client, namespace)
  108. if err != nil {
  109. return nil, err
  110. }
  111. idx := storeKey(storeProvider)
  112. m.clientMap[idx] = &clientVal{
  113. client: secretClient,
  114. store: store,
  115. }
  116. return secretClient, nil
  117. }
  118. // returns a previously stored client from the cache if store and store-version match
  119. // if a client exists for the same provider which points to a different store or store version
  120. // it will be cleaned up.
  121. func (m *Manager) getStoredClient(ctx context.Context, storeProvider esv1beta1.Provider, store esv1beta1.GenericStore) esv1beta1.SecretsClient {
  122. idx := storeKey(storeProvider)
  123. val, ok := m.clientMap[idx]
  124. if !ok {
  125. return nil
  126. }
  127. storeName := fmt.Sprintf("%s/%s", store.GetNamespace(), store.GetName())
  128. // return client if it points to the very same store
  129. if val.store.GetObjectMeta().Generation == store.GetGeneration() &&
  130. val.store.GetTypeMeta().Kind == store.GetTypeMeta().Kind &&
  131. val.store.GetName() == store.GetName() &&
  132. val.store.GetNamespace() == store.GetNamespace() {
  133. m.log.V(1).Info("reusing stored client",
  134. "provider", fmt.Sprintf("%T", storeProvider),
  135. "store", storeName)
  136. return val.client
  137. }
  138. m.log.V(1).Info("cleaning up client",
  139. "provider", fmt.Sprintf("%T", storeProvider),
  140. "store", storeName)
  141. // if we have a client but it points to a different store
  142. // we must clean it up
  143. val.client.Close(ctx)
  144. delete(m.clientMap, idx)
  145. return nil
  146. }
  147. func storeKey(storeProvider esv1beta1.Provider) clientKey {
  148. return clientKey{
  149. providerType: fmt.Sprintf("%T", storeProvider),
  150. }
  151. }
  152. // getStore fetches the (Cluster)SecretStore from the kube-apiserver
  153. // and returns a GenericStore representing it.
  154. func (m *Manager) getStore(ctx context.Context, storeRef *esv1beta1.SecretStoreRef, namespace string) (esv1beta1.GenericStore, error) {
  155. ref := types.NamespacedName{
  156. Name: storeRef.Name,
  157. }
  158. if storeRef.Kind == esv1beta1.ClusterSecretStoreKind {
  159. var store esv1beta1.ClusterSecretStore
  160. err := m.client.Get(ctx, ref, &store)
  161. if err != nil {
  162. return nil, fmt.Errorf(errGetClusterSecretStore, ref.Name, err)
  163. }
  164. return &store, nil
  165. }
  166. ref.Namespace = namespace
  167. var store esv1beta1.SecretStore
  168. err := m.client.Get(ctx, ref, &store)
  169. if err != nil {
  170. return nil, fmt.Errorf(errGetSecretStore, ref.Name, err)
  171. }
  172. return &store, nil
  173. }
  174. // Close cleans up all clients.
  175. func (m *Manager) Close(ctx context.Context) error {
  176. var errs []string
  177. for key, val := range m.clientMap {
  178. err := val.client.Close(ctx)
  179. if err != nil {
  180. errs = append(errs, err.Error())
  181. }
  182. delete(m.clientMap, key)
  183. }
  184. if len(errs) != 0 {
  185. return fmt.Errorf("errors while closing clients: %s", strings.Join(errs, ", "))
  186. }
  187. return nil
  188. }
  189. func (m *Manager) shouldProcessSecret(store esv1beta1.GenericStore, ns string) (bool, error) {
  190. if store.GetKind() != esv1beta1.ClusterSecretStoreKind {
  191. return true, nil
  192. }
  193. if len(store.GetSpec().Conditions) == 0 {
  194. return true, nil
  195. }
  196. namespaceList := &v1.NamespaceList{}
  197. for _, condition := range store.GetSpec().Conditions {
  198. if condition.NamespaceSelector != nil {
  199. namespaceSelector, err := metav1.LabelSelectorAsSelector(condition.NamespaceSelector)
  200. if err != nil {
  201. return false, err
  202. }
  203. if err := m.client.List(context.Background(), namespaceList, client.MatchingLabelsSelector{Selector: namespaceSelector}); err != nil {
  204. return false, err
  205. }
  206. for _, namespace := range namespaceList.Items {
  207. if namespace.GetName() == ns {
  208. return true, nil // namespace matches the labelselector
  209. }
  210. }
  211. }
  212. if condition.Namespaces != nil {
  213. if slices.Contains(condition.Namespaces, ns) {
  214. return true, nil // namespace in the namespaces list
  215. }
  216. }
  217. }
  218. return false, nil
  219. }
  220. // assertStoreIsUsable assert that the store is ready to use.
  221. func assertStoreIsUsable(store esv1beta1.GenericStore) error {
  222. if store == nil {
  223. return nil
  224. }
  225. condition := secretstore.GetSecretStoreCondition(store.GetStatus(), esv1beta1.SecretStoreReady)
  226. if condition == nil || condition.Status != v1.ConditionTrue {
  227. return fmt.Errorf(errSecretStoreNotReady, store.GetName())
  228. }
  229. return nil
  230. }