externalsecret_controller.go 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435
  1. /*
  2. Copyright © The ESO Authors
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. https://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. // Package externalsecret implements the controller for managing ExternalSecret resources
  14. package externalsecret
  15. import (
  16. "context"
  17. "encoding/json"
  18. "errors"
  19. "fmt"
  20. "maps"
  21. "slices"
  22. "strings"
  23. "time"
  24. "github.com/go-logr/logr"
  25. "github.com/prometheus/client_golang/prometheus"
  26. v1 "k8s.io/api/core/v1"
  27. "k8s.io/apimachinery/pkg/api/equality"
  28. apierrors "k8s.io/apimachinery/pkg/api/errors"
  29. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  30. "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
  31. "k8s.io/apimachinery/pkg/fields"
  32. "k8s.io/apimachinery/pkg/labels"
  33. "k8s.io/apimachinery/pkg/runtime"
  34. "k8s.io/apimachinery/pkg/runtime/schema"
  35. "k8s.io/apimachinery/pkg/types"
  36. "k8s.io/client-go/rest"
  37. "k8s.io/client-go/tools/record"
  38. "k8s.io/utils/ptr"
  39. ctrl "sigs.k8s.io/controller-runtime"
  40. "sigs.k8s.io/controller-runtime/pkg/builder"
  41. "sigs.k8s.io/controller-runtime/pkg/client"
  42. "sigs.k8s.io/controller-runtime/pkg/controller"
  43. "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
  44. "sigs.k8s.io/controller-runtime/pkg/event"
  45. "sigs.k8s.io/controller-runtime/pkg/handler"
  46. "sigs.k8s.io/controller-runtime/pkg/predicate"
  47. "sigs.k8s.io/controller-runtime/pkg/reconcile"
  48. esv1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1"
  49. // Metrics.
  50. "github.com/external-secrets/external-secrets/pkg/controllers/externalsecret/esmetrics"
  51. ctrlmetrics "github.com/external-secrets/external-secrets/pkg/controllers/metrics"
  52. ctrlutil "github.com/external-secrets/external-secrets/pkg/controllers/util"
  53. "github.com/external-secrets/external-secrets/runtime/esutils"
  54. "github.com/external-secrets/external-secrets/runtime/esutils/resolvers"
  55. // Loading registered generators.
  56. _ "github.com/external-secrets/external-secrets/pkg/register"
  57. )
  58. const (
  59. fieldOwnerTemplate = "externalsecrets.external-secrets.io/%v"
  60. fieldOwnerTemplateSha = "externalsecrets.external-secrets.io/sha3/%x"
  61. // ExternalSecretFinalizer is the finalizer for ExternalSecret resources.
  62. ExternalSecretFinalizer = "externalsecrets.external-secrets.io/externalsecret-cleanup"
  63. // condition messages for "SecretSynced" reason.
  64. msgSynced = "secret synced"
  65. msgSyncedRetain = "secret retained due to DeletionPolicy=Retain"
  66. // condition messages for "SecretDeleted" reason.
  67. msgDeleted = "secret deleted due to DeletionPolicy=Delete"
  68. // condition messages for "SecretMissing" reason.
  69. msgMissing = "secret will not be created due to CreationPolicy=Merge"
  70. // condition messages for "SecretSyncedError" reason.
  71. msgErrorGetSecretData = "could not get secret data from provider"
  72. msgErrorDeleteSecret = "could not delete secret"
  73. msgErrorDeleteOrphaned = "could not delete orphaned secrets"
  74. msgErrorUpdateSecret = "could not update secret"
  75. msgErrorUpdateImmutable = "could not update secret, target is immutable"
  76. msgErrorBecomeOwner = "failed to take ownership of target secret"
  77. msgErrorIsOwned = "target is owned by another ExternalSecret"
  78. // log messages.
  79. logErrorGetES = "unable to get ExternalSecret"
  80. logErrorUpdateESStatus = "unable to update ExternalSecret status"
  81. logErrorGetSecret = "unable to get Secret"
  82. logErrorPatchSecret = "unable to patch Secret"
  83. logErrorSecretCacheNotSynced = "controller caches for Secret are not in sync"
  84. logErrorUnmanagedStore = "unable to determine if store is managed"
  85. // log messages for mutating / destructive secret operations, emitted at
  86. // V(1) so they are opt-in. They only ever carry key names, never values.
  87. logSecretDeleted = "deleted secret"
  88. logManagedSecretDeleted = "deleted managed secret"
  89. logSecretDeletedOrphaned = "deleted orphaned secret"
  90. logSecretDataChanged = "secret data keys changed"
  91. // error formats.
  92. errConvert = "error applying conversion strategy %s to keys: %w"
  93. errRewrite = "error applying rewrite to keys: %w"
  94. errDecode = "error applying decoding strategy %s to data: %w"
  95. errGenerate = "error using generator: %w"
  96. errInvalidKeys = "invalid secret keys (TIP: use rewrite or conversionStrategy to change keys): %w"
  97. errFetchTplFrom = "error fetching templateFrom data: %w"
  98. errApplyTemplate = "could not apply template: %w"
  99. errExecTpl = "could not execute template: %w"
  100. errMutate = "unable to mutate secret %s: %w"
  101. errUpdate = "unable to update secret %s: %w"
  102. errUpdateNotFound = "unable to update secret %s: not found"
  103. errDeleteCreatePolicy = "unable to delete secret %s: creationPolicy=%s is not Owner"
  104. errSecretCachesNotSynced = "controller caches for secret %s are not in sync"
  105. // event messages.
  106. eventCreated = "secret created"
  107. eventUpdated = "secret updated"
  108. eventDeleted = "secret deleted due to DeletionPolicy=Delete"
  109. eventDeletedOrphaned = "secret deleted because it was orphaned"
  110. eventMissingProviderSecret = "secret does not exist at provider using spec.dataFrom[%d]"
  111. eventMissingProviderSecretKey = "secret does not exist at provider using spec.dataFrom[%d] (key=%s)"
  112. // cacheSyncRetryDelay is used when partial and full secret caches are temporarily out of sync.
  113. cacheSyncRetryDelay = 200 * time.Millisecond
  114. )
  115. // these errors are explicitly defined so we can detect them with `errors.Is()`.
  116. var (
  117. ErrSecretImmutable = fmt.Errorf("secret is immutable")
  118. ErrSecretIsOwned = fmt.Errorf("secret is owned by another ExternalSecret")
  119. ErrSecretSetCtrlRef = fmt.Errorf("could not set controller reference on secret")
  120. ErrSecretRemoveCtrlRef = fmt.Errorf("could not remove controller reference on secret")
  121. )
  122. const (
  123. indexESTargetSecretNameField = ".metadata.targetSecretName"
  124. indexESTargetResourceField = ".spec.target.resource"
  125. )
  126. // Reconciler reconciles a ExternalSecret object.
  127. type Reconciler struct {
  128. client.Client
  129. SecretClient client.Client
  130. APIReader client.Reader
  131. EnableSecretAPIReadOnCacheMismatch bool
  132. Log logr.Logger
  133. Scheme *runtime.Scheme
  134. RestConfig *rest.Config
  135. ControllerClass string
  136. RequeueInterval time.Duration
  137. ClusterSecretStoreEnabled bool
  138. EnableFloodGate bool
  139. EnableGeneratorState bool
  140. AllowGenericTargets bool
  141. recorder record.EventRecorder
  142. // informerManager manages dynamic informers for generic targets
  143. informerManager InformerManager
  144. }
  145. // Reconcile implements the main reconciliation loop
  146. // for watched objects (ExternalSecret, ClusterSecretStore and SecretStore),
  147. // and updates/creates a Kubernetes secret based on them.
  148. func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (result ctrl.Result, err error) {
  149. log := r.Log.WithValues("ExternalSecret", req.NamespacedName)
  150. resourceLabels := ctrlmetrics.RefineNonConditionMetricLabels(map[string]string{"name": req.Name, "namespace": req.Namespace})
  151. start := time.Now()
  152. syncCallsError := esmetrics.GetCounterVec(esmetrics.SyncCallsErrorKey)
  153. // use closures to dynamically update resourceLabels
  154. defer func() {
  155. esmetrics.GetGaugeVec(esmetrics.ExternalSecretReconcileDurationKey).With(resourceLabels).Set(float64(time.Since(start)))
  156. esmetrics.GetCounterVec(esmetrics.SyncCallsKey).With(resourceLabels).Inc()
  157. }()
  158. externalSecret := &esv1.ExternalSecret{}
  159. err = r.Get(ctx, req.NamespacedName, externalSecret)
  160. if err != nil {
  161. if apierrors.IsNotFound(err) {
  162. // NOTE: this does not actually set the condition on the ExternalSecret, because it does not exist
  163. // this is a hack to disable metrics for deleted ExternalSecrets, see:
  164. // https://github.com/external-secrets/external-secrets/pull/612
  165. conditionSynced := NewExternalSecretCondition(esv1.ExternalSecretDeleted, v1.ConditionFalse, esv1.ConditionReasonSecretDeleted, "Secret was deleted")
  166. SetExternalSecretCondition(&esv1.ExternalSecret{
  167. ObjectMeta: metav1.ObjectMeta{
  168. Name: req.Name,
  169. Namespace: req.Namespace,
  170. },
  171. }, *conditionSynced)
  172. return ctrl.Result{}, nil
  173. }
  174. log.Error(err, logErrorGetES)
  175. syncCallsError.With(resourceLabels).Inc()
  176. return ctrl.Result{}, err
  177. }
  178. // Handle deletion with finalizer
  179. if !externalSecret.GetDeletionTimestamp().IsZero() {
  180. // Always attempt cleanup to handle edge case where finalizer might be removed externally
  181. if err := r.cleanupManagedSecrets(ctx, log, externalSecret); err != nil {
  182. log.Error(err, "failed to cleanup managed secrets")
  183. return ctrl.Result{}, err
  184. }
  185. // Release informer for generic targets
  186. if isGenericTarget(externalSecret) && r.informerManager != nil {
  187. gvk := getTargetGVK(externalSecret)
  188. esName := types.NamespacedName{Name: externalSecret.Name, Namespace: externalSecret.Namespace}
  189. if err := r.informerManager.ReleaseInformer(ctx, gvk, esName); err != nil {
  190. log.Error(err, "failed to release informer for generic target",
  191. "group", gvk.Group,
  192. "version", gvk.Version,
  193. "kind", gvk.Kind)
  194. }
  195. }
  196. // Remove finalizer if it exists
  197. // Use Patch instead of Update to avoid claiming ownership of spec fields like refreshInterval
  198. patch := client.MergeFrom(externalSecret.DeepCopy())
  199. if updated := controllerutil.RemoveFinalizer(externalSecret, ExternalSecretFinalizer); updated {
  200. if err := r.Patch(ctx, externalSecret, patch); err != nil {
  201. return ctrl.Result{}, err
  202. }
  203. }
  204. return ctrl.Result{}, nil
  205. }
  206. // Add finalizer if it doesn't exist
  207. // Use Patch instead of Update to avoid claiming ownership of spec fields like refreshInterval
  208. patch := client.MergeFrom(externalSecret.DeepCopy())
  209. if updated := controllerutil.AddFinalizer(externalSecret, ExternalSecretFinalizer); updated {
  210. if err := r.Patch(ctx, externalSecret, patch); err != nil {
  211. return ctrl.Result{}, err
  212. }
  213. }
  214. // if extended metrics is enabled, refine the time series vector
  215. resourceLabels = ctrlmetrics.RefineLabels(resourceLabels, externalSecret.Labels)
  216. // skip this ExternalSecret if it uses a ClusterSecretStore and the feature is disabled
  217. if shouldSkipClusterSecretStore(r, externalSecret) {
  218. log.V(1).Info("skipping ExternalSecret, ClusterSecretStore feature is disabled")
  219. return ctrl.Result{}, nil
  220. }
  221. // skip this ExternalSecret if it uses any SecretStore not managed by this controller
  222. skip, err := shouldSkipUnmanagedStore(ctx, req.Namespace, r, externalSecret)
  223. if err != nil {
  224. log.Error(err, logErrorUnmanagedStore)
  225. syncCallsError.With(resourceLabels).Inc()
  226. return ctrl.Result{}, err
  227. }
  228. if skip {
  229. log.V(1).Info("skipping ExternalSecret, uses unmanaged SecretStore")
  230. return ctrl.Result{}, nil
  231. }
  232. // if this is a generic target, use a different reconciliation path
  233. if isGenericTarget(externalSecret) {
  234. // update the status of the ExternalSecret when this function returns, if needed
  235. currentStatus := *externalSecret.Status.DeepCopy()
  236. defer func() {
  237. if equality.Semantic.DeepEqual(currentStatus, externalSecret.Status) {
  238. return
  239. }
  240. updateErr := r.Status().Update(ctx, externalSecret)
  241. if updateErr != nil && !apierrors.IsConflict(updateErr) {
  242. log.Error(updateErr, logErrorUpdateESStatus)
  243. }
  244. }()
  245. // validate generic target configuration early
  246. if err := r.validateGenericTarget(log, externalSecret); err != nil {
  247. r.markAsFailed("invalid generic target", err, externalSecret, syncCallsError.With(resourceLabels), esv1.ConditionReasonSecretSyncedError)
  248. return ctrl.Result{}, nil // don't requeue as this is a configuration error that is not recoverable
  249. }
  250. return r.reconcileGenericTarget(ctx, externalSecret, log, start, resourceLabels, syncCallsError)
  251. }
  252. // the target secret name defaults to the ExternalSecret name, if not explicitly set
  253. secretName := externalSecret.Spec.Target.Name
  254. if secretName == "" {
  255. secretName = externalSecret.Name
  256. }
  257. // fetch the existing secret (from the partial cache)
  258. // - please note that the ~partial cache~ is different from the ~full cache~
  259. // so there can be race conditions between the two caches
  260. // - the WatchesMetadata(v1.Secret{}) in SetupWithManager() is using the partial cache
  261. // so we might receive a reconcile request before the full cache is updated
  262. // - furthermore, when `--enable-managed-secrets-caching` is true, the full cache
  263. // will ONLY include secrets with the "managed" label, so we cant use the full cache
  264. // to reliably determine if a secret exists or not
  265. secretPartial := &metav1.PartialObjectMetadata{}
  266. secretPartial.SetGroupVersionKind(v1.SchemeGroupVersion.WithKind("Secret"))
  267. err = r.Get(ctx, client.ObjectKey{Name: secretName, Namespace: externalSecret.Namespace}, secretPartial)
  268. if err != nil && !apierrors.IsNotFound(err) {
  269. log.Error(err, logErrorGetSecret, "secretName", secretName, "secretNamespace", externalSecret.Namespace)
  270. syncCallsError.With(resourceLabels).Inc()
  271. return ctrl.Result{}, err
  272. }
  273. // if the secret exists but does not have the "managed" label, add the label
  274. // using a PATCH so it is visible in the cache, then requeue immediately
  275. if secretPartial.UID != "" && secretPartial.Labels[esv1.LabelManaged] != esv1.LabelManagedValue {
  276. fqdn := fqdnFor(externalSecret.Name)
  277. patch := client.MergeFrom(secretPartial.DeepCopy())
  278. if secretPartial.Labels == nil {
  279. secretPartial.Labels = make(map[string]string)
  280. }
  281. secretPartial.Labels[esv1.LabelManaged] = esv1.LabelManagedValue
  282. err = r.Patch(ctx, secretPartial, patch, client.FieldOwner(fqdn))
  283. if err != nil {
  284. log.Error(err, logErrorPatchSecret, "secretName", secretName, "secretNamespace", externalSecret.Namespace)
  285. syncCallsError.With(resourceLabels).Inc()
  286. return ctrl.Result{}, err
  287. }
  288. return ctrl.Result{Requeue: true}, nil
  289. }
  290. // fetch existing secret (from the full cache)
  291. // NOTE: we are using the `r.SecretClient` which we only use for managed secrets.
  292. // when `enableManagedSecretsCache` is true, this is a cached client that only sees our managed secrets,
  293. // otherwise it will be the normal controller-runtime client which may be cached or make direct API calls,
  294. // depending on if `enabledSecretCache` is true or false.
  295. existingSecret := &v1.Secret{}
  296. err = r.SecretClient.Get(ctx, client.ObjectKey{Name: secretName, Namespace: externalSecret.Namespace}, existingSecret)
  297. if err != nil && !apierrors.IsNotFound(err) {
  298. log.Error(err, logErrorGetSecret, "secretName", secretName, "secretNamespace", externalSecret.Namespace)
  299. syncCallsError.With(resourceLabels).Inc()
  300. return ctrl.Result{}, err
  301. }
  302. // ensure the full cache is up-to-date
  303. // NOTE: this prevents race conditions between the partial and full cache.
  304. // if enabled, we verify against the API server before retrying to avoid unnecessary error backoff
  305. // when the cache is temporarily stale.
  306. existingSecret, cacheNotSynced, getErr := r.resolveSecretCacheMismatch(ctx, client.ObjectKey{Name: secretName, Namespace: externalSecret.Namespace}, secretPartial, existingSecret)
  307. if getErr != nil && !apierrors.IsNotFound(getErr) {
  308. log.Error(getErr, logErrorGetSecret, "secretName", secretName, "secretNamespace", externalSecret.Namespace)
  309. syncCallsError.With(resourceLabels).Inc()
  310. return ctrl.Result{}, getErr
  311. }
  312. if cacheNotSynced {
  313. log.V(1).Info(logErrorSecretCacheNotSynced, "secretName", secretName, "secretNamespace", externalSecret.Namespace)
  314. return ctrl.Result{RequeueAfter: cacheSyncRetryDelay}, nil
  315. }
  316. // refresh will be skipped if ALL the following conditions are met:
  317. // 1. refresh interval is not 0
  318. // 2. resource generation of the ExternalSecret has not changed
  319. // 3. the last refresh time of the ExternalSecret is within the refresh interval
  320. // 4. the target secret is valid:
  321. // - it exists
  322. // - it has the correct "managed" label
  323. // - it has the correct "data-hash" annotation
  324. if !shouldRefresh(externalSecret) && isSecretValid(existingSecret, externalSecret) {
  325. log.V(1).Info("skipping refresh")
  326. return r.getRequeueResult(externalSecret), nil
  327. }
  328. // update status of the ExternalSecret when this function returns, if needed.
  329. // NOTE: we use the ability of deferred functions to update named return values `result` and `err`
  330. // NOTE: we dereference the DeepCopy of the status field because status fields are NOT pointers,
  331. // so otherwise the `equality.Semantic.DeepEqual` will always return false.
  332. currentStatus := *externalSecret.Status.DeepCopy()
  333. defer func() {
  334. // if the status has not changed, we don't need to update it
  335. if equality.Semantic.DeepEqual(currentStatus, externalSecret.Status) {
  336. return
  337. }
  338. // update the status of the ExternalSecret, storing any error in a new variable
  339. // if there was no new error, we don't need to change the `result` or `err` values
  340. updateErr := r.Status().Update(ctx, externalSecret)
  341. if updateErr == nil {
  342. return
  343. }
  344. // if we got an update conflict, we should requeue immediately
  345. if apierrors.IsConflict(updateErr) {
  346. log.V(1).Info("conflict while updating status, will requeue")
  347. // we only explicitly request a requeue if the main function did not return an `err`.
  348. // otherwise, we get an annoying log saying that results are ignored when there is an error,
  349. // as errors are always retried.
  350. if err == nil {
  351. result = ctrl.Result{Requeue: true}
  352. }
  353. return
  354. }
  355. // for other errors, log and update the `err` variable if there is no error already
  356. // so the reconciler will requeue the request
  357. log.Error(updateErr, logErrorUpdateESStatus)
  358. if err == nil {
  359. err = updateErr
  360. }
  361. }()
  362. // retrieve the provider secret data.
  363. dataMap, err := r.GetProviderSecretData(ctx, externalSecret)
  364. if err != nil {
  365. r.markAsFailed(msgErrorGetSecretData, err, externalSecret, syncCallsError.With(resourceLabels), esv1.ConditionReasonSecretSyncedError)
  366. return ctrl.Result{}, err
  367. }
  368. // if no data was found we can delete the secret if needed.
  369. if len(dataMap) == 0 {
  370. switch externalSecret.Spec.Target.DeletionPolicy {
  371. // delete secret and return early.
  372. case esv1.DeletionPolicyDelete:
  373. // safeguard that we only can delete secrets we own.
  374. // this is also implemented in the es validation webhook.
  375. // NOTE: this error cant be fixed by retrying so we don't return an error (which would requeue immediately)
  376. creationPolicy := externalSecret.Spec.Target.CreationPolicy
  377. if creationPolicy != esv1.CreatePolicyOwner {
  378. err = fmt.Errorf(errDeleteCreatePolicy, secretName, creationPolicy)
  379. r.markAsFailed(msgErrorDeleteSecret, err, externalSecret, syncCallsError.With(resourceLabels), esv1.ConditionReasonSecretSyncedError)
  380. return ctrl.Result{}, nil
  381. }
  382. // delete the secret, if it exists
  383. if existingSecret.UID != "" {
  384. err = r.Delete(ctx, existingSecret)
  385. if err != nil && !apierrors.IsNotFound(err) {
  386. r.markAsFailed(msgErrorDeleteSecret, err, externalSecret, syncCallsError.With(resourceLabels), esv1.ConditionReasonSecretSyncedError)
  387. return ctrl.Result{}, err
  388. }
  389. log.V(1).Info(logSecretDeleted, "secret", secretName, "namespace", externalSecret.Namespace, "reason", "DeletionPolicy=Delete and provider returned no data")
  390. r.recorder.Event(externalSecret, v1.EventTypeNormal, esv1.ReasonDeleted, eventDeleted)
  391. }
  392. r.markAsDone(externalSecret, start, log, esv1.ConditionReasonSecretDeleted, msgDeleted)
  393. return r.getRequeueResult(externalSecret), nil
  394. // In case provider secrets don't exist the kubernetes secret will be kept as-is.
  395. case esv1.DeletionPolicyRetain:
  396. r.markAsDone(externalSecret, start, log, esv1.ConditionReasonSecretSynced, msgSyncedRetain)
  397. return r.getRequeueResult(externalSecret), nil
  398. // noop, handled below
  399. case esv1.DeletionPolicyMerge:
  400. }
  401. }
  402. // mutationFunc is a function which can be applied to a secret to make it match the desired state.
  403. mutationFunc := func(secret *v1.Secret) error {
  404. // initialize maps within the secret so it's safe to set values
  405. if secret.Annotations == nil {
  406. secret.Annotations = make(map[string]string)
  407. }
  408. if secret.Labels == nil {
  409. secret.Labels = make(map[string]string)
  410. }
  411. if secret.Data == nil {
  412. secret.Data = make(map[string][]byte)
  413. }
  414. // set the immutable flag on the secret if requested by the ExternalSecret
  415. if externalSecret.Spec.Target.Immutable {
  416. secret.Immutable = new(true)
  417. }
  418. // only apply the template if the secret is mutable or if the secret is new (has no UID)
  419. // otherwise we would mutate an object that is immutable and already exists
  420. objectDoesNotExistOrCanBeMutated := secret.GetUID() == "" || !externalSecret.Spec.Target.Immutable
  421. if objectDoesNotExistOrCanBeMutated {
  422. // get the list of keys that are managed by this ExternalSecret
  423. keys, err := getManagedDataKeys(secret, externalSecret.Name)
  424. if err != nil {
  425. return err
  426. }
  427. // remove any data keys that are managed by this ExternalSecret, so we can re-add them
  428. // this ensures keys added by templates are not left behind when they are removed from the template
  429. for _, key := range keys {
  430. delete(secret.Data, key)
  431. }
  432. // WARNING: this will remove any labels or annotations managed by this ExternalSecret
  433. // so any updates to labels and annotations should be done AFTER this point
  434. err = r.ApplyTemplate(ctx, externalSecret, secret, dataMap)
  435. if err != nil {
  436. return fmt.Errorf(errApplyTemplate, err)
  437. }
  438. }
  439. if err := r.applyOwnership(externalSecret, secret); err != nil {
  440. return err
  441. }
  442. secret.Labels[esv1.LabelManaged] = esv1.LabelManagedValue
  443. secret.Annotations[esv1.AnnotationDataHash] = esutils.ObjectHash(secret.Data)
  444. return nil
  445. }
  446. switch externalSecret.Spec.Target.CreationPolicy {
  447. case esv1.CreatePolicyNone:
  448. log.V(1).Info("secret creation skipped due to CreationPolicy=None")
  449. err = nil
  450. case esv1.CreatePolicyMerge:
  451. // update the secret, if it exists
  452. if existingSecret.UID != "" {
  453. err = r.updateSecret(ctx, log, existingSecret, mutationFunc, externalSecret, secretName)
  454. } else {
  455. // if the secret does not exist, we wait until the next refresh interval
  456. // rather than returning an error which would requeue immediately
  457. r.markAsDone(externalSecret, start, log, esv1.ConditionReasonSecretMissing, msgMissing)
  458. return r.getRequeueResult(externalSecret), nil
  459. }
  460. case esv1.CreatePolicyOrphan:
  461. // create the secret, if it does not exist
  462. if existingSecret.UID == "" {
  463. err = r.createSecret(ctx, mutationFunc, externalSecret, secretName)
  464. } else {
  465. // if the secret exists, we should update it
  466. err = r.updateSecret(ctx, log, existingSecret, mutationFunc, externalSecret, secretName)
  467. }
  468. case esv1.CreatePolicyOwner:
  469. // we may have orphaned secrets to clean up,
  470. // for example, if the target secret name was changed
  471. err = r.deleteOrphanedSecrets(ctx, log, externalSecret, secretName)
  472. if err != nil {
  473. r.markAsFailed(msgErrorDeleteOrphaned, err, externalSecret, syncCallsError.With(resourceLabels), esv1.ConditionReasonSecretSyncedError)
  474. return ctrl.Result{}, err
  475. }
  476. // create the secret, if it does not exist
  477. if existingSecret.UID == "" {
  478. err = r.createSecret(ctx, mutationFunc, externalSecret, secretName)
  479. } else {
  480. // if the secret exists, we should update it
  481. err = r.updateSecret(ctx, log, existingSecret, mutationFunc, externalSecret, secretName)
  482. }
  483. }
  484. if err != nil {
  485. // if we got an update conflict, we should requeue immediately
  486. if apierrors.IsConflict(err) {
  487. log.V(1).Info("conflict while updating secret, will requeue")
  488. return ctrl.Result{Requeue: true}, nil
  489. }
  490. // detect errors indicating that we failed to set ourselves as the owner of the secret
  491. // NOTE: this error cant be fixed by retrying so we don't return an error (which would requeue immediately)
  492. if errors.Is(err, ErrSecretSetCtrlRef) {
  493. r.markAsFailed(msgErrorBecomeOwner, err, externalSecret, syncCallsError.With(resourceLabels), esv1.ConditionReasonSecretSyncedError)
  494. return ctrl.Result{}, nil
  495. }
  496. // detect errors indicating that the secret has another ExternalSecret as owner
  497. // NOTE: this error cant be fixed by retrying so we don't return an error (which would requeue immediately)
  498. if errors.Is(err, ErrSecretIsOwned) {
  499. r.markAsFailed(msgErrorIsOwned, err, externalSecret, syncCallsError.With(resourceLabels), esv1.ConditionReasonSecretSyncedError)
  500. return ctrl.Result{}, nil
  501. }
  502. // detect errors indicating that the secret is immutable
  503. // NOTE: this error cant be fixed by retrying so we don't return an error (which would requeue immediately)
  504. if errors.Is(err, ErrSecretImmutable) {
  505. r.markAsFailed(msgErrorUpdateImmutable, err, externalSecret, syncCallsError.With(resourceLabels), esv1.ConditionReasonSecretSyncedError)
  506. return ctrl.Result{}, nil
  507. }
  508. r.markAsFailed(msgErrorUpdateSecret, err, externalSecret, syncCallsError.With(resourceLabels), esv1.ConditionReasonSecretSyncedError)
  509. return ctrl.Result{}, err
  510. }
  511. r.markAsDone(externalSecret, start, log, esv1.ConditionReasonSecretSynced, msgSynced)
  512. return r.getRequeueResult(externalSecret), nil
  513. }
  514. // reconcileGenericTarget handles reconciliation for generic targets (ConfigMaps, Custom Resources).
  515. func (r *Reconciler) reconcileGenericTarget(
  516. ctx context.Context,
  517. externalSecret *esv1.ExternalSecret,
  518. log logr.Logger,
  519. start time.Time,
  520. resourceLabels map[string]string,
  521. syncCallsError *prometheus.CounterVec,
  522. ) (ctrl.Result, error) {
  523. var existing *unstructured.Unstructured
  524. if externalSecret.Spec.Target.CreationPolicy == esv1.CreatePolicyMerge ||
  525. externalSecret.Spec.Target.CreationPolicy == esv1.CreatePolicyOrphan ||
  526. externalSecret.Spec.Target.CreationPolicy == esv1.CreatePolicyOwner {
  527. var getErr error
  528. existing, getErr = r.getGenericResource(ctx, log, externalSecret)
  529. if getErr != nil && !apierrors.IsNotFound(getErr) {
  530. r.markAsFailed("could not get target resource", getErr, externalSecret, syncCallsError.With(resourceLabels), esv1.ConditionReasonResourceSyncedError)
  531. return ctrl.Result{}, getErr
  532. }
  533. }
  534. valid, err := isGenericTargetValid(existing, externalSecret)
  535. if err != nil {
  536. log.V(1).Info("unable to validate target", "error", err)
  537. return ctrl.Result{}, err
  538. }
  539. if !shouldRefresh(externalSecret) && valid {
  540. log.V(1).Info("skipping refresh of generic target")
  541. return r.getRequeueResult(externalSecret), nil
  542. }
  543. dataMap, err := r.GetProviderSecretData(ctx, externalSecret)
  544. if err != nil {
  545. r.markAsFailed(msgErrorGetSecretData, err, externalSecret, syncCallsError.With(resourceLabels), esv1.ConditionReasonResourceSyncedError)
  546. return ctrl.Result{}, err
  547. }
  548. if len(dataMap) == 0 {
  549. switch externalSecret.Spec.Target.DeletionPolicy {
  550. case esv1.DeletionPolicyDelete:
  551. creationPolicy := externalSecret.Spec.Target.CreationPolicy
  552. if creationPolicy != esv1.CreatePolicyOwner {
  553. err = fmt.Errorf("unable to delete resource: creationPolicy=%s is not Owner", creationPolicy)
  554. r.markAsFailed("could not delete resource", err, externalSecret, syncCallsError.With(resourceLabels), esv1.ConditionReasonResourceSyncedError)
  555. return ctrl.Result{}, nil
  556. }
  557. err = r.deleteGenericResource(ctx, log, externalSecret)
  558. if err != nil {
  559. r.markAsFailed("could not delete resource", err, externalSecret, syncCallsError.With(resourceLabels), esv1.ConditionReasonResourceSyncedError)
  560. return ctrl.Result{}, err
  561. }
  562. r.markAsDone(externalSecret, start, log, esv1.ConditionReasonResourceDeleted, msgDeleted)
  563. return r.getRequeueResult(externalSecret), nil
  564. case esv1.DeletionPolicyRetain:
  565. r.markAsDone(externalSecret, start, log, esv1.ConditionReasonResourceSynced, msgSyncedRetain)
  566. return r.getRequeueResult(externalSecret), nil
  567. case esv1.DeletionPolicyMerge:
  568. }
  569. }
  570. // For Merge policy with existing resource, pass it to applyTemplateToManifest
  571. // so templates are applied to the existing resource instead of creating a new one
  572. var baseObj *unstructured.Unstructured
  573. if externalSecret.Spec.Target.CreationPolicy == esv1.CreatePolicyMerge && existing != nil {
  574. baseObj = existing
  575. }
  576. // render the template for the manifest
  577. obj, err := r.applyTemplateToManifest(ctx, externalSecret, dataMap, baseObj)
  578. if err != nil {
  579. r.markAsFailed("could not apply template to manifest", err, externalSecret, syncCallsError.With(resourceLabels), esv1.ConditionReasonResourceSyncedError)
  580. return ctrl.Result{}, err
  581. }
  582. // handle creation policies
  583. switch externalSecret.Spec.Target.CreationPolicy {
  584. case esv1.CreatePolicyNone:
  585. log.V(1).Info("resource creation skipped due to CreationPolicy=None")
  586. err = nil
  587. case esv1.CreatePolicyMerge:
  588. // for Merge policy, only update if resource exists
  589. if existing == nil || existing.GetUID() == "" {
  590. r.markAsDone(externalSecret, start, log, esv1.ConditionReasonResourceMissing, "resource will not be created due to CreationPolicy=Merge")
  591. return r.getRequeueResult(externalSecret), nil
  592. }
  593. obj.SetResourceVersion(existing.GetResourceVersion())
  594. obj.SetUID(existing.GetUID())
  595. // update the existing resource
  596. err = r.updateGenericResource(ctx, log, externalSecret, obj)
  597. case esv1.CreatePolicyOrphan, esv1.CreatePolicyOwner:
  598. if existing != nil {
  599. obj.SetResourceVersion(existing.GetResourceVersion())
  600. obj.SetUID(existing.GetUID())
  601. err = r.updateGenericResource(ctx, log, externalSecret, obj)
  602. } else {
  603. err = r.createGenericResource(ctx, log, externalSecret, obj)
  604. }
  605. }
  606. if err != nil {
  607. // if we got an update conflict, requeue immediately
  608. if apierrors.IsConflict(err) {
  609. log.V(1).Info("conflict while updating resource, will requeue")
  610. return ctrl.Result{RequeueAfter: 1 * time.Second}, nil
  611. }
  612. r.markAsFailed(msgErrorUpdateSecret, err, externalSecret, syncCallsError.With(resourceLabels), esv1.ConditionReasonResourceSyncedError)
  613. return ctrl.Result{}, err
  614. }
  615. if externalSecret.Spec.Target.CreationPolicy != esv1.CreatePolicyNone {
  616. gvk := getTargetGVK(externalSecret)
  617. esName := types.NamespacedName{Name: externalSecret.Name, Namespace: externalSecret.Namespace}
  618. if _, err := r.informerManager.EnsureInformer(ctx, gvk, esName); err != nil {
  619. log.Error(err, "failed to register informer for generic target, drift detection may not work",
  620. "group", gvk.Group,
  621. "version", gvk.Version,
  622. "kind", gvk.Kind)
  623. }
  624. }
  625. r.markAsDone(externalSecret, start, log, esv1.ConditionReasonResourceSynced, msgSynced)
  626. return r.getRequeueResult(externalSecret), nil
  627. }
  628. // getRequeueResult create a result with requeueAfter based on the ExternalSecret refresh interval.
  629. func (r *Reconciler) getRequeueResult(externalSecret *esv1.ExternalSecret) ctrl.Result {
  630. // default to the global requeue interval
  631. // note, this will never be used because the CRD has a default value of 1 hour
  632. refreshInterval := r.RequeueInterval
  633. if externalSecret.Spec.RefreshInterval != nil {
  634. refreshInterval = externalSecret.Spec.RefreshInterval.Duration
  635. }
  636. // if the refresh interval is <= 0, we should not requeue
  637. if refreshInterval <= 0 {
  638. return ctrl.Result{}
  639. }
  640. // if the last refresh time is not set, requeue after the refresh interval
  641. // note, this should not happen, as we only call this function on ExternalSecrets
  642. // that have been reconciled at least once
  643. if externalSecret.Status.RefreshTime.IsZero() {
  644. return ctrl.Result{RequeueAfter: refreshInterval}
  645. }
  646. timeSinceLastRefresh := time.Since(externalSecret.Status.RefreshTime.Time)
  647. // if the last refresh time is in the future, we should requeue immediately
  648. // note, this should not happen, as we always refresh an ExternalSecret
  649. // that has a last refresh time in the future
  650. if timeSinceLastRefresh < 0 {
  651. return ctrl.Result{Requeue: true}
  652. }
  653. // if there is time remaining, requeue after the remaining time
  654. if timeSinceLastRefresh < refreshInterval {
  655. return ctrl.Result{RequeueAfter: refreshInterval - timeSinceLastRefresh}
  656. }
  657. // otherwise, requeue immediately
  658. return ctrl.Result{Requeue: true}
  659. }
  660. func (r *Reconciler) markAsDone(externalSecret *esv1.ExternalSecret, start time.Time, log logr.Logger, reason, msg string) {
  661. oldReadyCondition := esv1.GetExternalSecretCondition(externalSecret.Status, esv1.ExternalSecretReady)
  662. newReadyCondition := NewExternalSecretCondition(esv1.ExternalSecretReady, v1.ConditionTrue, reason, msg)
  663. SetExternalSecretCondition(externalSecret, *newReadyCondition)
  664. externalSecret.Status.RefreshTime = metav1.NewTime(start)
  665. externalSecret.Status.SyncedResourceVersion = ctrlutil.GetResourceVersion(externalSecret.ObjectMeta)
  666. // if the status or reason has changed, log at the appropriate verbosity level
  667. if oldReadyCondition == nil || oldReadyCondition.Status != newReadyCondition.Status || oldReadyCondition.Reason != newReadyCondition.Reason {
  668. if newReadyCondition.Reason == esv1.ConditionReasonSecretDeleted {
  669. log.Info("deleted secret")
  670. } else {
  671. log.Info("reconciled secret")
  672. }
  673. } else {
  674. log.V(1).Info("reconciled secret")
  675. }
  676. }
  677. func (r *Reconciler) markAsFailed(msg string, err error, externalSecret *esv1.ExternalSecret, counter prometheus.Counter, reason string) {
  678. r.recorder.Event(externalSecret, v1.EventTypeWarning, esv1.ReasonUpdateFailed, err.Error())
  679. conditionSynced := NewExternalSecretCondition(esv1.ExternalSecretReady, v1.ConditionFalse, reason, msg)
  680. SetExternalSecretCondition(externalSecret, *conditionSynced)
  681. counter.Inc()
  682. }
  683. // applyOwnership handles ownership-related logic for target resources (Secrets and generic targets).
  684. // It detects ownership conflicts with other ExternalSecrets, sets or removes the controller reference
  685. // based on CreationPolicy, and manages the LabelOwner label.
  686. func (r *Reconciler) applyOwnership(es *esv1.ExternalSecret, target client.Object) error {
  687. // get information about the current owner of the target
  688. // - we ignore the API version as it can change over time
  689. // - we ignore the UID for consistency with the SetControllerReference function
  690. currentOwner := metav1.GetControllerOf(target)
  691. ownerIsESKind := false
  692. ownerIsCurrentES := false
  693. if currentOwner != nil {
  694. currentOwnerGK := schema.FromAPIVersionAndKind(currentOwner.APIVersion, currentOwner.Kind).GroupKind()
  695. ownerIsESKind = currentOwnerGK.String() == esv1.ExtSecretGroupKind
  696. ownerIsCurrentES = ownerIsESKind && currentOwner.Name == es.Name
  697. }
  698. // if another ExternalSecret is the owner, we should return an error
  699. // otherwise the controller will fight with itself to update the target.
  700. // note, this does not prevent other controllers from owning the target.
  701. if ownerIsESKind && !ownerIsCurrentES {
  702. return fmt.Errorf("%w: %s", ErrSecretIsOwned, currentOwner.Name)
  703. }
  704. // if the CreationPolicy is Owner, we should set ourselves as the owner of the target
  705. if es.Spec.Target.CreationPolicy == esv1.CreatePolicyOwner {
  706. if err := controllerutil.SetControllerReference(es, target, r.Scheme); err != nil {
  707. return fmt.Errorf("%w: %w", ErrSecretSetCtrlRef, err)
  708. }
  709. }
  710. // if the creation policy is not Owner, we should remove ourselves as the owner
  711. // this could happen if the creation policy was changed after the target was created
  712. if es.Spec.Target.CreationPolicy != esv1.CreatePolicyOwner && ownerIsCurrentES {
  713. if err := controllerutil.RemoveControllerReference(es, target, r.Scheme); err != nil {
  714. return fmt.Errorf("%w: %w", ErrSecretRemoveCtrlRef, err)
  715. }
  716. }
  717. // we also use a label to keep track of the owner of the target
  718. // this lets us remove targets that are no longer needed if the target name changes
  719. labels := target.GetLabels()
  720. if labels == nil {
  721. labels = make(map[string]string)
  722. }
  723. if es.Spec.Target.CreationPolicy == esv1.CreatePolicyOwner {
  724. labels[esv1.LabelOwner] = esutils.ObjectHash(fmt.Sprintf("%v/%v", es.Namespace, es.Name))
  725. } else {
  726. delete(labels, esv1.LabelOwner)
  727. }
  728. target.SetLabels(labels)
  729. return nil
  730. }
  731. func (r *Reconciler) cleanupManagedSecrets(ctx context.Context, log logr.Logger, externalSecret *esv1.ExternalSecret) error {
  732. // Only delete resources if DeletionPolicy is Delete
  733. if externalSecret.Spec.Target.DeletionPolicy != esv1.DeletionPolicyDelete {
  734. log.V(1).Info("skipping resource deletion due to DeletionPolicy", "policy", externalSecret.Spec.Target.DeletionPolicy)
  735. return nil
  736. }
  737. // if this is a generic target, use deleteGenericResource
  738. if isGenericTarget(externalSecret) {
  739. return r.deleteGenericResource(ctx, log, externalSecret)
  740. }
  741. // handle Secret deletion
  742. secretName := externalSecret.Spec.Target.Name
  743. if secretName == "" {
  744. secretName = externalSecret.Name
  745. }
  746. var secret v1.Secret
  747. err := r.Get(ctx, types.NamespacedName{Name: secretName, Namespace: externalSecret.Namespace}, &secret)
  748. if err != nil {
  749. if apierrors.IsNotFound(err) {
  750. return nil
  751. }
  752. return err
  753. }
  754. // Only delete if we own it
  755. if metav1.IsControlledBy(&secret, externalSecret) {
  756. if err := r.Delete(ctx, &secret); err != nil && !apierrors.IsNotFound(err) {
  757. return err
  758. }
  759. log.V(1).Info(logManagedSecretDeleted, "secret", secretName, "namespace", externalSecret.Namespace, "reason", "ExternalSecret deleted")
  760. }
  761. return nil
  762. }
  763. func (r *Reconciler) deleteOrphanedSecrets(ctx context.Context, log logr.Logger, externalSecret *esv1.ExternalSecret, secretName string) error {
  764. ownerLabel := esutils.ObjectHash(fmt.Sprintf("%v/%v", externalSecret.Namespace, externalSecret.Name))
  765. // we use a PartialObjectMetadataList to avoid loading the full secret objects
  766. // and because the Secrets partials are always cached due to WatchesMetadata() in SetupWithManager()
  767. secretListPartial := &metav1.PartialObjectMetadataList{}
  768. secretListPartial.SetGroupVersionKind(v1.SchemeGroupVersion.WithKind("SecretList"))
  769. listOpts := &client.ListOptions{
  770. LabelSelector: labels.SelectorFromSet(map[string]string{
  771. esv1.LabelOwner: ownerLabel,
  772. }),
  773. Namespace: externalSecret.Namespace,
  774. }
  775. if err := r.List(ctx, secretListPartial, listOpts); err != nil {
  776. return err
  777. }
  778. // delete all secrets that are not the target secret
  779. for _, secretPartial := range secretListPartial.Items {
  780. if secretPartial.GetName() != secretName {
  781. err := r.Delete(ctx, &secretPartial)
  782. if err != nil && !apierrors.IsNotFound(err) {
  783. return err
  784. }
  785. log.V(1).Info(logSecretDeletedOrphaned, "secret", secretPartial.GetName(), "namespace", externalSecret.Namespace)
  786. r.recorder.Event(externalSecret, v1.EventTypeNormal, esv1.ReasonDeleted, eventDeletedOrphaned)
  787. }
  788. }
  789. return nil
  790. }
  791. // createSecret creates a new secret with the given mutation function.
  792. func (r *Reconciler) createSecret(ctx context.Context, mutationFunc func(secret *v1.Secret) error, es *esv1.ExternalSecret, secretName string) error {
  793. fqdn := fqdnFor(es.Name)
  794. // define and mutate the new secret
  795. newSecret := &v1.Secret{
  796. ObjectMeta: metav1.ObjectMeta{
  797. Name: secretName,
  798. Namespace: es.Namespace,
  799. Labels: map[string]string{},
  800. Annotations: map[string]string{},
  801. },
  802. Data: make(map[string][]byte),
  803. }
  804. if err := mutationFunc(newSecret); err != nil {
  805. return err
  806. }
  807. // note, we set field owner even for Create
  808. if err := r.Create(ctx, newSecret, client.FieldOwner(fqdn)); err != nil {
  809. return err
  810. }
  811. // set the binding reference to the secret
  812. // https://github.com/external-secrets/external-secrets/pull/2263
  813. es.Status.Binding = v1.LocalObjectReference{Name: newSecret.Name}
  814. r.recorder.Event(es, v1.EventTypeNormal, esv1.ReasonCreated, eventCreated)
  815. return nil
  816. }
  817. func (r *Reconciler) updateSecret(ctx context.Context, log logr.Logger, existingSecret *v1.Secret, mutationFunc func(secret *v1.Secret) error, es *esv1.ExternalSecret, secretName string) error {
  818. fqdn := fqdnFor(es.Name)
  819. // fail if the secret does not exist
  820. // this should never happen because we check this before calling this function
  821. if existingSecret.UID == "" {
  822. return fmt.Errorf(errUpdateNotFound, secretName)
  823. }
  824. // set the binding reference to the secret
  825. // https://github.com/external-secrets/external-secrets/pull/2263
  826. es.Status.Binding = v1.LocalObjectReference{Name: secretName}
  827. // mutate a copy of the existing secret with the mutation function
  828. updatedSecret := existingSecret.DeepCopy()
  829. if err := mutationFunc(updatedSecret); err != nil {
  830. return fmt.Errorf(errMutate, updatedSecret.Name, err)
  831. }
  832. // if the secret does not need to be updated, return early
  833. if equality.Semantic.DeepEqual(existingSecret, updatedSecret) {
  834. return nil
  835. }
  836. // if the existing secret is immutable, we can only update the object metadata
  837. if ptr.Deref(existingSecret.Immutable, false) {
  838. // check if the metadata was changed
  839. metadataChanged := !equality.Semantic.DeepEqual(existingSecret.ObjectMeta, updatedSecret.ObjectMeta)
  840. // check if the immutable data/type was changed
  841. var dataChanged bool
  842. if metadataChanged {
  843. // update the `existingSecret` object with the metadata from `updatedSecret`
  844. // this lets us compare the objects to see if the immutable data/type was changed
  845. existingSecret.ObjectMeta = *updatedSecret.ObjectMeta.DeepCopy()
  846. dataChanged = !equality.Semantic.DeepEqual(existingSecret, updatedSecret)
  847. // because we use labels and annotations to keep track of the secret,
  848. // we need to update the metadata, regardless of if the immutable data was changed
  849. // NOTE: we are using the `existingSecret` object here, as we ONLY want to update the metadata,
  850. // and we previously copied the metadata from the `updatedSecret` object
  851. if err := r.Update(ctx, existingSecret, client.FieldOwner(fqdn)); err != nil {
  852. // if we get a conflict, we should return early to requeue immediately
  853. // note, we don't wrap this error so we can handle it in the caller
  854. if apierrors.IsConflict(err) {
  855. return err
  856. }
  857. return fmt.Errorf(errUpdate, existingSecret.Name, err)
  858. }
  859. } else {
  860. // we know there was some change in the secret (or we would have returned early)
  861. // we know the metadata was NOT changed (metadataChanged == false)
  862. // so, the only thing that could have changed is the immutable data/type fields
  863. dataChanged = true
  864. }
  865. // if the immutable data was changed, we should return an error
  866. if dataChanged {
  867. return fmt.Errorf(errUpdate, existingSecret.Name, ErrSecretImmutable)
  868. }
  869. }
  870. // update the secret
  871. if err := r.Update(ctx, updatedSecret, client.FieldOwner(fqdn)); err != nil {
  872. // if we get a conflict, we should return early to requeue immediately
  873. // note, we don't wrap this error so we can handle it in the caller
  874. if apierrors.IsConflict(err) {
  875. return err
  876. }
  877. return fmt.Errorf(errUpdate, updatedSecret.Name, err)
  878. }
  879. // only compute the key diff when debug verbosity is active (--loglevel=debug /
  880. // log.level=debug in Helm). skipping it by default avoids per-reconcile
  881. // allocation on every managed secret. we only ever log key names, never values.
  882. if log.V(1).Enabled() {
  883. added, updated, removed, emptied := diffSecretDataKeys(existingSecret.Data, updatedSecret.Data)
  884. if len(added) > 0 || len(updated) > 0 || len(removed) > 0 {
  885. log.V(1).Info(logSecretDataChanged,
  886. "secret", secretName,
  887. "namespace", es.Namespace,
  888. "added", added,
  889. "updated", updated,
  890. "removed", removed,
  891. "emptied", emptied,
  892. )
  893. }
  894. }
  895. r.recorder.Event(es, v1.EventTypeNormal, esv1.ReasonUpdated, eventUpdated)
  896. return nil
  897. }
  898. // getManagedDataKeys returns the list of data keys in a secret which are managed by a specified owner.
  899. func getManagedDataKeys(secret *v1.Secret, fieldOwner string) ([]string, error) {
  900. return getManagedFieldKeys(secret, fieldOwner, func(fields map[string]any) []string {
  901. dataFields := fields["f:data"]
  902. if dataFields == nil {
  903. return nil
  904. }
  905. df, ok := dataFields.(map[string]any)
  906. if !ok {
  907. return nil
  908. }
  909. return slices.Collect(maps.Keys(df))
  910. })
  911. }
  912. func getManagedFieldKeys(
  913. secret *v1.Secret,
  914. fieldOwner string,
  915. process func(fields map[string]any) []string,
  916. ) ([]string, error) {
  917. fqdn := fqdnFor(fieldOwner)
  918. var keys []string
  919. for _, v := range secret.ObjectMeta.ManagedFields {
  920. if v.Manager != fqdn {
  921. continue
  922. }
  923. fields := make(map[string]any)
  924. err := json.Unmarshal(v.FieldsV1.Raw, &fields)
  925. if err != nil {
  926. return nil, fmt.Errorf("error unmarshaling managed fields: %w", err)
  927. }
  928. for _, key := range process(fields) {
  929. if key == "." {
  930. continue
  931. }
  932. keys = append(keys, strings.TrimPrefix(key, "f:"))
  933. }
  934. }
  935. return keys, nil
  936. }
  937. func shouldSkipClusterSecretStore(r *Reconciler, es *esv1.ExternalSecret) bool {
  938. return !r.ClusterSecretStoreEnabled && es.Spec.SecretStoreRef.Kind == esv1.ClusterSecretStoreKind
  939. }
  940. // shouldSkipUnmanagedStore iterates over all secretStore references in the externalSecret spec,
  941. // fetches the store and evaluates the controllerClass property.
  942. // Returns true if any storeRef points to store with a non-matching controllerClass.
  943. func shouldSkipUnmanagedStore(ctx context.Context, namespace string, r *Reconciler, es *esv1.ExternalSecret) (bool, error) {
  944. var storeList []esv1.SecretStoreRef
  945. if es.Spec.SecretStoreRef.Name != "" {
  946. storeList = append(storeList, es.Spec.SecretStoreRef)
  947. }
  948. for _, ref := range es.Spec.Data {
  949. if ref.SourceRef != nil {
  950. storeList = append(storeList, ref.SourceRef.SecretStoreRef)
  951. }
  952. }
  953. for _, ref := range es.Spec.DataFrom {
  954. if ref.SourceRef != nil && ref.SourceRef.SecretStoreRef != nil {
  955. storeList = append(storeList, *ref.SourceRef.SecretStoreRef)
  956. }
  957. // verify that generator's controllerClass matches
  958. if ref.SourceRef != nil && ref.SourceRef.GeneratorRef != nil {
  959. _, obj, err := resolvers.GeneratorRef(ctx, r.Client, r.Scheme, namespace, ref.SourceRef.GeneratorRef)
  960. if err != nil {
  961. if apierrors.IsNotFound(err) {
  962. // skip non-existent generators
  963. continue
  964. }
  965. if errors.Is(err, resolvers.ErrUnableToGetGenerator) {
  966. // skip generators that we can't get (e.g. due to being invalid)
  967. continue
  968. }
  969. return false, err
  970. }
  971. skipGenerator, err := shouldSkipGenerator(r, obj)
  972. if err != nil {
  973. return false, err
  974. }
  975. if skipGenerator {
  976. return true, nil
  977. }
  978. }
  979. }
  980. for _, ref := range storeList {
  981. var store esv1.GenericStore
  982. switch ref.Kind {
  983. case esv1.SecretStoreKind, "":
  984. store = &esv1.SecretStore{}
  985. case esv1.ClusterSecretStoreKind:
  986. store = &esv1.ClusterSecretStore{}
  987. namespace = ""
  988. default:
  989. return false, fmt.Errorf("unsupported secret store kind: %s", ref.Kind)
  990. }
  991. err := r.Get(ctx, types.NamespacedName{
  992. Name: ref.Name,
  993. Namespace: namespace,
  994. }, store)
  995. if err != nil {
  996. if apierrors.IsNotFound(err) {
  997. // skip non-existent stores
  998. continue
  999. }
  1000. return false, err
  1001. }
  1002. class := store.GetSpec().Controller
  1003. if class != "" && class != r.ControllerClass {
  1004. return true, nil
  1005. }
  1006. }
  1007. return false, nil
  1008. }
  1009. func shouldRefresh(es *esv1.ExternalSecret) bool {
  1010. switch es.Spec.RefreshPolicy {
  1011. case esv1.RefreshPolicyCreatedOnce:
  1012. if es.Status.SyncedResourceVersion == "" || es.Status.RefreshTime.IsZero() {
  1013. return true
  1014. }
  1015. return false
  1016. case esv1.RefreshPolicyOnChange:
  1017. if es.Status.SyncedResourceVersion == "" || es.Status.RefreshTime.IsZero() {
  1018. return true
  1019. }
  1020. return es.Status.SyncedResourceVersion != ctrlutil.GetResourceVersion(es.ObjectMeta)
  1021. case esv1.RefreshPolicyPeriodic:
  1022. return shouldRefreshPeriodic(es)
  1023. default:
  1024. return shouldRefreshPeriodic(es)
  1025. }
  1026. }
  1027. func shouldRefreshPeriodic(es *esv1.ExternalSecret) bool {
  1028. // if the refresh interval is 0, and we have synced previously, we should not refresh
  1029. if es.Spec.RefreshInterval.Duration <= 0 && es.Status.SyncedResourceVersion != "" {
  1030. return false
  1031. }
  1032. // if the ExternalSecret has been updated, we should refresh
  1033. if es.Status.SyncedResourceVersion != ctrlutil.GetResourceVersion(es.ObjectMeta) {
  1034. return true
  1035. }
  1036. // if the last refresh time is zero, we should refresh
  1037. if es.Status.RefreshTime.IsZero() {
  1038. return true
  1039. }
  1040. // if the last refresh time is in the future, we should refresh
  1041. if es.Status.RefreshTime.Time.After(time.Now()) {
  1042. return true
  1043. }
  1044. // if the last refresh time + refresh interval is before now, we should refresh
  1045. return es.Status.RefreshTime.Add(es.Spec.RefreshInterval.Duration).Before(time.Now())
  1046. }
  1047. // isSecretValid checks if the secret exists, and it's data is consistent with the calculated hash.
  1048. func isSecretValid(existingSecret *v1.Secret, es *esv1.ExternalSecret) bool {
  1049. // Secret is always valid with `CreationPolicy=Orphan`
  1050. if es.Spec.Target.CreationPolicy == esv1.CreatePolicyOrphan {
  1051. return true
  1052. }
  1053. if existingSecret.UID == "" {
  1054. return false
  1055. }
  1056. // if the managed label is missing or incorrect, then it's invalid
  1057. if existingSecret.Labels[esv1.LabelManaged] != esv1.LabelManagedValue {
  1058. return false
  1059. }
  1060. // if the data-hash annotation is missing or incorrect, then it's invalid
  1061. // this is how we know if the data has chanced since we last updated the secret
  1062. if existingSecret.Annotations[esv1.AnnotationDataHash] != esutils.ObjectHash(existingSecret.Data) {
  1063. return false
  1064. }
  1065. return true
  1066. }
  1067. func isGenericTargetValid(existingTarget *unstructured.Unstructured, es *esv1.ExternalSecret) (bool, error) {
  1068. if es.Spec.Target.CreationPolicy == esv1.CreatePolicyOrphan {
  1069. return true, nil
  1070. }
  1071. if existingTarget == nil || existingTarget.GetUID() == "" {
  1072. return false, nil
  1073. }
  1074. if existingTarget.GetLabels()[esv1.LabelManaged] != esv1.LabelManagedValue {
  1075. return false, nil
  1076. }
  1077. hash, err := genericTargetContentHash(existingTarget)
  1078. if err != nil {
  1079. return false, fmt.Errorf("failed to hash target: %w", err)
  1080. }
  1081. if existingTarget.GetAnnotations()[esv1.AnnotationDataHash] != hash {
  1082. return false, nil
  1083. }
  1084. return true, nil
  1085. }
  1086. // genericTargetContentHash computes a hash over the hashable content of an unstructured object.
  1087. // It uses the "spec" field if present, otherwise falls back to "data".
  1088. func genericTargetContentHash(obj *unstructured.Unstructured) (string, error) {
  1089. content := obj.Object
  1090. switch {
  1091. case content["spec"] != nil:
  1092. return esutils.ObjectHash(content["spec"]), nil
  1093. case content["data"] != nil:
  1094. return esutils.ObjectHash(content["data"]), nil
  1095. default:
  1096. return "", errors.New("generic target content does not have a spec or data field for content hashing")
  1097. }
  1098. }
  1099. // SetupWithManager returns a new controller builder that will be started by the provided Manager.
  1100. func (r *Reconciler) SetupWithManager(ctx context.Context, mgr ctrl.Manager, opts controller.Options) error {
  1101. r.recorder = mgr.GetEventRecorderFor("external-secrets")
  1102. if r.APIReader == nil {
  1103. r.APIReader = mgr.GetAPIReader()
  1104. }
  1105. // Initialize informer manager only if generic targets are allowed
  1106. if r.AllowGenericTargets && r.informerManager == nil {
  1107. r.informerManager = NewInformerManager(ctx, mgr.GetCache(), r.Client, r.Log.WithName("informer-manager"))
  1108. }
  1109. // index ExternalSecrets based on the target secret name,
  1110. // this lets us quickly find all ExternalSecrets which target a specific Secret
  1111. if err := mgr.GetFieldIndexer().IndexField(ctx, &esv1.ExternalSecret{}, indexESTargetSecretNameField, func(obj client.Object) []string {
  1112. es := obj.(*esv1.ExternalSecret)
  1113. // Don't index generic targets here (they use indexESTargetResourceField)
  1114. if isGenericTarget(es) {
  1115. return nil
  1116. }
  1117. // if the target name is set, use that as the index
  1118. if es.Spec.Target.Name != "" {
  1119. return []string{es.Spec.Target.Name}
  1120. }
  1121. // otherwise, use the ExternalSecret name
  1122. return []string{es.Name}
  1123. }); err != nil {
  1124. return err
  1125. }
  1126. // index ExternalSecrets based on the target resource (GVK + name)
  1127. // this lets us quickly find all ExternalSecrets which target a specific generic resource
  1128. if err := mgr.GetFieldIndexer().IndexField(ctx, &esv1.ExternalSecret{}, indexESTargetResourceField, func(obj client.Object) []string {
  1129. es := obj.(*esv1.ExternalSecret)
  1130. if !r.AllowGenericTargets || !isGenericTarget(es) {
  1131. return nil
  1132. }
  1133. gvk := getTargetGVK(es)
  1134. targetName := getTargetName(es)
  1135. // Index format: "group/version/kind/name"
  1136. return []string{fmt.Sprintf("%s/%s/%s/%s", gvk.Group, gvk.Version, gvk.Kind, targetName)}
  1137. }); err != nil {
  1138. return err
  1139. }
  1140. // predicate function to ignore secret events unless they have the "managed" label
  1141. secretHasESLabel := predicate.NewPredicateFuncs(func(object client.Object) bool {
  1142. value, hasLabel := object.GetLabels()[esv1.LabelManaged]
  1143. return hasLabel && value == esv1.LabelManagedValue
  1144. })
  1145. // filter ExternalSecret updates to avoid requeueing on status-only changes.
  1146. externalSecretPredicate := predicate.Funcs{
  1147. UpdateFunc: func(e event.UpdateEvent) bool {
  1148. return shouldEnqueueExternalSecretUpdate(e.ObjectOld, e.ObjectNew)
  1149. },
  1150. }
  1151. // Build the controller
  1152. builder := ctrl.NewControllerManagedBy(mgr).
  1153. WithOptions(opts).
  1154. For(&esv1.ExternalSecret{}, builder.WithPredicates(externalSecretPredicate)).
  1155. // we cant use Owns(), as we don't set ownerReferences when the creationPolicy is not Owner.
  1156. // we use WatchesMetadata() to reduce memory usage, as otherwise we have to process full secret objects.
  1157. WatchesMetadata(
  1158. &v1.Secret{},
  1159. handler.EnqueueRequestsFromMapFunc(r.findObjectsForSecret),
  1160. builder.WithPredicates(predicate.ResourceVersionChangedPredicate{}, secretHasESLabel),
  1161. )
  1162. // Watch generic targets dynamically via the informer manager
  1163. // Only add this watch source if the feature is enabled
  1164. if r.AllowGenericTargets {
  1165. builder = builder.WatchesRawSource(r.informerManager.Source())
  1166. }
  1167. return builder.Complete(r)
  1168. }
  1169. // shouldEnqueueExternalSecretUpdate returns true for spec/metadata updates that can affect reconciliation behavior,
  1170. // while ignoring status-only updates.
  1171. func shouldEnqueueExternalSecretUpdate(oldObj, newObj client.Object) bool {
  1172. oldES, oldOK := oldObj.(*esv1.ExternalSecret)
  1173. newES, newOK := newObj.(*esv1.ExternalSecret)
  1174. if !oldOK || !newOK {
  1175. return true
  1176. }
  1177. if oldES.GetGeneration() != newES.GetGeneration() {
  1178. return true
  1179. }
  1180. if !equality.Semantic.DeepEqual(oldES.GetLabels(), newES.GetLabels()) {
  1181. return true
  1182. }
  1183. if !equality.Semantic.DeepEqual(oldES.GetAnnotations(), newES.GetAnnotations()) {
  1184. return true
  1185. }
  1186. if !equality.Semantic.DeepEqual(oldES.GetFinalizers(), newES.GetFinalizers()) {
  1187. return true
  1188. }
  1189. oldDeletion := oldES.GetDeletionTimestamp()
  1190. newDeletion := newES.GetDeletionTimestamp()
  1191. if oldDeletion == nil && newDeletion == nil {
  1192. return false
  1193. }
  1194. if oldDeletion == nil || newDeletion == nil {
  1195. return true
  1196. }
  1197. return !oldDeletion.Equal(newDeletion)
  1198. }
  1199. // resolveSecretCacheMismatch optionally uses a direct API read when the partial
  1200. // and full secret caches disagree. It returns the secret to continue with,
  1201. // whether the caches should still be treated as out of sync, and any read error.
  1202. func (r *Reconciler) resolveSecretCacheMismatch(ctx context.Context, key client.ObjectKey, secretPartial *metav1.PartialObjectMetadata, existingSecret *v1.Secret) (*v1.Secret, bool, error) {
  1203. if secretPartial.UID == existingSecret.UID && secretPartial.ResourceVersion == existingSecret.ResourceVersion {
  1204. return existingSecret, false, nil
  1205. }
  1206. if !r.EnableSecretAPIReadOnCacheMismatch {
  1207. return nil, true, nil
  1208. }
  1209. authoritativeSecret := &v1.Secret{}
  1210. secretReader := r.APIReader
  1211. if secretReader == nil {
  1212. secretReader = r.SecretClient
  1213. }
  1214. err := secretReader.Get(ctx, key, authoritativeSecret)
  1215. if err != nil && !apierrors.IsNotFound(err) {
  1216. return nil, false, err
  1217. }
  1218. if secretPartial.UID != authoritativeSecret.UID || secretPartial.ResourceVersion != authoritativeSecret.ResourceVersion {
  1219. return nil, true, nil
  1220. }
  1221. return authoritativeSecret, false, nil
  1222. }
  1223. func (r *Reconciler) findObjectsForSecret(ctx context.Context, secret client.Object) []reconcile.Request {
  1224. externalSecretsList := &esv1.ExternalSecretList{}
  1225. listOps := &client.ListOptions{
  1226. FieldSelector: fields.OneTermEqualSelector(indexESTargetSecretNameField, secret.GetName()),
  1227. Namespace: secret.GetNamespace(),
  1228. }
  1229. err := r.List(ctx, externalSecretsList, listOps)
  1230. if err != nil {
  1231. return []reconcile.Request{}
  1232. }
  1233. requests := make([]reconcile.Request, len(externalSecretsList.Items))
  1234. for i := range externalSecretsList.Items {
  1235. requests[i] = reconcile.Request{
  1236. NamespacedName: types.NamespacedName{
  1237. Name: externalSecretsList.Items[i].GetName(),
  1238. Namespace: externalSecretsList.Items[i].GetNamespace(),
  1239. },
  1240. }
  1241. }
  1242. return requests
  1243. }