externalsecret_controller.go 55 KB

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