externalsecret_controller.go 38 KB

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