common.go 13 KB

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