externalsecret_controller.go 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012
  1. /*
  2. Licensed under the Apache License, Version 2.0 (the "License");
  3. you may not use this file except in compliance with the License.
  4. You may obtain a copy of the License at
  5. http://www.apache.org/licenses/LICENSE-2.0
  6. Unless required by applicable law or agreed to in writing, software
  7. distributed under the License is distributed on an "AS IS" BASIS,
  8. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. See the License for the specific language governing permissions and
  10. limitations under the License.
  11. */
  12. package externalsecret
  13. import (
  14. "context"
  15. "encoding/json"
  16. "errors"
  17. "fmt"
  18. "maps"
  19. "slices"
  20. "strings"
  21. "time"
  22. "github.com/go-logr/logr"
  23. "github.com/prometheus/client_golang/prometheus"
  24. v1 "k8s.io/api/core/v1"
  25. "k8s.io/apimachinery/pkg/api/equality"
  26. apierrors "k8s.io/apimachinery/pkg/api/errors"
  27. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  28. "k8s.io/apimachinery/pkg/fields"
  29. "k8s.io/apimachinery/pkg/labels"
  30. "k8s.io/apimachinery/pkg/runtime"
  31. "k8s.io/apimachinery/pkg/runtime/schema"
  32. "k8s.io/apimachinery/pkg/selection"
  33. "k8s.io/apimachinery/pkg/types"
  34. "k8s.io/client-go/rest"
  35. "k8s.io/client-go/tools/record"
  36. "k8s.io/utils/ptr"
  37. ctrl "sigs.k8s.io/controller-runtime"
  38. "sigs.k8s.io/controller-runtime/pkg/builder"
  39. "sigs.k8s.io/controller-runtime/pkg/cache"
  40. "sigs.k8s.io/controller-runtime/pkg/client"
  41. "sigs.k8s.io/controller-runtime/pkg/controller"
  42. "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
  43. "sigs.k8s.io/controller-runtime/pkg/handler"
  44. "sigs.k8s.io/controller-runtime/pkg/predicate"
  45. "sigs.k8s.io/controller-runtime/pkg/reconcile"
  46. esv1beta1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1beta1"
  47. // Metrics.
  48. "github.com/external-secrets/external-secrets/pkg/controllers/externalsecret/esmetrics"
  49. ctrlmetrics "github.com/external-secrets/external-secrets/pkg/controllers/metrics"
  50. "github.com/external-secrets/external-secrets/pkg/utils"
  51. "github.com/external-secrets/external-secrets/pkg/utils/resolvers"
  52. // Loading registered generators.
  53. _ "github.com/external-secrets/external-secrets/pkg/generator/register"
  54. // Loading registered providers.
  55. _ "github.com/external-secrets/external-secrets/pkg/provider/register"
  56. )
  57. const (
  58. fieldOwnerTemplate = "externalsecrets.external-secrets.io/%v"
  59. // condition messages for "SecretSynced" reason.
  60. msgSynced = "secret synced"
  61. msgSyncedRetain = "secret retained due to DeletionPolicy=Retain"
  62. // condition messages for "SecretDeleted" reason.
  63. msgDeleted = "secret deleted due to DeletionPolicy=Delete"
  64. // condition messages for "SecretMissing" reason.
  65. msgMissing = "secret will not be created due to CreationPolicy=Merge"
  66. // condition messages for "SecretSyncedError" reason.
  67. msgErrorGetSecretData = "could not get secret data from provider"
  68. msgErrorDeleteSecret = "could not delete secret"
  69. msgErrorDeleteOrphaned = "could not delete orphaned secrets"
  70. msgErrorUpdateSecret = "could not update secret"
  71. msgErrorUpdateImmutable = "could not update secret, target is immutable"
  72. msgErrorBecomeOwner = "failed to take ownership of target secret"
  73. msgErrorIsOwned = "target is owned by another ExternalSecret"
  74. // log messages.
  75. logErrorGetES = "unable to get ExternalSecret"
  76. logErrorUpdateESStatus = "unable to update ExternalSecret status"
  77. logErrorGetSecret = "unable to get Secret"
  78. logErrorPatchSecret = "unable to patch Secret"
  79. logErrorSecretCacheNotSynced = "controller caches for Secret are not in sync"
  80. logErrorUnmanagedStore = "unable to determine if store is managed"
  81. // error formats.
  82. errConvert = "could not apply conversion strategy to keys: %v"
  83. errDecode = "could not apply decoding strategy to %v[%d]: %v"
  84. errGenerate = "could not generate [%d]: %w"
  85. errRewrite = "could not rewrite spec.dataFrom[%d]: %v"
  86. errInvalidKeys = "secret keys from spec.dataFrom.%v[%d] can only have alphanumeric, '-', '_' or '.' characters. Convert them using rewrite (https://external-secrets.io/latest/guides/datafrom-rewrite/)"
  87. errFetchTplFrom = "error fetching templateFrom data: %w"
  88. errApplyTemplate = "could not apply template: %w"
  89. errExecTpl = "could not execute template: %w"
  90. errMutate = "unable to mutate secret %s: %w"
  91. errUpdate = "unable to update secret %s: %w"
  92. errUpdateNotFound = "unable to update secret %s: not found"
  93. errDeleteCreatePolicy = "unable to delete secret %s: creationPolicy=%s is not Owner"
  94. errSecretCachesNotSynced = "controller caches for secret %s are not in sync"
  95. )
  96. // these errors are explicitly defined so we can detect them with `errors.Is()`.
  97. var (
  98. ErrSecretImmutable = fmt.Errorf("secret is immutable")
  99. ErrSecretIsOwned = fmt.Errorf("secret is owned by another ExternalSecret")
  100. ErrSecretSetCtrlRef = fmt.Errorf("could not set controller reference on secret")
  101. ErrSecretRemoveCtrlRef = fmt.Errorf("could not remove controller reference on secret")
  102. )
  103. const indexESTargetSecretNameField = ".metadata.targetSecretName"
  104. // Reconciler reconciles a ExternalSecret object.
  105. type Reconciler struct {
  106. client.Client
  107. SecretClient client.Client
  108. Log logr.Logger
  109. Scheme *runtime.Scheme
  110. RestConfig *rest.Config
  111. ControllerClass string
  112. RequeueInterval time.Duration
  113. ClusterSecretStoreEnabled bool
  114. EnableFloodGate bool
  115. recorder record.EventRecorder
  116. }
  117. // Reconcile implements the main reconciliation loop
  118. // for watched objects (ExternalSecret, ClusterSecretStore and SecretStore),
  119. // and updates/creates a Kubernetes secret based on them.
  120. func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (result ctrl.Result, err error) {
  121. log := r.Log.WithValues("ExternalSecret", req.NamespacedName)
  122. resourceLabels := ctrlmetrics.RefineNonConditionMetricLabels(map[string]string{"name": req.Name, "namespace": req.Namespace})
  123. start := time.Now()
  124. syncCallsError := esmetrics.GetCounterVec(esmetrics.SyncCallsErrorKey)
  125. // use closures to dynamically update resourceLabels
  126. defer func() {
  127. esmetrics.GetGaugeVec(esmetrics.ExternalSecretReconcileDurationKey).With(resourceLabels).Set(float64(time.Since(start)))
  128. esmetrics.GetCounterVec(esmetrics.SyncCallsKey).With(resourceLabels).Inc()
  129. }()
  130. externalSecret := &esv1beta1.ExternalSecret{}
  131. err = r.Get(ctx, req.NamespacedName, externalSecret)
  132. if err != nil {
  133. if apierrors.IsNotFound(err) {
  134. // NOTE: this does not actually set the condition on the ExternalSecret, because it does not exist
  135. // this is a hack to disable metrics for deleted ExternalSecrets, see:
  136. // https://github.com/external-secrets/external-secrets/pull/612
  137. conditionSynced := NewExternalSecretCondition(esv1beta1.ExternalSecretDeleted, v1.ConditionFalse, esv1beta1.ConditionReasonSecretDeleted, "Secret was deleted")
  138. SetExternalSecretCondition(&esv1beta1.ExternalSecret{
  139. ObjectMeta: metav1.ObjectMeta{
  140. Name: req.Name,
  141. Namespace: req.Namespace,
  142. },
  143. }, *conditionSynced)
  144. return ctrl.Result{}, nil
  145. }
  146. log.Error(err, logErrorGetES)
  147. syncCallsError.With(resourceLabels).Inc()
  148. return ctrl.Result{}, err
  149. }
  150. // skip reconciliation if deletion timestamp is set on external secret
  151. if !externalSecret.GetDeletionTimestamp().IsZero() {
  152. log.V(1).Info("skipping ExternalSecret, it is marked for deletion")
  153. return ctrl.Result{}, nil
  154. }
  155. // if extended metrics is enabled, refine the time series vector
  156. resourceLabels = ctrlmetrics.RefineLabels(resourceLabels, externalSecret.Labels)
  157. // skip this ExternalSecret if it uses a ClusterSecretStore and the feature is disabled
  158. if shouldSkipClusterSecretStore(r, externalSecret) {
  159. log.V(1).Info("skipping ExternalSecret, ClusterSecretStore feature is disabled")
  160. return ctrl.Result{}, nil
  161. }
  162. // skip this ExternalSecret if it uses any SecretStore not managed by this controller
  163. skip, err := shouldSkipUnmanagedStore(ctx, req.Namespace, r, externalSecret)
  164. if err != nil {
  165. log.Error(err, logErrorUnmanagedStore)
  166. syncCallsError.With(resourceLabels).Inc()
  167. return ctrl.Result{}, err
  168. }
  169. if skip {
  170. log.V(1).Info("skipping ExternalSecret, uses unmanaged SecretStore")
  171. return ctrl.Result{}, nil
  172. }
  173. // the target secret name defaults to the ExternalSecret name, if not explicitly set
  174. secretName := externalSecret.Spec.Target.Name
  175. if secretName == "" {
  176. secretName = externalSecret.Name
  177. }
  178. // fetch the existing secret (from the partial cache)
  179. // - please note that the ~partial cache~ is different from the ~full cache~
  180. // so there can be race conditions between the two caches
  181. // - the WatchesMetadata(v1.Secret{}) in SetupWithManager() is using the partial cache
  182. // so we might receive a reconcile request before the full cache is updated
  183. // - furthermore, when `--enable-managed-secrets-caching` is true, the full cache
  184. // will ONLY include secrets with the "managed" label, so we cant use the full cache
  185. // to reliably determine if a secret exists or not
  186. secretPartial := &metav1.PartialObjectMetadata{}
  187. secretPartial.SetGroupVersionKind(v1.SchemeGroupVersion.WithKind("Secret"))
  188. err = r.Get(ctx, client.ObjectKey{Name: secretName, Namespace: externalSecret.Namespace}, secretPartial)
  189. if err != nil && !apierrors.IsNotFound(err) {
  190. log.Error(err, logErrorGetSecret, "secretName", secretName, "secretNamespace", externalSecret.Namespace)
  191. syncCallsError.With(resourceLabels).Inc()
  192. return ctrl.Result{}, err
  193. }
  194. // if the secret exists but does not have the "managed" label, add the label
  195. // using a PATCH so it is visible in the cache, then requeue immediately
  196. if secretPartial.UID != "" && secretPartial.Labels[esv1beta1.LabelManaged] != esv1beta1.LabelManagedValue {
  197. fqdn := fmt.Sprintf(fieldOwnerTemplate, externalSecret.Name)
  198. patch := client.MergeFrom(secretPartial.DeepCopy())
  199. if secretPartial.Labels == nil {
  200. secretPartial.Labels = make(map[string]string)
  201. }
  202. secretPartial.Labels[esv1beta1.LabelManaged] = esv1beta1.LabelManagedValue
  203. err = r.Patch(ctx, secretPartial, patch, client.FieldOwner(fqdn))
  204. if err != nil {
  205. log.Error(err, logErrorPatchSecret, "secretName", secretName, "secretNamespace", externalSecret.Namespace)
  206. syncCallsError.With(resourceLabels).Inc()
  207. return ctrl.Result{}, err
  208. }
  209. return ctrl.Result{Requeue: true}, nil
  210. }
  211. // fetch existing secret (from the full cache)
  212. // NOTE: we are using the `r.SecretClient` which we only use for managed secrets.
  213. // when `enableManagedSecretsCache` is true, this is a cached client that only sees our managed secrets,
  214. // otherwise it will be the normal controller-runtime client which may be cached or make direct API calls,
  215. // depending on if `enabledSecretCache` is true or false.
  216. existingSecret := &v1.Secret{}
  217. err = r.SecretClient.Get(ctx, client.ObjectKey{Name: secretName, Namespace: externalSecret.Namespace}, existingSecret)
  218. if err != nil && !apierrors.IsNotFound(err) {
  219. log.Error(err, logErrorGetSecret, "secretName", secretName, "secretNamespace", externalSecret.Namespace)
  220. syncCallsError.With(resourceLabels).Inc()
  221. return ctrl.Result{}, err
  222. }
  223. // ensure the full cache is up-to-date
  224. // NOTE: this prevents race conditions between the partial and full cache.
  225. // we return an error so we get an exponential backoff if we end up looping,
  226. // for example, during high cluster load and frequent updates to the target secret by other controllers.
  227. if secretPartial.UID != existingSecret.UID || secretPartial.ResourceVersion != existingSecret.ResourceVersion {
  228. err = fmt.Errorf(errSecretCachesNotSynced, secretName)
  229. log.Error(err, logErrorSecretCacheNotSynced, "secretName", secretName, "secretNamespace", externalSecret.Namespace)
  230. syncCallsError.With(resourceLabels).Inc()
  231. return ctrl.Result{}, err
  232. }
  233. // refresh will be skipped if ALL the following conditions are met:
  234. // 1. refresh interval is not 0
  235. // 2. resource generation of the ExternalSecret has not changed
  236. // 3. the last refresh time of the ExternalSecret is within the refresh interval
  237. // 4. the target secret is valid:
  238. // - it exists
  239. // - it has the correct "managed" label
  240. // - it has the correct "data-hash" annotation
  241. if !shouldRefresh(externalSecret) && isSecretValid(existingSecret) {
  242. log.V(1).Info("skipping refresh")
  243. return r.getRequeueResult(externalSecret), nil
  244. }
  245. // update status of the ExternalSecret when this function returns, if needed.
  246. // NOTE: we use the ability of deferred functions to update named return values `result` and `err`
  247. // NOTE: we dereference the DeepCopy of the status field because status fields are NOT pointers,
  248. // so otherwise the `equality.Semantic.DeepEqual` will always return false.
  249. currentStatus := *externalSecret.Status.DeepCopy()
  250. defer func() {
  251. // if the status has not changed, we don't need to update it
  252. if equality.Semantic.DeepEqual(currentStatus, externalSecret.Status) {
  253. return
  254. }
  255. // update the status of the ExternalSecret, storing any error in a new variable
  256. // if there was no new error, we don't need to change the `result` or `err` values
  257. updateErr := r.Status().Update(ctx, externalSecret)
  258. if updateErr == nil {
  259. return
  260. }
  261. // if we got an update conflict, we should requeue immediately
  262. if apierrors.IsConflict(updateErr) {
  263. log.V(1).Info("conflict while updating status, will requeue")
  264. // we only explicitly request a requeue if the main function did not return an `err`.
  265. // otherwise, we get an annoying log saying that results are ignored when there is an error,
  266. // as errors are always retried.
  267. if err == nil {
  268. result = ctrl.Result{Requeue: true}
  269. }
  270. return
  271. }
  272. // for other errors, log and update the `err` variable if there is no error already
  273. // so the reconciler will requeue the request
  274. log.Error(updateErr, logErrorUpdateESStatus)
  275. if err == nil {
  276. err = updateErr
  277. }
  278. }()
  279. // retrieve the provider secret data.
  280. dataMap, err := r.getProviderSecretData(ctx, externalSecret)
  281. if err != nil {
  282. r.markAsFailed(msgErrorGetSecretData, err, externalSecret, syncCallsError.With(resourceLabels))
  283. return ctrl.Result{}, err
  284. }
  285. // if no data was found we can delete the secret if needed.
  286. if len(dataMap) == 0 {
  287. switch externalSecret.Spec.Target.DeletionPolicy {
  288. // delete secret and return early.
  289. case esv1beta1.DeletionPolicyDelete:
  290. // safeguard that we only can delete secrets we own.
  291. // this is also implemented in the es validation webhook.
  292. // NOTE: this error cant be fixed by retrying so we don't return an error (which would requeue immediately)
  293. creationPolicy := externalSecret.Spec.Target.CreationPolicy
  294. if creationPolicy != esv1beta1.CreatePolicyOwner {
  295. err := fmt.Errorf(errDeleteCreatePolicy, secretName, creationPolicy)
  296. r.markAsFailed(msgErrorDeleteSecret, err, externalSecret, syncCallsError.With(resourceLabels))
  297. return ctrl.Result{}, nil
  298. }
  299. // delete the secret, if it exists
  300. if existingSecret.UID != "" {
  301. if err := r.Delete(ctx, existingSecret); err != nil && !apierrors.IsNotFound(err) {
  302. r.markAsFailed(msgErrorDeleteSecret, err, externalSecret, syncCallsError.With(resourceLabels))
  303. return ctrl.Result{}, err
  304. }
  305. }
  306. r.markAsDone(externalSecret, start, log, esv1beta1.ConditionReasonSecretDeleted, msgDeleted)
  307. return r.getRequeueResult(externalSecret), nil
  308. // In case provider secrets don't exist the kubernetes secret will be kept as-is.
  309. case esv1beta1.DeletionPolicyRetain:
  310. r.markAsDone(externalSecret, start, log, esv1beta1.ConditionReasonSecretSynced, msgSyncedRetain)
  311. return r.getRequeueResult(externalSecret), nil
  312. // noop, handled below
  313. case esv1beta1.DeletionPolicyMerge:
  314. }
  315. }
  316. // mutationFunc is a function which can be applied to a secret to make it match the desired state.
  317. mutationFunc := func(secret *v1.Secret) error {
  318. // get information about the current owner of the secret
  319. // - we ignore the API version as it can change over time
  320. // - we ignore the UID for consistency with the SetControllerReference function
  321. currentOwner := metav1.GetControllerOf(secret)
  322. ownerIsESKind := false
  323. ownerIsCurrentES := false
  324. if currentOwner != nil {
  325. currentOwnerGK := schema.FromAPIVersionAndKind(currentOwner.APIVersion, currentOwner.Kind).GroupKind()
  326. ownerIsESKind = currentOwnerGK.String() == esv1beta1.ExtSecretGroupKind
  327. ownerIsCurrentES = ownerIsESKind && currentOwner.Name == externalSecret.Name
  328. }
  329. // if another ExternalSecret is the owner, we should return an error
  330. // otherwise the controller will fight with itself to update the secret.
  331. // note, this does not prevent other controllers from owning the secret.
  332. if ownerIsESKind && !ownerIsCurrentES {
  333. return fmt.Errorf("%w: %s", ErrSecretIsOwned, currentOwner.Name)
  334. }
  335. // if the CreationPolicy is Owner, we should set ourselves as the owner of the secret
  336. if externalSecret.Spec.Target.CreationPolicy == esv1beta1.CreatePolicyOwner {
  337. err = controllerutil.SetControllerReference(externalSecret, secret, r.Scheme)
  338. if err != nil {
  339. return fmt.Errorf("%w: %w", ErrSecretSetCtrlRef, err)
  340. }
  341. }
  342. // if the creation policy is not Owner, we should remove ourselves as the owner
  343. // this could happen if the creation policy was changed after the secret was created
  344. if externalSecret.Spec.Target.CreationPolicy != esv1beta1.CreatePolicyOwner && ownerIsCurrentES {
  345. err = controllerutil.RemoveControllerReference(externalSecret, secret, r.Scheme)
  346. if err != nil {
  347. return fmt.Errorf("%w: %w", ErrSecretRemoveCtrlRef, err)
  348. }
  349. }
  350. // initialize maps within the secret so it's safe to set values
  351. if secret.Annotations == nil {
  352. secret.Annotations = make(map[string]string)
  353. }
  354. if secret.Labels == nil {
  355. secret.Labels = make(map[string]string)
  356. }
  357. if secret.Data == nil {
  358. secret.Data = make(map[string][]byte)
  359. }
  360. // get the list of keys that are managed by this ExternalSecret
  361. keys, err := getManagedDataKeys(secret, externalSecret.Name)
  362. if err != nil {
  363. return err
  364. }
  365. // remove any data keys that are managed by this ExternalSecret, so we can re-add them
  366. // this ensures keys added by templates are not left behind when they are removed from the template
  367. for _, key := range keys {
  368. delete(secret.Data, key)
  369. }
  370. // WARNING: this will remove any labels or annotations managed by this ExternalSecret
  371. // so any updates to labels and annotations should be done AFTER this point
  372. err = r.applyTemplate(ctx, externalSecret, secret, dataMap)
  373. if err != nil {
  374. return fmt.Errorf(errApplyTemplate, err)
  375. }
  376. // set the immutable flag on the secret if requested by the ExternalSecret
  377. if externalSecret.Spec.Target.Immutable {
  378. secret.Immutable = ptr.To(true)
  379. }
  380. // we also use a label to keep track of the owner of the secret
  381. // this lets us remove secrets that are no longer needed if the target secret name changes
  382. if externalSecret.Spec.Target.CreationPolicy == esv1beta1.CreatePolicyOwner {
  383. lblValue := utils.ObjectHash(fmt.Sprintf("%v/%v", externalSecret.Namespace, externalSecret.Name))
  384. secret.Labels[esv1beta1.LabelOwner] = lblValue
  385. } else {
  386. // the label should not be set if the creation policy is not Owner
  387. delete(secret.Labels, esv1beta1.LabelOwner)
  388. }
  389. secret.Labels[esv1beta1.LabelManaged] = esv1beta1.LabelManagedValue
  390. secret.Annotations[esv1beta1.AnnotationDataHash] = utils.ObjectHash(secret.Data)
  391. return nil
  392. }
  393. switch externalSecret.Spec.Target.CreationPolicy { //nolint:exhaustive
  394. case esv1beta1.CreatePolicyMerge:
  395. // update the secret, if it exists
  396. if existingSecret.UID != "" {
  397. err = r.updateSecret(ctx, existingSecret, mutationFunc, externalSecret, secretName)
  398. } else {
  399. // if the secret does not exist, we wait until the next refresh interval
  400. // rather than returning an error which would requeue immediately
  401. r.markAsDone(externalSecret, start, log, esv1beta1.ConditionReasonSecretMissing, msgMissing)
  402. return r.getRequeueResult(externalSecret), nil
  403. }
  404. case esv1beta1.CreatePolicyNone:
  405. log.V(1).Info("secret creation skipped due to creationPolicy=None")
  406. err = nil
  407. default:
  408. // create the secret, if it does not exist
  409. if existingSecret.UID == "" {
  410. err = r.createSecret(ctx, mutationFunc, externalSecret, secretName)
  411. // we may have orphaned secrets to clean up,
  412. // for example, if the target secret name was changed
  413. if err == nil {
  414. delErr := deleteOrphanedSecrets(ctx, r.Client, externalSecret, secretName)
  415. if delErr != nil {
  416. r.markAsFailed(msgErrorDeleteOrphaned, delErr, externalSecret, syncCallsError.With(resourceLabels))
  417. return ctrl.Result{}, delErr
  418. }
  419. }
  420. } else {
  421. // update the secret, if it exists
  422. err = r.updateSecret(ctx, existingSecret, mutationFunc, externalSecret, secretName)
  423. }
  424. }
  425. if err != nil {
  426. // if we got an update conflict, we should requeue immediately
  427. if apierrors.IsConflict(err) {
  428. log.V(1).Info("conflict while updating secret, will requeue")
  429. return ctrl.Result{Requeue: true}, nil
  430. }
  431. // detect errors indicating that we failed to set ourselves as the owner of the secret
  432. // NOTE: this error cant be fixed by retrying so we don't return an error (which would requeue immediately)
  433. if errors.Is(err, ErrSecretSetCtrlRef) {
  434. r.markAsFailed(msgErrorBecomeOwner, err, externalSecret, syncCallsError.With(resourceLabels))
  435. return ctrl.Result{}, nil
  436. }
  437. // detect errors indicating that the secret has another ExternalSecret as owner
  438. // NOTE: this error cant be fixed by retrying so we don't return an error (which would requeue immediately)
  439. if errors.Is(err, ErrSecretIsOwned) {
  440. r.markAsFailed(msgErrorIsOwned, err, externalSecret, syncCallsError.With(resourceLabels))
  441. return ctrl.Result{}, nil
  442. }
  443. // detect errors indicating that the secret is immutable
  444. // NOTE: this error cant be fixed by retrying so we don't return an error (which would requeue immediately)
  445. if errors.Is(err, ErrSecretImmutable) {
  446. r.markAsFailed(msgErrorUpdateImmutable, err, externalSecret, syncCallsError.With(resourceLabels))
  447. return ctrl.Result{}, nil
  448. }
  449. r.markAsFailed(msgErrorUpdateSecret, err, externalSecret, syncCallsError.With(resourceLabels))
  450. return ctrl.Result{}, err
  451. }
  452. r.markAsDone(externalSecret, start, log, esv1beta1.ConditionReasonSecretSynced, msgSynced)
  453. return r.getRequeueResult(externalSecret), nil
  454. }
  455. // getRequeueResult create a result with requeueAfter based on the ExternalSecret refresh interval.
  456. func (r *Reconciler) getRequeueResult(externalSecret *esv1beta1.ExternalSecret) ctrl.Result {
  457. // default to the global requeue interval
  458. // note, this will never be used because the CRD has a default value of 1 hour
  459. refreshInterval := r.RequeueInterval
  460. if externalSecret.Spec.RefreshInterval != nil {
  461. refreshInterval = externalSecret.Spec.RefreshInterval.Duration
  462. }
  463. // if the refresh interval is <= 0, we should not requeue
  464. if refreshInterval <= 0 {
  465. return ctrl.Result{}
  466. }
  467. // if the last refresh time is not set, requeue after the refresh interval
  468. // note, this should not happen, as we only call this function on ExternalSecrets
  469. // that have been reconciled at least once
  470. if externalSecret.Status.RefreshTime.IsZero() {
  471. return ctrl.Result{RequeueAfter: refreshInterval}
  472. }
  473. timeSinceLastRefresh := time.Since(externalSecret.Status.RefreshTime.Time)
  474. // if the last refresh time is in the future, we should requeue immediately
  475. // note, this should not happen, as we always refresh an ExternalSecret
  476. // that has a last refresh time in the future
  477. if timeSinceLastRefresh < 0 {
  478. return ctrl.Result{Requeue: true}
  479. }
  480. // if there is time remaining, requeue after the remaining time
  481. if timeSinceLastRefresh < refreshInterval {
  482. return ctrl.Result{RequeueAfter: refreshInterval - timeSinceLastRefresh}
  483. }
  484. // otherwise, requeue immediately
  485. return ctrl.Result{Requeue: true}
  486. }
  487. func (r *Reconciler) markAsDone(externalSecret *esv1beta1.ExternalSecret, start time.Time, log logr.Logger, reason, msg string) {
  488. oldReadyCondition := GetExternalSecretCondition(externalSecret.Status, esv1beta1.ExternalSecretReady)
  489. newReadyCondition := NewExternalSecretCondition(esv1beta1.ExternalSecretReady, v1.ConditionTrue, reason, msg)
  490. SetExternalSecretCondition(externalSecret, *newReadyCondition)
  491. externalSecret.Status.RefreshTime = metav1.NewTime(start)
  492. externalSecret.Status.SyncedResourceVersion = getResourceVersion(externalSecret)
  493. // if the status or reason has changed, log at the appropriate verbosity level
  494. if oldReadyCondition == nil || oldReadyCondition.Status != newReadyCondition.Status || oldReadyCondition.Reason != newReadyCondition.Reason {
  495. if newReadyCondition.Reason == esv1beta1.ConditionReasonSecretDeleted {
  496. log.Info("deleted secret")
  497. } else {
  498. log.Info("reconciled secret")
  499. }
  500. } else {
  501. log.V(1).Info("reconciled secret")
  502. }
  503. }
  504. func (r *Reconciler) markAsFailed(msg string, err error, externalSecret *esv1beta1.ExternalSecret, counter prometheus.Counter) {
  505. r.recorder.Event(externalSecret, v1.EventTypeWarning, esv1beta1.ReasonUpdateFailed, err.Error())
  506. conditionSynced := NewExternalSecretCondition(esv1beta1.ExternalSecretReady, v1.ConditionFalse, esv1beta1.ConditionReasonSecretSyncedError, msg)
  507. SetExternalSecretCondition(externalSecret, *conditionSynced)
  508. counter.Inc()
  509. }
  510. func deleteOrphanedSecrets(ctx context.Context, cl client.Client, externalSecret *esv1beta1.ExternalSecret, secretName string) error {
  511. ownerLabel := utils.ObjectHash(fmt.Sprintf("%v/%v", externalSecret.Namespace, externalSecret.Name))
  512. secretListPartial := &metav1.PartialObjectMetadataList{}
  513. secretListPartial.SetGroupVersionKind(v1.SchemeGroupVersion.WithKind("SecretList"))
  514. listOpts := &client.ListOptions{
  515. LabelSelector: labels.SelectorFromSet(map[string]string{
  516. esv1beta1.LabelOwner: ownerLabel,
  517. }),
  518. Namespace: externalSecret.Namespace,
  519. }
  520. if err := cl.List(ctx, secretListPartial, listOpts); err != nil {
  521. return err
  522. }
  523. // delete all secrets that are not the target secret
  524. for _, secretPartial := range secretListPartial.Items {
  525. if secretPartial.GetName() != secretName {
  526. if err := cl.Delete(ctx, &secretPartial); err != nil {
  527. return err
  528. }
  529. }
  530. }
  531. return nil
  532. }
  533. // createSecret creates a new secret with the given mutation function.
  534. func (r *Reconciler) createSecret(ctx context.Context, mutationFunc func(secret *v1.Secret) error, es *esv1beta1.ExternalSecret, secretName string) error {
  535. fqdn := fmt.Sprintf(fieldOwnerTemplate, es.Name)
  536. // define and mutate the new secret
  537. newSecret := &v1.Secret{
  538. ObjectMeta: metav1.ObjectMeta{
  539. Name: secretName,
  540. Namespace: es.Namespace,
  541. },
  542. Data: make(map[string][]byte),
  543. }
  544. if err := mutationFunc(newSecret); err != nil {
  545. return err
  546. }
  547. // note, we set field owner even for Create
  548. if err := r.Create(ctx, newSecret, client.FieldOwner(fqdn)); err != nil {
  549. return err
  550. }
  551. // set the binding reference to the secret
  552. // https://github.com/external-secrets/external-secrets/pull/2263
  553. es.Status.Binding = v1.LocalObjectReference{Name: newSecret.Name}
  554. r.recorder.Event(es, v1.EventTypeNormal, esv1beta1.ReasonCreated, "Created Secret")
  555. return nil
  556. }
  557. func (r *Reconciler) updateSecret(ctx context.Context, existingSecret *v1.Secret, mutationFunc func(secret *v1.Secret) error, es *esv1beta1.ExternalSecret, secretName string) error {
  558. fqdn := fmt.Sprintf(fieldOwnerTemplate, es.Name)
  559. // fail if the secret does not exist
  560. // this should never happen because we check this before calling this function
  561. if existingSecret.UID == "" {
  562. return fmt.Errorf(errUpdateNotFound, secretName)
  563. }
  564. // set the binding reference to the secret
  565. // https://github.com/external-secrets/external-secrets/pull/2263
  566. es.Status.Binding = v1.LocalObjectReference{Name: secretName}
  567. // mutate a copy of the existing secret with the mutation function
  568. updatedSecret := existingSecret.DeepCopy()
  569. if err := mutationFunc(updatedSecret); err != nil {
  570. return fmt.Errorf(errMutate, updatedSecret.Name, err)
  571. }
  572. // if the secret does not need to be updated, return early
  573. if equality.Semantic.DeepEqual(existingSecret, updatedSecret) {
  574. return nil
  575. }
  576. // if the existing secret is immutable, we can only update the object metadata
  577. if ptr.Deref(existingSecret.Immutable, false) {
  578. // check if the metadata was changed
  579. metadataChanged := !equality.Semantic.DeepEqual(existingSecret.ObjectMeta, updatedSecret.ObjectMeta)
  580. // check if the immutable data/type was changed
  581. var dataChanged bool
  582. if metadataChanged {
  583. // update the `existingSecret` object with the metadata from `updatedSecret`
  584. // this lets us compare the objects to see if the immutable data/type was changed
  585. existingSecret.ObjectMeta = *updatedSecret.ObjectMeta.DeepCopy()
  586. dataChanged = !equality.Semantic.DeepEqual(existingSecret, updatedSecret)
  587. // because we use labels and annotations to keep track of the secret,
  588. // we need to update the metadata, regardless of if the immutable data was changed
  589. // NOTE: we are using the `existingSecret` object here, as we ONLY want to update the metadata,
  590. // and we previously copied the metadata from the `updatedSecret` object
  591. if err := r.Update(ctx, existingSecret, client.FieldOwner(fqdn)); err != nil {
  592. // if we get a conflict, we should return early to requeue immediately
  593. // note, we don't wrap this error so we can handle it in the caller
  594. if apierrors.IsConflict(err) {
  595. return err
  596. }
  597. return fmt.Errorf(errUpdate, existingSecret.Name, err)
  598. }
  599. } else {
  600. // we know there was some change in the secret (or we would have returned early)
  601. // we know the metadata was NOT changed (metadataChanged == false)
  602. // so, the only thing that could have changed is the immutable data/type fields
  603. dataChanged = true
  604. }
  605. // if the immutable data was changed, we should return an error
  606. if dataChanged {
  607. return fmt.Errorf(errUpdate, existingSecret.Name, ErrSecretImmutable)
  608. }
  609. }
  610. // update the secret
  611. if err := r.Update(ctx, updatedSecret, client.FieldOwner(fqdn)); err != nil {
  612. // if we get a conflict, we should return early to requeue immediately
  613. // note, we don't wrap this error so we can handle it in the caller
  614. if apierrors.IsConflict(err) {
  615. return err
  616. }
  617. return fmt.Errorf(errUpdate, updatedSecret.Name, err)
  618. }
  619. r.recorder.Event(es, v1.EventTypeNormal, esv1beta1.ReasonUpdated, "Updated Secret")
  620. return nil
  621. }
  622. // getManagedDataKeys returns the list of data keys in a secret which are managed by a specified owner.
  623. func getManagedDataKeys(secret *v1.Secret, fieldOwner string) ([]string, error) {
  624. return getManagedFieldKeys(secret, fieldOwner, func(fields map[string]any) []string {
  625. dataFields := fields["f:data"]
  626. if dataFields == nil {
  627. return nil
  628. }
  629. df, ok := dataFields.(map[string]any)
  630. if !ok {
  631. return nil
  632. }
  633. return slices.Collect(maps.Keys(df))
  634. })
  635. }
  636. func getManagedFieldKeys(
  637. secret *v1.Secret,
  638. fieldOwner string,
  639. process func(fields map[string]any) []string,
  640. ) ([]string, error) {
  641. fqdn := fmt.Sprintf(fieldOwnerTemplate, fieldOwner)
  642. var keys []string
  643. for _, v := range secret.ObjectMeta.ManagedFields {
  644. if v.Manager != fqdn {
  645. continue
  646. }
  647. fields := make(map[string]any)
  648. err := json.Unmarshal(v.FieldsV1.Raw, &fields)
  649. if err != nil {
  650. return nil, fmt.Errorf("error unmarshaling managed fields: %w", err)
  651. }
  652. for _, key := range process(fields) {
  653. if key == "." {
  654. continue
  655. }
  656. keys = append(keys, strings.TrimPrefix(key, "f:"))
  657. }
  658. }
  659. return keys, nil
  660. }
  661. func getResourceVersion(es *esv1beta1.ExternalSecret) string {
  662. return fmt.Sprintf("%d-%s", es.ObjectMeta.GetGeneration(), hashMeta(es.ObjectMeta))
  663. }
  664. // hashMeta returns a consistent hash of the `metadata.labels` and `metadata.annotations` fields of the given object.
  665. func hashMeta(m metav1.ObjectMeta) string {
  666. type meta struct {
  667. annotations map[string]string
  668. labels map[string]string
  669. }
  670. objectMeta := meta{
  671. annotations: m.Annotations,
  672. labels: m.Labels,
  673. }
  674. return utils.ObjectHash(objectMeta)
  675. }
  676. func shouldSkipClusterSecretStore(r *Reconciler, es *esv1beta1.ExternalSecret) bool {
  677. return !r.ClusterSecretStoreEnabled && es.Spec.SecretStoreRef.Kind == esv1beta1.ClusterSecretStoreKind
  678. }
  679. // shouldSkipUnmanagedStore iterates over all secretStore references in the externalSecret spec,
  680. // fetches the store and evaluates the controllerClass property.
  681. // Returns true if any storeRef points to store with a non-matching controllerClass.
  682. func shouldSkipUnmanagedStore(ctx context.Context, namespace string, r *Reconciler, es *esv1beta1.ExternalSecret) (bool, error) {
  683. var storeList []esv1beta1.SecretStoreRef
  684. if es.Spec.SecretStoreRef.Name != "" {
  685. storeList = append(storeList, es.Spec.SecretStoreRef)
  686. }
  687. for _, ref := range es.Spec.Data {
  688. if ref.SourceRef != nil {
  689. storeList = append(storeList, ref.SourceRef.SecretStoreRef)
  690. }
  691. }
  692. for _, ref := range es.Spec.DataFrom {
  693. if ref.SourceRef != nil && ref.SourceRef.SecretStoreRef != nil {
  694. storeList = append(storeList, *ref.SourceRef.SecretStoreRef)
  695. }
  696. // verify that generator's controllerClass matches
  697. if ref.SourceRef != nil && ref.SourceRef.GeneratorRef != nil {
  698. _, obj, err := resolvers.GeneratorRef(ctx, r.Client, r.Scheme, namespace, ref.SourceRef.GeneratorRef)
  699. if err != nil {
  700. if apierrors.IsNotFound(err) {
  701. // skip non-existent generators
  702. continue
  703. }
  704. if errors.Is(err, resolvers.ErrUnableToGetGenerator) {
  705. // skip generators that we can't get (e.g. due to being invalid)
  706. continue
  707. }
  708. return false, err
  709. }
  710. skipGenerator, err := shouldSkipGenerator(r, obj)
  711. if err != nil {
  712. return false, err
  713. }
  714. if skipGenerator {
  715. return true, nil
  716. }
  717. }
  718. }
  719. for _, ref := range storeList {
  720. var store esv1beta1.GenericStore
  721. switch ref.Kind {
  722. case esv1beta1.SecretStoreKind, "":
  723. store = &esv1beta1.SecretStore{}
  724. case esv1beta1.ClusterSecretStoreKind:
  725. store = &esv1beta1.ClusterSecretStore{}
  726. namespace = ""
  727. }
  728. err := r.Get(ctx, types.NamespacedName{
  729. Name: ref.Name,
  730. Namespace: namespace,
  731. }, store)
  732. if err != nil {
  733. if apierrors.IsNotFound(err) {
  734. // skip non-existent stores
  735. continue
  736. }
  737. return false, err
  738. }
  739. class := store.GetSpec().Controller
  740. if class != "" && class != r.ControllerClass {
  741. return true, nil
  742. }
  743. }
  744. return false, nil
  745. }
  746. func shouldRefresh(es *esv1beta1.ExternalSecret) bool {
  747. // if the refresh interval is 0, and we have synced previously, we should not refresh
  748. if es.Spec.RefreshInterval.Duration <= 0 && es.Status.SyncedResourceVersion != "" {
  749. return false
  750. }
  751. // if the ExternalSecret has been updated, we should refresh
  752. if es.Status.SyncedResourceVersion != getResourceVersion(es) {
  753. return true
  754. }
  755. // if the last refresh time is zero, we should refresh
  756. if es.Status.RefreshTime.IsZero() {
  757. return true
  758. }
  759. // if the last refresh time is in the future, we should refresh
  760. if es.Status.RefreshTime.Time.After(time.Now()) {
  761. return true
  762. }
  763. // if the last refresh time + refresh interval is before now, we should refresh
  764. return es.Status.RefreshTime.Add(es.Spec.RefreshInterval.Duration).Before(time.Now())
  765. }
  766. // isSecretValid checks if the secret exists, and it's data is consistent with the calculated hash.
  767. func isSecretValid(existingSecret *v1.Secret) bool {
  768. // if target secret doesn't exist, we need to refresh
  769. if existingSecret.UID == "" {
  770. return false
  771. }
  772. // if the managed label is missing or incorrect, then it's invalid
  773. if existingSecret.Labels[esv1beta1.LabelManaged] != esv1beta1.LabelManagedValue {
  774. return false
  775. }
  776. // if the data-hash annotation is missing or incorrect, then it's invalid
  777. // this is how we know if the data has chanced since we last updated the secret
  778. if existingSecret.Annotations[esv1beta1.AnnotationDataHash] != utils.ObjectHash(existingSecret.Data) {
  779. return false
  780. }
  781. return true
  782. }
  783. // SetupWithManager returns a new controller builder that will be started by the provided Manager.
  784. func (r *Reconciler) SetupWithManager(mgr ctrl.Manager, opts controller.Options) error {
  785. r.recorder = mgr.GetEventRecorderFor("external-secrets")
  786. // index ExternalSecrets based on the target secret name,
  787. // this lets us quickly find all ExternalSecrets which target a specific Secret
  788. if err := mgr.GetFieldIndexer().IndexField(context.Background(), &esv1beta1.ExternalSecret{}, indexESTargetSecretNameField, func(obj client.Object) []string {
  789. es := obj.(*esv1beta1.ExternalSecret)
  790. // if the target name is set, use that as the index
  791. if es.Spec.Target.Name != "" {
  792. return []string{es.Spec.Target.Name}
  793. }
  794. // otherwise, use the ExternalSecret name
  795. return []string{es.Name}
  796. }); err != nil {
  797. return err
  798. }
  799. // predicate function to ignore secret events unless they have the "managed" label
  800. secretHasESLabel := predicate.NewPredicateFuncs(func(object client.Object) bool {
  801. value, hasLabel := object.GetLabels()[esv1beta1.LabelManaged]
  802. return hasLabel && value == esv1beta1.LabelManagedValue
  803. })
  804. return ctrl.NewControllerManagedBy(mgr).
  805. WithOptions(opts).
  806. For(&esv1beta1.ExternalSecret{}).
  807. // we cant use Owns(), as we don't set ownerReferences when the creationPolicy is not Owner.
  808. // we use WatchesMetadata() to reduce memory usage, as otherwise we have to process full secret objects.
  809. WatchesMetadata(
  810. &v1.Secret{},
  811. handler.EnqueueRequestsFromMapFunc(r.findObjectsForSecret),
  812. builder.WithPredicates(predicate.ResourceVersionChangedPredicate{}, secretHasESLabel),
  813. ).
  814. Complete(r)
  815. }
  816. func (r *Reconciler) findObjectsForSecret(ctx context.Context, secret client.Object) []reconcile.Request {
  817. externalSecretsList := &esv1beta1.ExternalSecretList{}
  818. listOps := &client.ListOptions{
  819. FieldSelector: fields.OneTermEqualSelector(indexESTargetSecretNameField, secret.GetName()),
  820. Namespace: secret.GetNamespace(),
  821. }
  822. err := r.List(ctx, externalSecretsList, listOps)
  823. if err != nil {
  824. return []reconcile.Request{}
  825. }
  826. requests := make([]reconcile.Request, len(externalSecretsList.Items))
  827. for i, item := range externalSecretsList.Items {
  828. requests[i] = reconcile.Request{
  829. NamespacedName: types.NamespacedName{
  830. Name: item.GetName(),
  831. Namespace: item.GetNamespace(),
  832. },
  833. }
  834. }
  835. return requests
  836. }
  837. func BuildManagedSecretClient(mgr ctrl.Manager) (client.Client, error) {
  838. // secrets we manage will have the `reconcile.external-secrets.io/managed=true` label
  839. managedLabelReq, _ := labels.NewRequirement(esv1beta1.LabelManaged, selection.Equals, []string{esv1beta1.LabelManagedValue})
  840. managedLabelSelector := labels.NewSelector().Add(*managedLabelReq)
  841. // create a new cache with a label selector for managed secrets
  842. // NOTE: this means that the cache/client will be unable to see secrets without the "managed" label
  843. secretCacheOpts := cache.Options{
  844. HTTPClient: mgr.GetHTTPClient(),
  845. Scheme: mgr.GetScheme(),
  846. Mapper: mgr.GetRESTMapper(),
  847. ByObject: map[client.Object]cache.ByObject{
  848. &v1.Secret{}: {
  849. Label: managedLabelSelector,
  850. },
  851. },
  852. // this requires us to explicitly start an informer for each object type
  853. // and helps avoid people mistakenly using the secret client for other resources
  854. ReaderFailOnMissingInformer: true,
  855. }
  856. secretCache, err := cache.New(mgr.GetConfig(), secretCacheOpts)
  857. if err != nil {
  858. return nil, err
  859. }
  860. // start an informer for secrets
  861. // this is required because we set ReaderFailOnMissingInformer to true
  862. _, err = secretCache.GetInformer(context.Background(), &v1.Secret{})
  863. if err != nil {
  864. return nil, err
  865. }
  866. // add the secret cache to the manager, so that it starts at the same time
  867. err = mgr.Add(secretCache)
  868. if err != nil {
  869. return nil, err
  870. }
  871. // create a new client that uses the secret cache
  872. secretClient, err := client.New(mgr.GetConfig(), client.Options{
  873. HTTPClient: mgr.GetHTTPClient(),
  874. Scheme: mgr.GetScheme(),
  875. Mapper: mgr.GetRESTMapper(),
  876. Cache: &client.CacheOptions{
  877. Reader: secretCache,
  878. },
  879. })
  880. if err != nil {
  881. return nil, err
  882. }
  883. return secretClient, nil
  884. }