externalsecret_controller.go 41 KB

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