externalsecret_controller.go 58 KB

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