externalsecret_controller.go 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051
  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 externalsecret
  14. import (
  15. "context"
  16. "encoding/json"
  17. "errors"
  18. "fmt"
  19. "maps"
  20. "slices"
  21. "strings"
  22. "time"
  23. "github.com/go-logr/logr"
  24. "github.com/prometheus/client_golang/prometheus"
  25. v1 "k8s.io/api/core/v1"
  26. "k8s.io/apimachinery/pkg/api/equality"
  27. apierrors "k8s.io/apimachinery/pkg/api/errors"
  28. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  29. "k8s.io/apimachinery/pkg/fields"
  30. "k8s.io/apimachinery/pkg/labels"
  31. "k8s.io/apimachinery/pkg/runtime"
  32. "k8s.io/apimachinery/pkg/runtime/schema"
  33. "k8s.io/apimachinery/pkg/types"
  34. "k8s.io/client-go/rest"
  35. "k8s.io/client-go/tools/record"
  36. "k8s.io/utils/ptr"
  37. ctrl "sigs.k8s.io/controller-runtime"
  38. "sigs.k8s.io/controller-runtime/pkg/builder"
  39. "sigs.k8s.io/controller-runtime/pkg/client"
  40. "sigs.k8s.io/controller-runtime/pkg/controller"
  41. "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
  42. "sigs.k8s.io/controller-runtime/pkg/handler"
  43. "sigs.k8s.io/controller-runtime/pkg/predicate"
  44. "sigs.k8s.io/controller-runtime/pkg/reconcile"
  45. esv1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1"
  46. // Metrics.
  47. "github.com/external-secrets/external-secrets/pkg/controllers/externalsecret/esmetrics"
  48. ctrlmetrics "github.com/external-secrets/external-secrets/pkg/controllers/metrics"
  49. "github.com/external-secrets/external-secrets/pkg/controllers/util"
  50. "github.com/external-secrets/external-secrets/pkg/utils"
  51. "github.com/external-secrets/external-secrets/pkg/utils/resolvers"
  52. // Loading registered generators.
  53. _ "github.com/external-secrets/external-secrets/pkg/generator/register"
  54. // Loading registered providers.
  55. _ "github.com/external-secrets/external-secrets/pkg/provider/register"
  56. )
  57. const (
  58. fieldOwnerTemplate = "externalsecrets.external-secrets.io/%v"
  59. fieldOwnerTemplateSha = "externalsecrets.external-secrets.io/sha3/%x"
  60. // ExternalSecretFinalizer is the finalizer for ExternalSecret resources.
  61. ExternalSecretFinalizer = "externalsecrets.external-secrets.io/externalsecret-cleanup"
  62. // condition messages for "SecretSynced" reason.
  63. msgSynced = "secret synced"
  64. msgSyncedRetain = "secret retained due to DeletionPolicy=Retain"
  65. // condition messages for "SecretDeleted" reason.
  66. msgDeleted = "secret deleted due to DeletionPolicy=Delete"
  67. // condition messages for "SecretMissing" reason.
  68. msgMissing = "secret will not be created due to CreationPolicy=Merge"
  69. // condition messages for "SecretSyncedError" reason.
  70. msgErrorGetSecretData = "could not get secret data from provider"
  71. msgErrorDeleteSecret = "could not delete secret"
  72. msgErrorDeleteOrphaned = "could not delete orphaned secrets"
  73. msgErrorUpdateSecret = "could not update secret"
  74. msgErrorUpdateImmutable = "could not update secret, target is immutable"
  75. msgErrorBecomeOwner = "failed to take ownership of target secret"
  76. msgErrorIsOwned = "target is owned by another ExternalSecret"
  77. // log messages.
  78. logErrorGetES = "unable to get ExternalSecret"
  79. logErrorUpdateESStatus = "unable to update ExternalSecret status"
  80. logErrorGetSecret = "unable to get Secret"
  81. logErrorPatchSecret = "unable to patch Secret"
  82. logErrorSecretCacheNotSynced = "controller caches for Secret are not in sync"
  83. logErrorUnmanagedStore = "unable to determine if store is managed"
  84. // error formats.
  85. errConvert = "error applying conversion strategy %s to keys: %w"
  86. errRewrite = "error applying rewrite to keys: %w"
  87. errDecode = "error applying decoding strategy %s to data: %w"
  88. errGenerate = "error using generator: %w"
  89. errInvalidKeys = "invalid secret keys (TIP: use rewrite or conversionStrategy to change keys): %w"
  90. errFetchTplFrom = "error fetching templateFrom data: %w"
  91. errApplyTemplate = "could not apply template: %w"
  92. errExecTpl = "could not execute template: %w"
  93. errMutate = "unable to mutate secret %s: %w"
  94. errUpdate = "unable to update secret %s: %w"
  95. errUpdateNotFound = "unable to update secret %s: not found"
  96. errDeleteCreatePolicy = "unable to delete secret %s: creationPolicy=%s is not Owner"
  97. errSecretCachesNotSynced = "controller caches for secret %s are not in sync"
  98. // event messages.
  99. eventCreated = "secret created"
  100. eventUpdated = "secret updated"
  101. eventDeleted = "secret deleted due to DeletionPolicy=Delete"
  102. eventDeletedOrphaned = "secret deleted because it was orphaned"
  103. eventMissingProviderSecret = "secret does not exist at provider using spec.dataFrom[%d]"
  104. eventMissingProviderSecretKey = "secret does not exist at provider using spec.dataFrom[%d] (key=%s)"
  105. )
  106. // these errors are explicitly defined so we can detect them with `errors.Is()`.
  107. var (
  108. ErrSecretImmutable = fmt.Errorf("secret is immutable")
  109. ErrSecretIsOwned = fmt.Errorf("secret is owned by another ExternalSecret")
  110. ErrSecretSetCtrlRef = fmt.Errorf("could not set controller reference on secret")
  111. ErrSecretRemoveCtrlRef = fmt.Errorf("could not remove controller reference on secret")
  112. )
  113. const indexESTargetSecretNameField = ".metadata.targetSecretName"
  114. // Reconciler reconciles a ExternalSecret object.
  115. type Reconciler struct {
  116. client.Client
  117. SecretClient client.Client
  118. Log logr.Logger
  119. Scheme *runtime.Scheme
  120. RestConfig *rest.Config
  121. ControllerClass string
  122. RequeueInterval time.Duration
  123. ClusterSecretStoreEnabled bool
  124. EnableFloodGate bool
  125. EnableGeneratorState bool
  126. recorder record.EventRecorder
  127. }
  128. // Reconcile implements the main reconciliation loop
  129. // for watched objects (ExternalSecret, ClusterSecretStore and SecretStore),
  130. // and updates/creates a Kubernetes secret based on them.
  131. func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (result ctrl.Result, err error) {
  132. log := r.Log.WithValues("ExternalSecret", req.NamespacedName)
  133. resourceLabels := ctrlmetrics.RefineNonConditionMetricLabels(map[string]string{"name": req.Name, "namespace": req.Namespace})
  134. start := time.Now()
  135. syncCallsError := esmetrics.GetCounterVec(esmetrics.SyncCallsErrorKey)
  136. // use closures to dynamically update resourceLabels
  137. defer func() {
  138. esmetrics.GetGaugeVec(esmetrics.ExternalSecretReconcileDurationKey).With(resourceLabels).Set(float64(time.Since(start)))
  139. esmetrics.GetCounterVec(esmetrics.SyncCallsKey).With(resourceLabels).Inc()
  140. }()
  141. externalSecret := &esv1.ExternalSecret{}
  142. err = r.Get(ctx, req.NamespacedName, externalSecret)
  143. if err != nil {
  144. if apierrors.IsNotFound(err) {
  145. // NOTE: this does not actually set the condition on the ExternalSecret, because it does not exist
  146. // this is a hack to disable metrics for deleted ExternalSecrets, see:
  147. // https://github.com/external-secrets/external-secrets/pull/612
  148. conditionSynced := NewExternalSecretCondition(esv1.ExternalSecretDeleted, v1.ConditionFalse, esv1.ConditionReasonSecretDeleted, "Secret was deleted")
  149. SetExternalSecretCondition(&esv1.ExternalSecret{
  150. ObjectMeta: metav1.ObjectMeta{
  151. Name: req.Name,
  152. Namespace: req.Namespace,
  153. },
  154. }, *conditionSynced)
  155. return ctrl.Result{}, nil
  156. }
  157. log.Error(err, logErrorGetES)
  158. syncCallsError.With(resourceLabels).Inc()
  159. return ctrl.Result{}, err
  160. }
  161. // Handle deletion with finalizer
  162. if !externalSecret.GetDeletionTimestamp().IsZero() {
  163. // Always attempt cleanup to handle edge case where finalizer might be removed externally
  164. if err := r.cleanupManagedSecrets(ctx, log, externalSecret); err != nil {
  165. log.Error(err, "failed to cleanup managed secrets")
  166. return ctrl.Result{}, err
  167. }
  168. // Remove finalizer if it exists
  169. if updated := controllerutil.RemoveFinalizer(externalSecret, ExternalSecretFinalizer); updated {
  170. if err := r.Update(ctx, externalSecret); err != nil {
  171. return ctrl.Result{}, err
  172. }
  173. }
  174. return ctrl.Result{}, nil
  175. }
  176. // Add finalizer if it doesn't exist
  177. if updated := controllerutil.AddFinalizer(externalSecret, ExternalSecretFinalizer); updated {
  178. if err := r.Update(ctx, externalSecret); err != nil {
  179. return ctrl.Result{}, err
  180. }
  181. }
  182. // if extended metrics is enabled, refine the time series vector
  183. resourceLabels = ctrlmetrics.RefineLabels(resourceLabels, externalSecret.Labels)
  184. // skip this ExternalSecret if it uses a ClusterSecretStore and the feature is disabled
  185. if shouldSkipClusterSecretStore(r, externalSecret) {
  186. log.V(1).Info("skipping ExternalSecret, ClusterSecretStore feature is disabled")
  187. return ctrl.Result{}, nil
  188. }
  189. // skip this ExternalSecret if it uses any SecretStore not managed by this controller
  190. skip, err := shouldSkipUnmanagedStore(ctx, req.Namespace, r, externalSecret)
  191. if err != nil {
  192. log.Error(err, logErrorUnmanagedStore)
  193. syncCallsError.With(resourceLabels).Inc()
  194. return ctrl.Result{}, err
  195. }
  196. if skip {
  197. log.V(1).Info("skipping ExternalSecret, uses unmanaged SecretStore")
  198. return ctrl.Result{}, nil
  199. }
  200. // the target secret name defaults to the ExternalSecret name, if not explicitly set
  201. secretName := externalSecret.Spec.Target.Name
  202. if secretName == "" {
  203. secretName = externalSecret.Name
  204. }
  205. // fetch the existing secret (from the partial cache)
  206. // - please note that the ~partial cache~ is different from the ~full cache~
  207. // so there can be race conditions between the two caches
  208. // - the WatchesMetadata(v1.Secret{}) in SetupWithManager() is using the partial cache
  209. // so we might receive a reconcile request before the full cache is updated
  210. // - furthermore, when `--enable-managed-secrets-caching` is true, the full cache
  211. // will ONLY include secrets with the "managed" label, so we cant use the full cache
  212. // to reliably determine if a secret exists or not
  213. secretPartial := &metav1.PartialObjectMetadata{}
  214. secretPartial.SetGroupVersionKind(v1.SchemeGroupVersion.WithKind("Secret"))
  215. err = r.Get(ctx, client.ObjectKey{Name: secretName, Namespace: externalSecret.Namespace}, secretPartial)
  216. if err != nil && !apierrors.IsNotFound(err) {
  217. log.Error(err, logErrorGetSecret, "secretName", secretName, "secretNamespace", externalSecret.Namespace)
  218. syncCallsError.With(resourceLabels).Inc()
  219. return ctrl.Result{}, err
  220. }
  221. // if the secret exists but does not have the "managed" label, add the label
  222. // using a PATCH so it is visible in the cache, then requeue immediately
  223. if secretPartial.UID != "" && secretPartial.Labels[esv1.LabelManaged] != esv1.LabelManagedValue {
  224. fqdn := fqdnFor(externalSecret.Name)
  225. patch := client.MergeFrom(secretPartial.DeepCopy())
  226. if secretPartial.Labels == nil {
  227. secretPartial.Labels = make(map[string]string)
  228. }
  229. secretPartial.Labels[esv1.LabelManaged] = esv1.LabelManagedValue
  230. err = r.Patch(ctx, secretPartial, patch, client.FieldOwner(fqdn))
  231. if err != nil {
  232. log.Error(err, logErrorPatchSecret, "secretName", secretName, "secretNamespace", externalSecret.Namespace)
  233. syncCallsError.With(resourceLabels).Inc()
  234. return ctrl.Result{}, err
  235. }
  236. return ctrl.Result{Requeue: true}, nil
  237. }
  238. // fetch existing secret (from the full cache)
  239. // NOTE: we are using the `r.SecretClient` which we only use for managed secrets.
  240. // when `enableManagedSecretsCache` is true, this is a cached client that only sees our managed secrets,
  241. // otherwise it will be the normal controller-runtime client which may be cached or make direct API calls,
  242. // depending on if `enabledSecretCache` is true or false.
  243. existingSecret := &v1.Secret{}
  244. err = r.SecretClient.Get(ctx, client.ObjectKey{Name: secretName, Namespace: externalSecret.Namespace}, existingSecret)
  245. if err != nil && !apierrors.IsNotFound(err) {
  246. log.Error(err, logErrorGetSecret, "secretName", secretName, "secretNamespace", externalSecret.Namespace)
  247. syncCallsError.With(resourceLabels).Inc()
  248. return ctrl.Result{}, err
  249. }
  250. // ensure the full cache is up-to-date
  251. // NOTE: this prevents race conditions between the partial and full cache.
  252. // we return an error so we get an exponential backoff if we end up looping,
  253. // for example, during high cluster load and frequent updates to the target secret by other controllers.
  254. if secretPartial.UID != existingSecret.UID || secretPartial.ResourceVersion != existingSecret.ResourceVersion {
  255. err = fmt.Errorf(errSecretCachesNotSynced, secretName)
  256. log.Error(err, logErrorSecretCacheNotSynced, "secretName", secretName, "secretNamespace", externalSecret.Namespace)
  257. syncCallsError.With(resourceLabels).Inc()
  258. return ctrl.Result{}, err
  259. }
  260. // refresh will be skipped if ALL the following conditions are met:
  261. // 1. refresh interval is not 0
  262. // 2. resource generation of the ExternalSecret has not changed
  263. // 3. the last refresh time of the ExternalSecret is within the refresh interval
  264. // 4. the target secret is valid:
  265. // - it exists
  266. // - it has the correct "managed" label
  267. // - it has the correct "data-hash" annotation
  268. if !shouldRefresh(externalSecret) && isSecretValid(existingSecret, externalSecret) {
  269. log.V(1).Info("skipping refresh")
  270. return r.getRequeueResult(externalSecret), nil
  271. }
  272. // update status of the ExternalSecret when this function returns, if needed.
  273. // NOTE: we use the ability of deferred functions to update named return values `result` and `err`
  274. // NOTE: we dereference the DeepCopy of the status field because status fields are NOT pointers,
  275. // so otherwise the `equality.Semantic.DeepEqual` will always return false.
  276. currentStatus := *externalSecret.Status.DeepCopy()
  277. defer func() {
  278. // if the status has not changed, we don't need to update it
  279. if equality.Semantic.DeepEqual(currentStatus, externalSecret.Status) {
  280. return
  281. }
  282. // update the status of the ExternalSecret, storing any error in a new variable
  283. // if there was no new error, we don't need to change the `result` or `err` values
  284. updateErr := r.Status().Update(ctx, externalSecret)
  285. if updateErr == nil {
  286. return
  287. }
  288. // if we got an update conflict, we should requeue immediately
  289. if apierrors.IsConflict(updateErr) {
  290. log.V(1).Info("conflict while updating status, will requeue")
  291. // we only explicitly request a requeue if the main function did not return an `err`.
  292. // otherwise, we get an annoying log saying that results are ignored when there is an error,
  293. // as errors are always retried.
  294. if err == nil {
  295. result = ctrl.Result{Requeue: true}
  296. }
  297. return
  298. }
  299. // for other errors, log and update the `err` variable if there is no error already
  300. // so the reconciler will requeue the request
  301. log.Error(updateErr, logErrorUpdateESStatus)
  302. if err == nil {
  303. err = updateErr
  304. }
  305. }()
  306. // retrieve the provider secret data.
  307. dataMap, err := r.GetProviderSecretData(ctx, externalSecret)
  308. if err != nil {
  309. r.markAsFailed(msgErrorGetSecretData, err, externalSecret, syncCallsError.With(resourceLabels))
  310. return ctrl.Result{}, err
  311. }
  312. // if no data was found we can delete the secret if needed.
  313. if len(dataMap) == 0 {
  314. switch externalSecret.Spec.Target.DeletionPolicy {
  315. // delete secret and return early.
  316. case esv1.DeletionPolicyDelete:
  317. // safeguard that we only can delete secrets we own.
  318. // this is also implemented in the es validation webhook.
  319. // NOTE: this error cant be fixed by retrying so we don't return an error (which would requeue immediately)
  320. creationPolicy := externalSecret.Spec.Target.CreationPolicy
  321. if creationPolicy != esv1.CreatePolicyOwner {
  322. err = fmt.Errorf(errDeleteCreatePolicy, secretName, creationPolicy)
  323. r.markAsFailed(msgErrorDeleteSecret, err, externalSecret, syncCallsError.With(resourceLabels))
  324. return ctrl.Result{}, nil
  325. }
  326. // delete the secret, if it exists
  327. if existingSecret.UID != "" {
  328. err = r.Delete(ctx, existingSecret)
  329. if err != nil && !apierrors.IsNotFound(err) {
  330. r.markAsFailed(msgErrorDeleteSecret, err, externalSecret, syncCallsError.With(resourceLabels))
  331. return ctrl.Result{}, err
  332. }
  333. r.recorder.Event(externalSecret, v1.EventTypeNormal, esv1.ReasonDeleted, eventDeleted)
  334. }
  335. r.markAsDone(externalSecret, start, log, esv1.ConditionReasonSecretDeleted, msgDeleted)
  336. return r.getRequeueResult(externalSecret), nil
  337. // In case provider secrets don't exist the kubernetes secret will be kept as-is.
  338. case esv1.DeletionPolicyRetain:
  339. r.markAsDone(externalSecret, start, log, esv1.ConditionReasonSecretSynced, msgSyncedRetain)
  340. return r.getRequeueResult(externalSecret), nil
  341. // noop, handled below
  342. case esv1.DeletionPolicyMerge:
  343. }
  344. }
  345. // mutationFunc is a function which can be applied to a secret to make it match the desired state.
  346. mutationFunc := func(secret *v1.Secret) error {
  347. // get information about the current owner of the secret
  348. // - we ignore the API version as it can change over time
  349. // - we ignore the UID for consistency with the SetControllerReference function
  350. currentOwner := metav1.GetControllerOf(secret)
  351. ownerIsESKind := false
  352. ownerIsCurrentES := false
  353. if currentOwner != nil {
  354. currentOwnerGK := schema.FromAPIVersionAndKind(currentOwner.APIVersion, currentOwner.Kind).GroupKind()
  355. ownerIsESKind = currentOwnerGK.String() == esv1.ExtSecretGroupKind
  356. ownerIsCurrentES = ownerIsESKind && currentOwner.Name == externalSecret.Name
  357. }
  358. // if another ExternalSecret is the owner, we should return an error
  359. // otherwise the controller will fight with itself to update the secret.
  360. // note, this does not prevent other controllers from owning the secret.
  361. if ownerIsESKind && !ownerIsCurrentES {
  362. return fmt.Errorf("%w: %s", ErrSecretIsOwned, currentOwner.Name)
  363. }
  364. // if the CreationPolicy is Owner, we should set ourselves as the owner of the secret
  365. if externalSecret.Spec.Target.CreationPolicy == esv1.CreatePolicyOwner {
  366. err = controllerutil.SetControllerReference(externalSecret, secret, r.Scheme)
  367. if err != nil {
  368. return fmt.Errorf("%w: %w", ErrSecretSetCtrlRef, err)
  369. }
  370. }
  371. // if the creation policy is not Owner, we should remove ourselves as the owner
  372. // this could happen if the creation policy was changed after the secret was created
  373. if externalSecret.Spec.Target.CreationPolicy != esv1.CreatePolicyOwner && ownerIsCurrentES {
  374. err = controllerutil.RemoveControllerReference(externalSecret, secret, r.Scheme)
  375. if err != nil {
  376. return fmt.Errorf("%w: %w", ErrSecretRemoveCtrlRef, err)
  377. }
  378. }
  379. // initialize maps within the secret so it's safe to set values
  380. if secret.Annotations == nil {
  381. secret.Annotations = make(map[string]string)
  382. }
  383. if secret.Labels == nil {
  384. secret.Labels = make(map[string]string)
  385. }
  386. if secret.Data == nil {
  387. secret.Data = make(map[string][]byte)
  388. }
  389. // set the immutable flag on the secret if requested by the ExternalSecret
  390. if externalSecret.Spec.Target.Immutable {
  391. secret.Immutable = ptr.To(true)
  392. }
  393. // only apply the template if the secret is mutable or if the secret is new (has no UID)
  394. // otherwise we would mutate an object that is immutable and already exists
  395. objectDoesNotExistOrCanBeMutated := secret.GetUID() == "" || !externalSecret.Spec.Target.Immutable
  396. if objectDoesNotExistOrCanBeMutated {
  397. // get the list of keys that are managed by this ExternalSecret
  398. keys, err := getManagedDataKeys(secret, externalSecret.Name)
  399. if err != nil {
  400. return err
  401. }
  402. // remove any data keys that are managed by this ExternalSecret, so we can re-add them
  403. // this ensures keys added by templates are not left behind when they are removed from the template
  404. for _, key := range keys {
  405. delete(secret.Data, key)
  406. }
  407. // WARNING: this will remove any labels or annotations managed by this ExternalSecret
  408. // so any updates to labels and annotations should be done AFTER this point
  409. err = r.ApplyTemplate(ctx, externalSecret, secret, dataMap)
  410. if err != nil {
  411. return fmt.Errorf(errApplyTemplate, err)
  412. }
  413. }
  414. // we also use a label to keep track of the owner of the secret
  415. // this lets us remove secrets that are no longer needed if the target secret name changes
  416. if externalSecret.Spec.Target.CreationPolicy == esv1.CreatePolicyOwner {
  417. lblValue := utils.ObjectHash(fmt.Sprintf("%v/%v", externalSecret.Namespace, externalSecret.Name))
  418. secret.Labels[esv1.LabelOwner] = lblValue
  419. } else {
  420. // the label should not be set if the creation policy is not Owner
  421. delete(secret.Labels, esv1.LabelOwner)
  422. }
  423. secret.Labels[esv1.LabelManaged] = esv1.LabelManagedValue
  424. secret.Annotations[esv1.AnnotationDataHash] = utils.ObjectHash(secret.Data)
  425. return nil
  426. }
  427. switch externalSecret.Spec.Target.CreationPolicy {
  428. case esv1.CreatePolicyNone:
  429. log.V(1).Info("secret creation skipped due to CreationPolicy=None")
  430. err = nil
  431. case esv1.CreatePolicyMerge:
  432. // update the secret, if it exists
  433. if existingSecret.UID != "" {
  434. err = r.updateSecret(ctx, existingSecret, mutationFunc, externalSecret, secretName)
  435. } else {
  436. // if the secret does not exist, we wait until the next refresh interval
  437. // rather than returning an error which would requeue immediately
  438. r.markAsDone(externalSecret, start, log, esv1.ConditionReasonSecretMissing, msgMissing)
  439. return r.getRequeueResult(externalSecret), nil
  440. }
  441. case esv1.CreatePolicyOrphan:
  442. // create the secret, if it does not exist
  443. if existingSecret.UID == "" {
  444. err = r.createSecret(ctx, mutationFunc, externalSecret, secretName)
  445. } else {
  446. // if the secret exists, we should update it
  447. err = r.updateSecret(ctx, existingSecret, mutationFunc, externalSecret, secretName)
  448. }
  449. case esv1.CreatePolicyOwner:
  450. // we may have orphaned secrets to clean up,
  451. // for example, if the target secret name was changed
  452. err = r.deleteOrphanedSecrets(ctx, externalSecret, secretName)
  453. if err != nil {
  454. r.markAsFailed(msgErrorDeleteOrphaned, err, externalSecret, syncCallsError.With(resourceLabels))
  455. return ctrl.Result{}, err
  456. }
  457. // create the secret, if it does not exist
  458. if existingSecret.UID == "" {
  459. err = r.createSecret(ctx, mutationFunc, externalSecret, secretName)
  460. } else {
  461. // if the secret exists, we should update it
  462. err = r.updateSecret(ctx, existingSecret, mutationFunc, externalSecret, secretName)
  463. }
  464. }
  465. if err != nil {
  466. // if we got an update conflict, we should requeue immediately
  467. if apierrors.IsConflict(err) {
  468. log.V(1).Info("conflict while updating secret, will requeue")
  469. return ctrl.Result{Requeue: true}, nil
  470. }
  471. // detect errors indicating that we failed to set ourselves as the owner of the secret
  472. // NOTE: this error cant be fixed by retrying so we don't return an error (which would requeue immediately)
  473. if errors.Is(err, ErrSecretSetCtrlRef) {
  474. r.markAsFailed(msgErrorBecomeOwner, err, externalSecret, syncCallsError.With(resourceLabels))
  475. return ctrl.Result{}, nil
  476. }
  477. // detect errors indicating that the secret has another ExternalSecret as owner
  478. // NOTE: this error cant be fixed by retrying so we don't return an error (which would requeue immediately)
  479. if errors.Is(err, ErrSecretIsOwned) {
  480. r.markAsFailed(msgErrorIsOwned, err, externalSecret, syncCallsError.With(resourceLabels))
  481. return ctrl.Result{}, nil
  482. }
  483. // detect errors indicating that the secret is immutable
  484. // NOTE: this error cant be fixed by retrying so we don't return an error (which would requeue immediately)
  485. if errors.Is(err, ErrSecretImmutable) {
  486. r.markAsFailed(msgErrorUpdateImmutable, err, externalSecret, syncCallsError.With(resourceLabels))
  487. return ctrl.Result{}, nil
  488. }
  489. r.markAsFailed(msgErrorUpdateSecret, err, externalSecret, syncCallsError.With(resourceLabels))
  490. return ctrl.Result{}, err
  491. }
  492. r.markAsDone(externalSecret, start, log, esv1.ConditionReasonSecretSynced, msgSynced)
  493. return r.getRequeueResult(externalSecret), nil
  494. }
  495. // getRequeueResult create a result with requeueAfter based on the ExternalSecret refresh interval.
  496. func (r *Reconciler) getRequeueResult(externalSecret *esv1.ExternalSecret) ctrl.Result {
  497. // default to the global requeue interval
  498. // note, this will never be used because the CRD has a default value of 1 hour
  499. refreshInterval := r.RequeueInterval
  500. if externalSecret.Spec.RefreshInterval != nil {
  501. refreshInterval = externalSecret.Spec.RefreshInterval.Duration
  502. }
  503. // if the refresh interval is <= 0, we should not requeue
  504. if refreshInterval <= 0 {
  505. return ctrl.Result{}
  506. }
  507. // if the last refresh time is not set, requeue after the refresh interval
  508. // note, this should not happen, as we only call this function on ExternalSecrets
  509. // that have been reconciled at least once
  510. if externalSecret.Status.RefreshTime.IsZero() {
  511. return ctrl.Result{RequeueAfter: refreshInterval}
  512. }
  513. timeSinceLastRefresh := time.Since(externalSecret.Status.RefreshTime.Time)
  514. // if the last refresh time is in the future, we should requeue immediately
  515. // note, this should not happen, as we always refresh an ExternalSecret
  516. // that has a last refresh time in the future
  517. if timeSinceLastRefresh < 0 {
  518. return ctrl.Result{Requeue: true}
  519. }
  520. // if there is time remaining, requeue after the remaining time
  521. if timeSinceLastRefresh < refreshInterval {
  522. return ctrl.Result{RequeueAfter: refreshInterval - timeSinceLastRefresh}
  523. }
  524. // otherwise, requeue immediately
  525. return ctrl.Result{Requeue: true}
  526. }
  527. func (r *Reconciler) markAsDone(externalSecret *esv1.ExternalSecret, start time.Time, log logr.Logger, reason, msg string) {
  528. oldReadyCondition := GetExternalSecretCondition(externalSecret.Status, esv1.ExternalSecretReady)
  529. newReadyCondition := NewExternalSecretCondition(esv1.ExternalSecretReady, v1.ConditionTrue, reason, msg)
  530. SetExternalSecretCondition(externalSecret, *newReadyCondition)
  531. externalSecret.Status.RefreshTime = metav1.NewTime(start)
  532. externalSecret.Status.SyncedResourceVersion = util.GetResourceVersion(externalSecret.ObjectMeta)
  533. // if the status or reason has changed, log at the appropriate verbosity level
  534. if oldReadyCondition == nil || oldReadyCondition.Status != newReadyCondition.Status || oldReadyCondition.Reason != newReadyCondition.Reason {
  535. if newReadyCondition.Reason == esv1.ConditionReasonSecretDeleted {
  536. log.Info("deleted secret")
  537. } else {
  538. log.Info("reconciled secret")
  539. }
  540. } else {
  541. log.V(1).Info("reconciled secret")
  542. }
  543. }
  544. func (r *Reconciler) markAsFailed(msg string, err error, externalSecret *esv1.ExternalSecret, counter prometheus.Counter) {
  545. r.recorder.Event(externalSecret, v1.EventTypeWarning, esv1.ReasonUpdateFailed, err.Error())
  546. conditionSynced := NewExternalSecretCondition(esv1.ExternalSecretReady, v1.ConditionFalse, esv1.ConditionReasonSecretSyncedError, msg)
  547. SetExternalSecretCondition(externalSecret, *conditionSynced)
  548. counter.Inc()
  549. }
  550. func (r *Reconciler) cleanupManagedSecrets(ctx context.Context, log logr.Logger, externalSecret *esv1.ExternalSecret) error {
  551. // Only delete secrets if DeletionPolicy is Delete
  552. if externalSecret.Spec.Target.DeletionPolicy != esv1.DeletionPolicyDelete {
  553. log.V(1).Info("skipping secret deletion due to DeletionPolicy", "policy", externalSecret.Spec.Target.DeletionPolicy)
  554. return nil
  555. }
  556. secretName := externalSecret.Spec.Target.Name
  557. if secretName == "" {
  558. secretName = externalSecret.Name
  559. }
  560. var secret v1.Secret
  561. err := r.Get(ctx, types.NamespacedName{Name: secretName, Namespace: externalSecret.Namespace}, &secret)
  562. if err != nil {
  563. if apierrors.IsNotFound(err) {
  564. return nil
  565. }
  566. return err
  567. }
  568. // Only delete if we own it
  569. if metav1.IsControlledBy(&secret, externalSecret) {
  570. if err := r.Delete(ctx, &secret); err != nil && !apierrors.IsNotFound(err) {
  571. return err
  572. }
  573. log.V(1).Info("deleted managed secret", "secret", secretName)
  574. }
  575. return nil
  576. }
  577. func (r *Reconciler) deleteOrphanedSecrets(ctx context.Context, externalSecret *esv1.ExternalSecret, secretName string) error {
  578. ownerLabel := utils.ObjectHash(fmt.Sprintf("%v/%v", externalSecret.Namespace, externalSecret.Name))
  579. // we use a PartialObjectMetadataList to avoid loading the full secret objects
  580. // and because the Secrets partials are always cached due to WatchesMetadata() in SetupWithManager()
  581. secretListPartial := &metav1.PartialObjectMetadataList{}
  582. secretListPartial.SetGroupVersionKind(v1.SchemeGroupVersion.WithKind("SecretList"))
  583. listOpts := &client.ListOptions{
  584. LabelSelector: labels.SelectorFromSet(map[string]string{
  585. esv1.LabelOwner: ownerLabel,
  586. }),
  587. Namespace: externalSecret.Namespace,
  588. }
  589. if err := r.List(ctx, secretListPartial, listOpts); err != nil {
  590. return err
  591. }
  592. // delete all secrets that are not the target secret
  593. for _, secretPartial := range secretListPartial.Items {
  594. if secretPartial.GetName() != secretName {
  595. err := r.Delete(ctx, &secretPartial)
  596. if err != nil && !apierrors.IsNotFound(err) {
  597. return err
  598. }
  599. r.recorder.Event(externalSecret, v1.EventTypeNormal, esv1.ReasonDeleted, eventDeletedOrphaned)
  600. }
  601. }
  602. return nil
  603. }
  604. // createSecret creates a new secret with the given mutation function.
  605. func (r *Reconciler) createSecret(ctx context.Context, mutationFunc func(secret *v1.Secret) error, es *esv1.ExternalSecret, secretName string) error {
  606. fqdn := fqdnFor(es.Name)
  607. // define and mutate the new secret
  608. newSecret := &v1.Secret{
  609. ObjectMeta: metav1.ObjectMeta{
  610. Name: secretName,
  611. Namespace: es.Namespace,
  612. },
  613. Data: make(map[string][]byte),
  614. }
  615. if err := mutationFunc(newSecret); err != nil {
  616. return err
  617. }
  618. // note, we set field owner even for Create
  619. if err := r.Create(ctx, newSecret, client.FieldOwner(fqdn)); err != nil {
  620. return err
  621. }
  622. // set the binding reference to the secret
  623. // https://github.com/external-secrets/external-secrets/pull/2263
  624. es.Status.Binding = v1.LocalObjectReference{Name: newSecret.Name}
  625. r.recorder.Event(es, v1.EventTypeNormal, esv1.ReasonCreated, eventCreated)
  626. return nil
  627. }
  628. func (r *Reconciler) updateSecret(ctx context.Context, existingSecret *v1.Secret, mutationFunc func(secret *v1.Secret) error, es *esv1.ExternalSecret, secretName string) error {
  629. fqdn := fqdnFor(es.Name)
  630. // fail if the secret does not exist
  631. // this should never happen because we check this before calling this function
  632. if existingSecret.UID == "" {
  633. return fmt.Errorf(errUpdateNotFound, secretName)
  634. }
  635. // set the binding reference to the secret
  636. // https://github.com/external-secrets/external-secrets/pull/2263
  637. es.Status.Binding = v1.LocalObjectReference{Name: secretName}
  638. // mutate a copy of the existing secret with the mutation function
  639. updatedSecret := existingSecret.DeepCopy()
  640. if err := mutationFunc(updatedSecret); err != nil {
  641. return fmt.Errorf(errMutate, updatedSecret.Name, err)
  642. }
  643. // if the secret does not need to be updated, return early
  644. if equality.Semantic.DeepEqual(existingSecret, updatedSecret) {
  645. return nil
  646. }
  647. // if the existing secret is immutable, we can only update the object metadata
  648. if ptr.Deref(existingSecret.Immutable, false) {
  649. // check if the metadata was changed
  650. metadataChanged := !equality.Semantic.DeepEqual(existingSecret.ObjectMeta, updatedSecret.ObjectMeta)
  651. // check if the immutable data/type was changed
  652. var dataChanged bool
  653. if metadataChanged {
  654. // update the `existingSecret` object with the metadata from `updatedSecret`
  655. // this lets us compare the objects to see if the immutable data/type was changed
  656. existingSecret.ObjectMeta = *updatedSecret.ObjectMeta.DeepCopy()
  657. dataChanged = !equality.Semantic.DeepEqual(existingSecret, updatedSecret)
  658. // because we use labels and annotations to keep track of the secret,
  659. // we need to update the metadata, regardless of if the immutable data was changed
  660. // NOTE: we are using the `existingSecret` object here, as we ONLY want to update the metadata,
  661. // and we previously copied the metadata from the `updatedSecret` object
  662. if err := r.Update(ctx, existingSecret, client.FieldOwner(fqdn)); err != nil {
  663. // if we get a conflict, we should return early to requeue immediately
  664. // note, we don't wrap this error so we can handle it in the caller
  665. if apierrors.IsConflict(err) {
  666. return err
  667. }
  668. return fmt.Errorf(errUpdate, existingSecret.Name, err)
  669. }
  670. } else {
  671. // we know there was some change in the secret (or we would have returned early)
  672. // we know the metadata was NOT changed (metadataChanged == false)
  673. // so, the only thing that could have changed is the immutable data/type fields
  674. dataChanged = true
  675. }
  676. // if the immutable data was changed, we should return an error
  677. if dataChanged {
  678. return fmt.Errorf(errUpdate, existingSecret.Name, ErrSecretImmutable)
  679. }
  680. }
  681. // update the secret
  682. if err := r.Update(ctx, updatedSecret, client.FieldOwner(fqdn)); err != nil {
  683. // if we get a conflict, we should return early to requeue immediately
  684. // note, we don't wrap this error so we can handle it in the caller
  685. if apierrors.IsConflict(err) {
  686. return err
  687. }
  688. return fmt.Errorf(errUpdate, updatedSecret.Name, err)
  689. }
  690. r.recorder.Event(es, v1.EventTypeNormal, esv1.ReasonUpdated, eventUpdated)
  691. return nil
  692. }
  693. // getManagedDataKeys returns the list of data keys in a secret which are managed by a specified owner.
  694. func getManagedDataKeys(secret *v1.Secret, fieldOwner string) ([]string, error) {
  695. return getManagedFieldKeys(secret, fieldOwner, func(fields map[string]any) []string {
  696. dataFields := fields["f:data"]
  697. if dataFields == nil {
  698. return nil
  699. }
  700. df, ok := dataFields.(map[string]any)
  701. if !ok {
  702. return nil
  703. }
  704. return slices.Collect(maps.Keys(df))
  705. })
  706. }
  707. func getManagedFieldKeys(
  708. secret *v1.Secret,
  709. fieldOwner string,
  710. process func(fields map[string]any) []string,
  711. ) ([]string, error) {
  712. fqdn := fqdnFor(fieldOwner)
  713. var keys []string
  714. for _, v := range secret.ObjectMeta.ManagedFields {
  715. if v.Manager != fqdn {
  716. continue
  717. }
  718. fields := make(map[string]any)
  719. err := json.Unmarshal(v.FieldsV1.Raw, &fields)
  720. if err != nil {
  721. return nil, fmt.Errorf("error unmarshaling managed fields: %w", err)
  722. }
  723. for _, key := range process(fields) {
  724. if key == "." {
  725. continue
  726. }
  727. keys = append(keys, strings.TrimPrefix(key, "f:"))
  728. }
  729. }
  730. return keys, nil
  731. }
  732. func shouldSkipClusterSecretStore(r *Reconciler, es *esv1.ExternalSecret) bool {
  733. return !r.ClusterSecretStoreEnabled && es.Spec.SecretStoreRef.Kind == esv1.ClusterSecretStoreKind
  734. }
  735. // shouldSkipUnmanagedStore iterates over all secretStore references in the externalSecret spec,
  736. // fetches the store and evaluates the controllerClass property.
  737. // Returns true if any storeRef points to store with a non-matching controllerClass.
  738. func shouldSkipUnmanagedStore(ctx context.Context, namespace string, r *Reconciler, es *esv1.ExternalSecret) (bool, error) {
  739. var storeList []esv1.SecretStoreRef
  740. if es.Spec.SecretStoreRef.Name != "" {
  741. storeList = append(storeList, es.Spec.SecretStoreRef)
  742. }
  743. for _, ref := range es.Spec.Data {
  744. if ref.SourceRef != nil {
  745. storeList = append(storeList, ref.SourceRef.SecretStoreRef)
  746. }
  747. }
  748. for _, ref := range es.Spec.DataFrom {
  749. if ref.SourceRef != nil && ref.SourceRef.SecretStoreRef != nil {
  750. storeList = append(storeList, *ref.SourceRef.SecretStoreRef)
  751. }
  752. // verify that generator's controllerClass matches
  753. if ref.SourceRef != nil && ref.SourceRef.GeneratorRef != nil {
  754. _, obj, err := resolvers.GeneratorRef(ctx, r.Client, r.Scheme, namespace, ref.SourceRef.GeneratorRef)
  755. if err != nil {
  756. if apierrors.IsNotFound(err) {
  757. // skip non-existent generators
  758. continue
  759. }
  760. if errors.Is(err, resolvers.ErrUnableToGetGenerator) {
  761. // skip generators that we can't get (e.g. due to being invalid)
  762. continue
  763. }
  764. return false, err
  765. }
  766. skipGenerator, err := shouldSkipGenerator(r, obj)
  767. if err != nil {
  768. return false, err
  769. }
  770. if skipGenerator {
  771. return true, nil
  772. }
  773. }
  774. }
  775. for _, ref := range storeList {
  776. var store esv1.GenericStore
  777. switch ref.Kind {
  778. case esv1.SecretStoreKind, "":
  779. store = &esv1.SecretStore{}
  780. case esv1.ClusterSecretStoreKind:
  781. store = &esv1.ClusterSecretStore{}
  782. namespace = ""
  783. default:
  784. return false, fmt.Errorf("unsupported secret store kind: %s", ref.Kind)
  785. }
  786. err := r.Get(ctx, types.NamespacedName{
  787. Name: ref.Name,
  788. Namespace: namespace,
  789. }, store)
  790. if err != nil {
  791. if apierrors.IsNotFound(err) {
  792. // skip non-existent stores
  793. continue
  794. }
  795. return false, err
  796. }
  797. class := store.GetSpec().Controller
  798. if class != "" && class != r.ControllerClass {
  799. return true, nil
  800. }
  801. }
  802. return false, nil
  803. }
  804. func shouldRefresh(es *esv1.ExternalSecret) bool {
  805. switch es.Spec.RefreshPolicy {
  806. case esv1.RefreshPolicyCreatedOnce:
  807. if es.Status.SyncedResourceVersion == "" || es.Status.RefreshTime.IsZero() {
  808. return true
  809. }
  810. return false
  811. case esv1.RefreshPolicyOnChange:
  812. if es.Status.SyncedResourceVersion == "" || es.Status.RefreshTime.IsZero() {
  813. return true
  814. }
  815. return es.Status.SyncedResourceVersion != util.GetResourceVersion(es.ObjectMeta)
  816. case esv1.RefreshPolicyPeriodic:
  817. return shouldRefreshPeriodic(es)
  818. default:
  819. return shouldRefreshPeriodic(es)
  820. }
  821. }
  822. func shouldRefreshPeriodic(es *esv1.ExternalSecret) bool {
  823. // if the refresh interval is 0, and we have synced previously, we should not refresh
  824. if es.Spec.RefreshInterval.Duration <= 0 && es.Status.SyncedResourceVersion != "" {
  825. return false
  826. }
  827. // if the ExternalSecret has been updated, we should refresh
  828. if es.Status.SyncedResourceVersion != util.GetResourceVersion(es.ObjectMeta) {
  829. return true
  830. }
  831. // if the last refresh time is zero, we should refresh
  832. if es.Status.RefreshTime.IsZero() {
  833. return true
  834. }
  835. // if the last refresh time is in the future, we should refresh
  836. if es.Status.RefreshTime.Time.After(time.Now()) {
  837. return true
  838. }
  839. // if the last refresh time + refresh interval is before now, we should refresh
  840. return es.Status.RefreshTime.Add(es.Spec.RefreshInterval.Duration).Before(time.Now())
  841. }
  842. // isSecretValid checks if the secret exists, and it's data is consistent with the calculated hash.
  843. func isSecretValid(existingSecret *v1.Secret, es *esv1.ExternalSecret) bool {
  844. // Secret is always valid with `CreationPolicy=Orphan`
  845. if es.Spec.Target.CreationPolicy == esv1.CreatePolicyOrphan {
  846. return true
  847. }
  848. if existingSecret.UID == "" {
  849. return false
  850. }
  851. // if the managed label is missing or incorrect, then it's invalid
  852. if existingSecret.Labels[esv1.LabelManaged] != esv1.LabelManagedValue {
  853. return false
  854. }
  855. // if the data-hash annotation is missing or incorrect, then it's invalid
  856. // this is how we know if the data has chanced since we last updated the secret
  857. if existingSecret.Annotations[esv1.AnnotationDataHash] != utils.ObjectHash(existingSecret.Data) {
  858. return false
  859. }
  860. return true
  861. }
  862. // SetupWithManager returns a new controller builder that will be started by the provided Manager.
  863. func (r *Reconciler) SetupWithManager(mgr ctrl.Manager, opts controller.Options) error {
  864. r.recorder = mgr.GetEventRecorderFor("external-secrets")
  865. // index ExternalSecrets based on the target secret name,
  866. // this lets us quickly find all ExternalSecrets which target a specific Secret
  867. if err := mgr.GetFieldIndexer().IndexField(context.Background(), &esv1.ExternalSecret{}, indexESTargetSecretNameField, func(obj client.Object) []string {
  868. es := obj.(*esv1.ExternalSecret)
  869. // if the target name is set, use that as the index
  870. if es.Spec.Target.Name != "" {
  871. return []string{es.Spec.Target.Name}
  872. }
  873. // otherwise, use the ExternalSecret name
  874. return []string{es.Name}
  875. }); err != nil {
  876. return err
  877. }
  878. // predicate function to ignore secret events unless they have the "managed" label
  879. secretHasESLabel := predicate.NewPredicateFuncs(func(object client.Object) bool {
  880. value, hasLabel := object.GetLabels()[esv1.LabelManaged]
  881. return hasLabel && value == esv1.LabelManagedValue
  882. })
  883. return ctrl.NewControllerManagedBy(mgr).
  884. WithOptions(opts).
  885. For(&esv1.ExternalSecret{}).
  886. // we cant use Owns(), as we don't set ownerReferences when the creationPolicy is not Owner.
  887. // we use WatchesMetadata() to reduce memory usage, as otherwise we have to process full secret objects.
  888. WatchesMetadata(
  889. &v1.Secret{},
  890. handler.EnqueueRequestsFromMapFunc(r.findObjectsForSecret),
  891. builder.WithPredicates(predicate.ResourceVersionChangedPredicate{}, secretHasESLabel),
  892. ).
  893. Complete(r)
  894. }
  895. func (r *Reconciler) findObjectsForSecret(ctx context.Context, secret client.Object) []reconcile.Request {
  896. externalSecretsList := &esv1.ExternalSecretList{}
  897. listOps := &client.ListOptions{
  898. FieldSelector: fields.OneTermEqualSelector(indexESTargetSecretNameField, secret.GetName()),
  899. Namespace: secret.GetNamespace(),
  900. }
  901. err := r.List(ctx, externalSecretsList, listOps)
  902. if err != nil {
  903. return []reconcile.Request{}
  904. }
  905. requests := make([]reconcile.Request, len(externalSecretsList.Items))
  906. for i := range externalSecretsList.Items {
  907. requests[i] = reconcile.Request{
  908. NamespacedName: types.NamespacedName{
  909. Name: externalSecretsList.Items[i].GetName(),
  910. Namespace: externalSecretsList.Items[i].GetNamespace(),
  911. },
  912. }
  913. }
  914. return requests
  915. }