client_manager.go 8.6 KB

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