externalsecret_controller.go 39 KB

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