client_manager.go 9.0 KB

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