client_manager.go 8.3 KB

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