client_manager.go 10 KB

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