client_manager.go 8.2 KB

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