client_manager.go 9.4 KB

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