externalsecret_controller.go 54 KB

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