common.go 12 KB

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