common.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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
  14. import (
  15. "context"
  16. "errors"
  17. "fmt"
  18. "time"
  19. "github.com/go-logr/logr"
  20. v1 "k8s.io/api/core/v1"
  21. apierrors "k8s.io/apimachinery/pkg/api/errors"
  22. "k8s.io/apimachinery/pkg/fields"
  23. "k8s.io/apimachinery/pkg/types"
  24. "k8s.io/client-go/tools/record"
  25. ctrl "sigs.k8s.io/controller-runtime"
  26. "sigs.k8s.io/controller-runtime/pkg/client"
  27. "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
  28. ctrlreconcile "sigs.k8s.io/controller-runtime/pkg/reconcile"
  29. esapi "github.com/external-secrets/external-secrets/apis/externalsecrets/v1"
  30. esv1alpha1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1alpha1"
  31. "github.com/external-secrets/external-secrets/pkg/controllers/secretstore/metrics"
  32. "github.com/external-secrets/external-secrets/pkg/controllers/secretstore/storeutil"
  33. "github.com/external-secrets/external-secrets/runtime/clientmanager"
  34. // Load registered providers.
  35. _ "github.com/external-secrets/external-secrets/pkg/register"
  36. )
  37. const (
  38. errStoreClient = "could not get provider client: %w"
  39. errValidationFailed = "could not validate provider: %w"
  40. errValidationUnknownMsg = "could not determine validation status"
  41. errPatchStatus = "unable to patch status: %w"
  42. errUnableCreateClient = "unable to create client"
  43. errUnableValidateStore = "unable to validate store"
  44. msgStoreValidated = "store validated"
  45. msgStoreNotMaintained = "store isn't currently maintained. Please plan and prepare accordingly."
  46. msgStoreDeprecated = "store is deprecated and will be removed on the next minor release. Please plan and prepare accordingly."
  47. // Finalizer for SecretStores when they have PushSecrets with DeletionPolicy=Delete.
  48. secretStoreFinalizer = "secretstore.externalsecrets.io/finalizer"
  49. )
  50. var errValidationUnknown = errors.New(errValidationUnknownMsg)
  51. // Opts holds the options for the reconcile function.
  52. type Opts struct {
  53. ControllerClass string
  54. GaugeVecGetter metrics.GaugeVevGetter
  55. Recorder record.EventRecorder
  56. RequeueInterval time.Duration
  57. }
  58. func reconcile(ctx context.Context, req ctrl.Request, ss esapi.GenericStore, cl client.Client, isPushSecretEnabled bool, log logr.Logger, opts Opts) (ctrl.Result, error) {
  59. if !storeutil.ShouldProcessStore(ss, opts.ControllerClass) {
  60. log.V(1).Info("skip store")
  61. return ctrl.Result{}, nil
  62. }
  63. // Manage finalizer if PushSecret feature is enabled.
  64. if isPushSecretEnabled {
  65. finalizersUpdated, err := handleFinalizer(ctx, cl, ss)
  66. if err != nil {
  67. return ctrl.Result{}, err
  68. }
  69. if finalizersUpdated {
  70. log.V(1).Info("updating resource with finalizer changes")
  71. if err := cl.Update(ctx, ss); err != nil {
  72. return ctrl.Result{}, err
  73. }
  74. }
  75. }
  76. requeueInterval := opts.RequeueInterval
  77. if ss.GetSpec().RefreshInterval != 0 {
  78. requeueInterval = time.Second * time.Duration(ss.GetSpec().RefreshInterval)
  79. }
  80. // patch status when done processing
  81. p := client.MergeFrom(ss.Copy())
  82. storeUID := ss.GetObjectMeta().UID
  83. defer func() {
  84. current := ss.Copy()
  85. if getErr := cl.Get(ctx, req.NamespacedName, current); getErr != nil {
  86. if apierrors.IsNotFound(getErr) {
  87. log.V(1).Info("store was deleted, skipping status patch")
  88. return
  89. }
  90. log.Error(getErr, "unable to get store for status patch")
  91. return
  92. }
  93. if current.GetObjectMeta().UID != storeUID {
  94. log.V(1).Info("store was replaced, skipping status patch")
  95. return
  96. }
  97. err := cl.Status().Patch(ctx, ss, p)
  98. if err != nil {
  99. log.Error(err, errPatchStatus)
  100. }
  101. }()
  102. // validateStore modifies the store conditions
  103. // we have to patch the status
  104. log.V(1).Info("validating")
  105. err := validateStore(ctx, req.Namespace, opts.ControllerClass, ss, cl, opts.GaugeVecGetter, opts.Recorder)
  106. if err != nil {
  107. log.Error(err, "unable to validate store")
  108. // in case of validation status unknown, validateStore will mark
  109. // the store as ready but we should show ReasonValidationUnknown
  110. if errors.Is(err, errValidationUnknown) {
  111. return ctrl.Result{RequeueAfter: requeueInterval}, nil
  112. }
  113. return ctrl.Result{}, err
  114. }
  115. storeProvider, err := esapi.GetProvider(ss)
  116. if err != nil {
  117. return ctrl.Result{}, err
  118. }
  119. isMaintained, err := esapi.GetMaintenanceStatus(ss)
  120. if err != nil {
  121. return ctrl.Result{}, err
  122. }
  123. annotations := ss.GetAnnotations()
  124. _, ok := annotations["external-secrets.io/ignore-maintenance-checks"]
  125. if !ok {
  126. switch isMaintained {
  127. case esapi.MaintenanceStatusNotMaintained:
  128. opts.Recorder.Event(ss, v1.EventTypeWarning, esapi.StoreUnmaintained, msgStoreNotMaintained)
  129. case esapi.MaintenanceStatusDeprecated:
  130. opts.Recorder.Event(ss, v1.EventTypeWarning, esapi.StoreDeprecated, msgStoreDeprecated)
  131. case esapi.MaintenanceStatusMaintained:
  132. default:
  133. // no warnings
  134. }
  135. }
  136. capStatus := esapi.SecretStoreStatus{
  137. Capabilities: storeProvider.Capabilities(),
  138. Conditions: ss.GetStatus().Conditions,
  139. }
  140. ss.SetStatus(capStatus)
  141. opts.Recorder.Event(ss, v1.EventTypeNormal, esapi.ReasonStoreValid, msgStoreValidated)
  142. cond := NewSecretStoreCondition(esapi.SecretStoreReady, v1.ConditionTrue, esapi.ReasonStoreValid, msgStoreValidated)
  143. SetExternalSecretCondition(ss, *cond, opts.GaugeVecGetter)
  144. return ctrl.Result{
  145. RequeueAfter: requeueInterval,
  146. }, err
  147. }
  148. // validateStore tries to construct a new client
  149. // if it fails sets a condition and writes events.
  150. func validateStore(ctx context.Context, namespace, controllerClass string, store esapi.GenericStore,
  151. client client.Client, gaugeVecGetter metrics.GaugeVevGetter, recorder record.EventRecorder) error {
  152. mgr := clientmanager.NewManager(client, controllerClass, false)
  153. defer func() {
  154. _ = mgr.Close(ctx)
  155. }()
  156. cl, err := mgr.GetFromStore(ctx, store, namespace)
  157. if err != nil {
  158. cond := NewSecretStoreCondition(esapi.SecretStoreReady, v1.ConditionFalse, esapi.ReasonInvalidProviderConfig, errUnableCreateClient)
  159. SetExternalSecretCondition(store, *cond, gaugeVecGetter)
  160. recorder.Event(store, v1.EventTypeWarning, esapi.ReasonInvalidProviderConfig, err.Error())
  161. return fmt.Errorf(errStoreClient, err)
  162. }
  163. validationResult, err := cl.Validate()
  164. if err != nil {
  165. if validationResult == esapi.ValidationResultUnknown {
  166. cond := NewSecretStoreCondition(esapi.SecretStoreReady, v1.ConditionTrue, esapi.ReasonValidationUnknown, errValidationUnknownMsg)
  167. SetExternalSecretCondition(store, *cond, gaugeVecGetter)
  168. recorder.Event(store, v1.EventTypeWarning, esapi.ReasonValidationUnknown, err.Error())
  169. return errValidationUnknown
  170. }
  171. cond := NewSecretStoreCondition(esapi.SecretStoreReady, v1.ConditionFalse, esapi.ReasonInvalidProviderConfig, errUnableValidateStore)
  172. SetExternalSecretCondition(store, *cond, gaugeVecGetter)
  173. recorder.Event(store, v1.EventTypeWarning, esapi.ReasonInvalidProviderConfig, err.Error())
  174. return fmt.Errorf(errValidationFailed, err)
  175. }
  176. return nil
  177. }
  178. // ShouldProcessStore returns true if the store should be processed.
  179. // This is a wrapper around storeutil.ShouldProcessStore for backward compatibility.
  180. func ShouldProcessStore(store esapi.GenericStore, class string) bool {
  181. return storeutil.ShouldProcessStore(store, class)
  182. }
  183. // AssertStoreIsUsable asserts that the store is ready to use.
  184. // This is a wrapper around storeutil.AssertStoreIsUsable for backward compatibility.
  185. func AssertStoreIsUsable(store esapi.GenericStore) error {
  186. return storeutil.AssertStoreIsUsable(store)
  187. }
  188. // handleFinalizer manages the finalizer for ClusterSecretStores and SecretStores.
  189. func handleFinalizer(ctx context.Context, cl client.Client, store esapi.GenericStore) (finalizersUpdated bool, err error) {
  190. log := logr.FromContextOrDiscard(ctx)
  191. hasPushSecretsWithDeletePolicy, err := hasPushSecretsWithDeletePolicy(ctx, cl, store)
  192. if err != nil {
  193. return false, fmt.Errorf("failed to check PushSecrets: %w", err)
  194. }
  195. storeKind := store.GetKind()
  196. // If the store is being deleted and has the finalizer, check if we can remove it
  197. if !store.GetObjectMeta().DeletionTimestamp.IsZero() {
  198. if hasPushSecretsWithDeletePolicy {
  199. log.Info("cannot remove finalizer, there are still PushSecrets with DeletionPolicy=Delete that reference this store")
  200. return false, nil
  201. }
  202. if controllerutil.RemoveFinalizer(store, secretStoreFinalizer) {
  203. log.Info(fmt.Sprintf("removed finalizer from %s during deletion", storeKind))
  204. return true, nil
  205. }
  206. return false, nil
  207. }
  208. // If the store is not being deleted, manage the finalizer based on PushSecrets
  209. if hasPushSecretsWithDeletePolicy {
  210. if controllerutil.AddFinalizer(store, secretStoreFinalizer) {
  211. log.Info(fmt.Sprintf("added finalizer to %s due to PushSecrets with DeletionPolicy=Delete", storeKind))
  212. return true, nil
  213. }
  214. } else {
  215. if controllerutil.RemoveFinalizer(store, secretStoreFinalizer) {
  216. log.Info(fmt.Sprintf("removed finalizer from %s, no more PushSecrets with DeletionPolicy=Delete", storeKind))
  217. return true, nil
  218. }
  219. }
  220. return false, nil
  221. }
  222. // hasPushSecretsWithDeletePolicy checks if there are any PushSecrets with DeletionPolicy=Delete
  223. // that reference this SecretStore using the controller-runtime index.
  224. func hasPushSecretsWithDeletePolicy(ctx context.Context, cl client.Client, store esapi.GenericStore) (bool, error) {
  225. // Search for PushSecrets that have already synced from this store.
  226. found, err := hasSyncedPushSecrets(ctx, cl, store)
  227. if err != nil {
  228. return false, fmt.Errorf("failed to check for synced push secrets: %w", err)
  229. }
  230. if found {
  231. return true, nil
  232. }
  233. // Search for PushSecrets that reference this store, but may not have synced yet.
  234. found, err = hasUnsyncedPushSecretRefs(ctx, cl, store)
  235. if err != nil {
  236. return false, fmt.Errorf("failed to check for unsynced push secret refs: %w", err)
  237. }
  238. return found, nil
  239. }
  240. // hasSyncedPushSecrets uses the 'status.syncedPushSecrets' index from PushSecrets to efficiently find
  241. // PushSecrets with DeletionPolicy=Delete that have already been synced from the given store.
  242. func hasSyncedPushSecrets(ctx context.Context, cl client.Client, store esapi.GenericStore) (bool, error) {
  243. storeKey := fmt.Sprintf("%s/%s", store.GetKind(), store.GetName())
  244. opts := &client.ListOptions{
  245. FieldSelector: fields.OneTermEqualSelector("status.syncedPushSecrets", storeKey),
  246. }
  247. if store.GetKind() == esapi.SecretStoreKind {
  248. opts.Namespace = store.GetNamespace()
  249. }
  250. var pushSecretList esv1alpha1.PushSecretList
  251. if err := cl.List(ctx, &pushSecretList, opts); err != nil {
  252. return false, err
  253. }
  254. // If any PushSecrets are found, return true. The index ensures they have DeletionPolicy=Delete.
  255. return len(pushSecretList.Items) > 0, nil
  256. }
  257. // hasUnsyncedPushSecretRefs searches for all PushSecrets with DeletionPolicy=Delete
  258. // and checks if any of them reference the given store (by name or labelSelector).
  259. // This is necessary for cases where the reference exists, but synchronization has not occurred yet.
  260. func hasUnsyncedPushSecretRefs(ctx context.Context, cl client.Client, store esapi.GenericStore) (bool, error) {
  261. opts := &client.ListOptions{
  262. FieldSelector: fields.OneTermEqualSelector("spec.deletionPolicy", string(esv1alpha1.PushSecretDeletionPolicyDelete)),
  263. }
  264. if store.GetKind() == esapi.SecretStoreKind {
  265. opts.Namespace = store.GetNamespace()
  266. }
  267. var pushSecretList esv1alpha1.PushSecretList
  268. if err := cl.List(ctx, &pushSecretList, opts); err != nil {
  269. return false, err
  270. }
  271. for _, ps := range pushSecretList.Items {
  272. for _, storeRef := range ps.Spec.SecretStoreRefs {
  273. if storeMatchesRef(store, storeRef) {
  274. return true, nil
  275. }
  276. }
  277. }
  278. return false, nil
  279. }
  280. // findStoresForPushSecret finds SecretStores or ClusterSecretStores that should be reconciled when a PushSecret changes.
  281. func findStoresForPushSecret(ctx context.Context, c client.Client, obj client.Object, storeList client.ObjectList) []ctrlreconcile.Request {
  282. ps, ok := obj.(*esv1alpha1.PushSecret)
  283. if !ok {
  284. return nil
  285. }
  286. var isClusterScoped bool
  287. switch storeList.(type) {
  288. case *esapi.ClusterSecretStoreList:
  289. isClusterScoped = true
  290. case *esapi.SecretStoreList:
  291. isClusterScoped = false
  292. default:
  293. return nil
  294. }
  295. listOpts := make([]client.ListOption, 0)
  296. if !isClusterScoped {
  297. listOpts = append(listOpts, client.InNamespace(ps.GetNamespace()))
  298. }
  299. if err := c.List(ctx, storeList, listOpts...); err != nil {
  300. return nil
  301. }
  302. requests := make([]ctrlreconcile.Request, 0)
  303. var stores []esapi.GenericStore
  304. switch sl := storeList.(type) {
  305. case *esapi.SecretStoreList:
  306. for i := range sl.Items {
  307. stores = append(stores, &sl.Items[i])
  308. }
  309. case *esapi.ClusterSecretStoreList:
  310. for i := range sl.Items {
  311. stores = append(stores, &sl.Items[i])
  312. }
  313. }
  314. for _, store := range stores {
  315. if shouldReconcileSecretStoreForPushSecret(store, ps) {
  316. req := ctrlreconcile.Request{
  317. NamespacedName: types.NamespacedName{
  318. Name: store.GetName(),
  319. },
  320. }
  321. if !isClusterScoped {
  322. req.NamespacedName.Namespace = store.GetNamespace()
  323. }
  324. requests = append(requests, req)
  325. }
  326. }
  327. return requests
  328. }