externalsecret_controller.go 54 KB

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