client_manager.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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. "regexp"
  17. "strings"
  18. "github.com/go-logr/logr"
  19. v1 "k8s.io/api/core/v1"
  20. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  21. "k8s.io/apimachinery/pkg/labels"
  22. "k8s.io/apimachinery/pkg/types"
  23. ctrl "sigs.k8s.io/controller-runtime"
  24. "sigs.k8s.io/controller-runtime/pkg/client"
  25. esv1beta1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1beta1"
  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. // NewManager constructs a new manager with defaults.
  54. func NewManager(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. func (m *Manager) GetFromStore(ctx context.Context, store esv1beta1.GenericStore, namespace string) (esv1beta1.SecretsClient, error) {
  65. storeProvider, err := esv1beta1.GetProvider(store)
  66. if err != nil {
  67. return nil, err
  68. }
  69. secretClient := m.getStoredClient(ctx, storeProvider, store)
  70. if secretClient != nil {
  71. return secretClient, nil
  72. }
  73. m.log.V(1).Info("creating new client",
  74. "provider", fmt.Sprintf("%T", storeProvider),
  75. "store", fmt.Sprintf("%s/%s", store.GetNamespace(), store.GetName()))
  76. // secret client is created only if we are going to refresh
  77. // this skip an unnecessary check/request in the case we are not going to do anything
  78. secretClient, err = storeProvider.NewClient(ctx, store, m.client, namespace)
  79. if err != nil {
  80. return nil, err
  81. }
  82. idx := storeKey(storeProvider)
  83. m.clientMap[idx] = &clientVal{
  84. client: secretClient,
  85. store: store,
  86. }
  87. return secretClient, nil
  88. }
  89. // Get returns a provider client from the given storeRef or sourceRef.secretStoreRef
  90. // while sourceRef.SecretStoreRef takes precedence over storeRef.
  91. // Do not close the client returned from this func, instead close
  92. // the manager once you're done with recinciling the external secret.
  93. func (m *Manager) Get(ctx context.Context, storeRef esv1beta1.SecretStoreRef, namespace string, sourceRef *esv1beta1.StoreGeneratorSourceRef) (esv1beta1.SecretsClient, error) {
  94. if sourceRef != nil && sourceRef.SecretStoreRef != nil {
  95. storeRef = *sourceRef.SecretStoreRef
  96. }
  97. store, err := m.getStore(ctx, &storeRef, namespace)
  98. if err != nil {
  99. return nil, err
  100. }
  101. // check if store should be handled by this controller instance
  102. if !ShouldProcessStore(store, m.controllerClass) {
  103. return nil, fmt.Errorf("can not reference unmanaged store")
  104. }
  105. // when using ClusterSecretStore, validate the ClusterSecretStore namespace conditions
  106. shouldProcess, err := m.shouldProcessSecret(store, namespace)
  107. if err != nil {
  108. return nil, err
  109. }
  110. if !shouldProcess {
  111. return nil, fmt.Errorf(errClusterStoreMismatch, store.GetName(), namespace)
  112. }
  113. if m.enableFloodgate {
  114. err := assertStoreIsUsable(store)
  115. if err != nil {
  116. return nil, err
  117. }
  118. }
  119. return m.GetFromStore(ctx, store, namespace)
  120. }
  121. // returns a previously stored client from the cache if store and store-version match
  122. // if a client exists for the same provider which points to a different store or store version
  123. // it will be cleaned up.
  124. func (m *Manager) getStoredClient(ctx context.Context, storeProvider esv1beta1.Provider, store esv1beta1.GenericStore) esv1beta1.SecretsClient {
  125. idx := storeKey(storeProvider)
  126. val, ok := m.clientMap[idx]
  127. if !ok {
  128. return nil
  129. }
  130. storeName := fmt.Sprintf("%s/%s", store.GetNamespace(), store.GetName())
  131. // return client if it points to the very same store
  132. if val.store.GetObjectMeta().Generation == store.GetGeneration() &&
  133. val.store.GetTypeMeta().Kind == store.GetTypeMeta().Kind &&
  134. val.store.GetName() == store.GetName() &&
  135. val.store.GetNamespace() == store.GetNamespace() {
  136. m.log.V(1).Info("reusing stored client",
  137. "provider", fmt.Sprintf("%T", storeProvider),
  138. "store", storeName)
  139. return val.client
  140. }
  141. m.log.V(1).Info("cleaning up client",
  142. "provider", fmt.Sprintf("%T", storeProvider),
  143. "store", storeName)
  144. // if we have a client, but it points to a different store
  145. // we must clean it up
  146. val.client.Close(ctx)
  147. delete(m.clientMap, idx)
  148. return nil
  149. }
  150. func storeKey(storeProvider esv1beta1.Provider) clientKey {
  151. return clientKey{
  152. providerType: fmt.Sprintf("%T", storeProvider),
  153. }
  154. }
  155. // getStore fetches the (Cluster)SecretStore from the kube-apiserver
  156. // and returns a GenericStore representing it.
  157. func (m *Manager) getStore(ctx context.Context, storeRef *esv1beta1.SecretStoreRef, namespace string) (esv1beta1.GenericStore, error) {
  158. ref := types.NamespacedName{
  159. Name: storeRef.Name,
  160. }
  161. if storeRef.Kind == esv1beta1.ClusterSecretStoreKind {
  162. var store esv1beta1.ClusterSecretStore
  163. err := m.client.Get(ctx, ref, &store)
  164. if err != nil {
  165. return nil, fmt.Errorf(errGetClusterSecretStore, ref.Name, err)
  166. }
  167. return &store, nil
  168. }
  169. ref.Namespace = namespace
  170. var store esv1beta1.SecretStore
  171. err := m.client.Get(ctx, ref, &store)
  172. if err != nil {
  173. return nil, fmt.Errorf(errGetSecretStore, ref.Name, err)
  174. }
  175. return &store, nil
  176. }
  177. // Close cleans up all clients.
  178. func (m *Manager) Close(ctx context.Context) error {
  179. var errs []string
  180. for key, val := range m.clientMap {
  181. err := val.client.Close(ctx)
  182. if err != nil {
  183. errs = append(errs, err.Error())
  184. }
  185. delete(m.clientMap, key)
  186. }
  187. if len(errs) != 0 {
  188. return fmt.Errorf("errors while closing clients: %s", strings.Join(errs, ", "))
  189. }
  190. return nil
  191. }
  192. func (m *Manager) shouldProcessSecret(store esv1beta1.GenericStore, ns string) (bool, error) {
  193. if store.GetKind() != esv1beta1.ClusterSecretStoreKind {
  194. return true, nil
  195. }
  196. if len(store.GetSpec().Conditions) == 0 {
  197. return true, nil
  198. }
  199. namespace := v1.Namespace{}
  200. if err := m.client.Get(context.Background(), client.ObjectKey{Name: ns}, &namespace); err != nil {
  201. return false, fmt.Errorf("failed to get a namespace %q: %w", ns, err)
  202. }
  203. nsLabels := labels.Set(namespace.GetLabels())
  204. for _, condition := range store.GetSpec().Conditions {
  205. var labelSelectors []*metav1.LabelSelector
  206. if condition.NamespaceSelector != nil {
  207. labelSelectors = append(labelSelectors, condition.NamespaceSelector)
  208. }
  209. for _, n := range condition.Namespaces {
  210. labelSelectors = append(labelSelectors, &metav1.LabelSelector{
  211. MatchLabels: map[string]string{
  212. "kubernetes.io/metadata.name": n,
  213. },
  214. })
  215. }
  216. for _, ls := range labelSelectors {
  217. selector, err := metav1.LabelSelectorAsSelector(ls)
  218. if err != nil {
  219. return false, fmt.Errorf("failed to convert label selector into selector %v: %w", ls, err)
  220. }
  221. if selector.Matches(nsLabels) {
  222. return true, nil
  223. }
  224. }
  225. for _, reg := range condition.NamespaceRegexes {
  226. match, err := regexp.MatchString(reg, ns)
  227. if err != nil {
  228. // Should not happen since store validation already verified the regexes.
  229. return false, fmt.Errorf("failed to compile regex %v: %w", reg, err)
  230. }
  231. if match {
  232. return true, nil
  233. }
  234. }
  235. }
  236. return false, nil
  237. }
  238. // assertStoreIsUsable assert that the store is ready to use.
  239. func assertStoreIsUsable(store esv1beta1.GenericStore) error {
  240. if store == nil {
  241. return nil
  242. }
  243. condition := GetSecretStoreCondition(store.GetStatus(), esv1beta1.SecretStoreReady)
  244. if condition == nil || condition.Status != v1.ConditionTrue {
  245. return fmt.Errorf(errSecretStoreNotReady, store.GetName())
  246. }
  247. return nil
  248. }