externalsecret_controller.go 49 KB

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