externalsecret_controller_test.go 106 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974
  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. "bytes"
  15. "context"
  16. "encoding/json"
  17. "errors"
  18. "fmt"
  19. "os"
  20. "strconv"
  21. "time"
  22. "github.com/google/go-cmp/cmp"
  23. "github.com/google/go-cmp/cmp/cmpopts"
  24. "github.com/onsi/gomega/format"
  25. "github.com/prometheus/client_golang/prometheus"
  26. dto "github.com/prometheus/client_model/go"
  27. v1 "k8s.io/api/core/v1"
  28. apiextensions "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
  29. apierrors "k8s.io/apimachinery/pkg/api/errors"
  30. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  31. "k8s.io/apimachinery/pkg/types"
  32. "sigs.k8s.io/controller-runtime/pkg/client"
  33. esv1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1"
  34. genv1alpha1 "github.com/external-secrets/external-secrets/apis/generators/v1alpha1"
  35. ctest "github.com/external-secrets/external-secrets/pkg/controllers/commontest"
  36. "github.com/external-secrets/external-secrets/pkg/controllers/externalsecret/esmetrics"
  37. ctrlmetrics "github.com/external-secrets/external-secrets/pkg/controllers/metrics"
  38. "github.com/external-secrets/external-secrets/pkg/controllers/util"
  39. "github.com/external-secrets/external-secrets/pkg/provider/testing/fake"
  40. "github.com/external-secrets/external-secrets/pkg/utils"
  41. . "github.com/onsi/ginkgo/v2"
  42. . "github.com/onsi/gomega"
  43. )
  44. const (
  45. labelKey = "label-key"
  46. labelValue = "label-value"
  47. annotationKey = "annotation-key"
  48. annotationValue = "annotation-value"
  49. existingLabelKey = "existing-label-key"
  50. existingLabelValue = "existing-label-value"
  51. )
  52. var (
  53. fakeProvider *fake.Client
  54. metric dto.Metric
  55. metricDuration dto.Metric
  56. timeout = time.Second * 10
  57. interval = time.Millisecond * 250
  58. )
  59. var (
  60. testSyncCallsTotal *prometheus.CounterVec
  61. testSyncCallsError *prometheus.CounterVec
  62. testExternalSecretCondition *prometheus.GaugeVec
  63. testExternalSecretReconcileDuration *prometheus.GaugeVec
  64. )
  65. type testCase struct {
  66. secretStore esv1.GenericStore
  67. externalSecret *esv1.ExternalSecret
  68. targetSecretName string
  69. // checkCondition should return true if the externalSecret
  70. // has the expected condition
  71. checkCondition func(*esv1.ExternalSecret) bool
  72. // checkExternalSecret is called after the condition has been verified
  73. // use this to verify the externalSecret
  74. checkExternalSecret func(*esv1.ExternalSecret)
  75. // optional. use this to test the secret value
  76. checkSecret func(*esv1.ExternalSecret, *v1.Secret)
  77. }
  78. type testTweaks func(*testCase)
  79. var _ = Describe("Kind=secret existence logic", func() {
  80. validData := map[string][]byte{
  81. "foo": []byte("value1"),
  82. "bar": []byte("value2"),
  83. }
  84. type testCase struct {
  85. Name string
  86. Input *v1.Secret
  87. ExpectedOutput bool
  88. }
  89. tests := []testCase{
  90. {
  91. Name: "Should not be valid in case of missing uid",
  92. Input: &v1.Secret{},
  93. ExpectedOutput: false,
  94. },
  95. {
  96. Name: "A nil annotation should not be valid",
  97. Input: &v1.Secret{
  98. ObjectMeta: metav1.ObjectMeta{
  99. UID: "xxx",
  100. Labels: map[string]string{
  101. esv1.LabelManaged: esv1.LabelManagedValue,
  102. },
  103. Annotations: map[string]string{},
  104. },
  105. },
  106. ExpectedOutput: false,
  107. },
  108. {
  109. Name: "An invalid annotation hash should not be valid",
  110. Input: &v1.Secret{
  111. ObjectMeta: metav1.ObjectMeta{
  112. UID: "xxx",
  113. Labels: map[string]string{
  114. esv1.LabelManaged: esv1.LabelManagedValue,
  115. },
  116. Annotations: map[string]string{
  117. esv1.AnnotationDataHash: "xxxxxx",
  118. },
  119. },
  120. },
  121. ExpectedOutput: false,
  122. },
  123. {
  124. Name: "A valid secret should return true",
  125. Input: &v1.Secret{
  126. ObjectMeta: metav1.ObjectMeta{
  127. UID: "xxx",
  128. Labels: map[string]string{
  129. esv1.LabelManaged: esv1.LabelManagedValue,
  130. },
  131. Annotations: map[string]string{
  132. esv1.AnnotationDataHash: utils.ObjectHash(validData),
  133. },
  134. },
  135. Data: validData,
  136. },
  137. ExpectedOutput: true,
  138. },
  139. }
  140. for _, tt := range tests {
  141. It(tt.Name, func() {
  142. Expect(isSecretValid(tt.Input)).To(BeEquivalentTo(tt.ExpectedOutput))
  143. })
  144. }
  145. })
  146. var _ = Describe("ExternalSecret controller", Serial, func() {
  147. const (
  148. ExternalSecretName = "test-es"
  149. ExternalSecretFQDN = "externalsecrets.external-secrets.io/test-es"
  150. ExternalSecretStore = "test-store"
  151. ExternalSecretTargetSecretName = "test-secret"
  152. FakeManager = "fake.manager"
  153. expectedSecretVal = "SOMEVALUE was templated"
  154. targetPropObj = "{{ .targetProperty | toString | upper }} was templated"
  155. FooValue = "map-foo-value"
  156. BarValue = "map-bar-value"
  157. NamespaceLabelKey = "css-test-label-key"
  158. NamespaceLabelValue = "css-test-label-value"
  159. )
  160. var ExternalSecretNamespace string
  161. // if we are in debug and need to increase the timeout for testing, we can do so by using an env var
  162. if customTimeout := os.Getenv("TEST_CUSTOM_TIMEOUT_SEC"); customTimeout != "" {
  163. if t, err := strconv.Atoi(customTimeout); err == nil {
  164. timeout = time.Second * time.Duration(t)
  165. }
  166. }
  167. BeforeEach(func() {
  168. var err error
  169. ExternalSecretNamespace, err = ctest.CreateNamespaceWithLabels("test-ns", k8sClient, map[string]string{NamespaceLabelKey: NamespaceLabelValue})
  170. Expect(err).ToNot(HaveOccurred())
  171. metric.Reset()
  172. testSyncCallsTotal.Reset()
  173. testSyncCallsError.Reset()
  174. testExternalSecretCondition.Reset()
  175. testExternalSecretReconcileDuration.Reset()
  176. fakeProvider.Reset()
  177. })
  178. AfterEach(
  179. func() {
  180. secretStore := &esv1.SecretStore{}
  181. secretStoreLookupKey := types.NamespacedName{
  182. Name: ExternalSecretStore,
  183. Namespace: ExternalSecretNamespace,
  184. }
  185. if err := k8sClient.Get(context.Background(), secretStoreLookupKey, secretStore); err == nil {
  186. Expect(k8sClient.Delete(context.Background(), secretStore)).To(Succeed())
  187. }
  188. clusterSecretStore := &esv1.ClusterSecretStore{}
  189. clusterSecretStoreLookupKey := types.NamespacedName{
  190. Name: ExternalSecretStore,
  191. }
  192. if err := k8sClient.Get(context.Background(), clusterSecretStoreLookupKey, clusterSecretStore); err == nil {
  193. Expect(k8sClient.Delete(context.Background(), clusterSecretStore)).To(Succeed())
  194. }
  195. Expect(k8sClient.Delete(context.Background(), &v1.Namespace{
  196. ObjectMeta: metav1.ObjectMeta{
  197. Name: ExternalSecretNamespace,
  198. },
  199. })).To(Succeed())
  200. },
  201. )
  202. const (
  203. secretVal = "some-value"
  204. targetProp = "targetProperty"
  205. remoteKey = "barz"
  206. remoteProperty = "bang"
  207. existingKey = "pre-existing-key"
  208. existingVal = "pre-existing-value"
  209. )
  210. makeDefaultTestcase := func() *testCase {
  211. return &testCase{
  212. // default condition: es should be ready
  213. targetSecretName: ExternalSecretTargetSecretName,
  214. checkCondition: func(es *esv1.ExternalSecret) bool {
  215. cond := GetExternalSecretCondition(es.Status, esv1.ExternalSecretReady)
  216. if cond == nil || cond.Status != v1.ConditionTrue {
  217. return false
  218. }
  219. return true
  220. },
  221. checkExternalSecret: func(es *esv1.ExternalSecret) {
  222. // noop by default
  223. },
  224. secretStore: &esv1.SecretStore{
  225. ObjectMeta: metav1.ObjectMeta{
  226. Name: ExternalSecretStore,
  227. Namespace: ExternalSecretNamespace,
  228. },
  229. Spec: esv1.SecretStoreSpec{
  230. Provider: &esv1.SecretStoreProvider{
  231. AWS: &esv1.AWSProvider{
  232. Service: esv1.AWSServiceSecretsManager,
  233. },
  234. },
  235. },
  236. },
  237. externalSecret: &esv1.ExternalSecret{
  238. ObjectMeta: metav1.ObjectMeta{
  239. Name: ExternalSecretName,
  240. Namespace: ExternalSecretNamespace,
  241. },
  242. Spec: esv1.ExternalSecretSpec{
  243. SecretStoreRef: esv1.SecretStoreRef{
  244. Name: ExternalSecretStore,
  245. },
  246. Target: esv1.ExternalSecretTarget{
  247. Name: ExternalSecretTargetSecretName,
  248. },
  249. Data: []esv1.ExternalSecretData{
  250. {
  251. SecretKey: targetProp,
  252. RemoteRef: esv1.ExternalSecretDataRemoteRef{
  253. Key: remoteKey,
  254. Property: remoteProperty,
  255. },
  256. },
  257. },
  258. },
  259. },
  260. }
  261. }
  262. // if target Secret name is not specified it should use the ExternalSecret name.
  263. syncWithoutTargetName := func(tc *testCase) {
  264. tc.externalSecret.Spec.Target.Name = ""
  265. tc.checkSecret = func(es *esv1.ExternalSecret, secret *v1.Secret) {
  266. // check secret name
  267. Expect(secret.ObjectMeta.Name).To(Equal(ExternalSecretName))
  268. // check binding secret on external secret
  269. Expect(es.Status.Binding.Name).To(Equal(secret.ObjectMeta.Name))
  270. }
  271. }
  272. // if target Secret name is not specified it should use the ExternalSecret name.
  273. syncBigNames := func(tc *testCase) {
  274. tc.targetSecretName = "this-is-a-very-big-secret-name-that-wouldnt-be-generated-due-to-label-limits"
  275. tc.externalSecret.Spec.Target.Name = "this-is-a-very-big-secret-name-that-wouldnt-be-generated-due-to-label-limits"
  276. tc.checkSecret = func(es *esv1.ExternalSecret, secret *v1.Secret) {
  277. // check binding secret on external secret
  278. Expect(es.Status.Binding.Name).To(Equal(tc.externalSecret.Spec.Target.Name))
  279. }
  280. }
  281. // the secret name is reflected on the external secret's status as the binding secret
  282. syncBindingSecret := func(tc *testCase) {
  283. tc.checkSecret = func(es *esv1.ExternalSecret, secret *v1.Secret) {
  284. // check binding secret on external secret
  285. Expect(es.Status.Binding.Name).To(Equal(secret.ObjectMeta.Name))
  286. }
  287. }
  288. // their is no binding secret when a secret is not synced
  289. skipBindingSecret := func(tc *testCase) {
  290. tc.externalSecret.Spec.Target.CreationPolicy = esv1.CreatePolicyNone
  291. tc.checkExternalSecret = func(es *esv1.ExternalSecret) {
  292. // check binding secret is not set
  293. Expect(es.Status.Binding.Name).To(BeEmpty())
  294. }
  295. }
  296. // labels and annotations from the Kind=ExternalSecret
  297. // should be copied over to the Kind=Secret
  298. syncLabelsAnnotations := func(tc *testCase) {
  299. tc.externalSecret.ObjectMeta.Labels = map[string]string{
  300. labelKey: labelValue,
  301. }
  302. tc.externalSecret.ObjectMeta.Annotations = map[string]string{
  303. annotationKey: annotationValue,
  304. }
  305. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  306. tc.checkSecret = func(es *esv1.ExternalSecret, secret *v1.Secret) {
  307. Expect(secret.ObjectMeta.Labels).To(HaveKeyWithValue(labelKey, labelValue))
  308. Expect(secret.ObjectMeta.Annotations).To(HaveKeyWithValue(annotationKey, annotationValue))
  309. // ownerRef must not be set!
  310. Expect(ctest.HasOwnerRef(secret.ObjectMeta, "ExternalSecret", ExternalSecretName)).To(BeTrue())
  311. }
  312. }
  313. // labels and annotations from the ExternalSecret
  314. // should be merged to the Secret if exists
  315. mergeLabelsAnnotations := func(tc *testCase) {
  316. tc.externalSecret.ObjectMeta.Labels = map[string]string{
  317. labelKey: labelValue,
  318. }
  319. tc.externalSecret.ObjectMeta.Annotations = map[string]string{
  320. annotationKey: annotationValue,
  321. }
  322. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  323. // Create a secret owned by another entity to test if the pre-existing metadata is preserved
  324. Expect(k8sClient.Create(context.Background(), &v1.Secret{
  325. ObjectMeta: metav1.ObjectMeta{
  326. Name: ExternalSecretTargetSecretName,
  327. Namespace: ExternalSecretNamespace,
  328. Labels: map[string]string{
  329. existingLabelKey: existingLabelValue,
  330. },
  331. Annotations: map[string]string{
  332. "existing-annotation-key": "existing-annotation-value",
  333. },
  334. },
  335. }, client.FieldOwner(FakeManager))).To(Succeed())
  336. tc.checkSecret = func(es *esv1.ExternalSecret, secret *v1.Secret) {
  337. Expect(secret.ObjectMeta.Labels).To(HaveKeyWithValue(labelKey, labelValue))
  338. Expect(secret.ObjectMeta.Labels).To(HaveKeyWithValue(existingLabelKey, existingLabelValue))
  339. Expect(secret.ObjectMeta.Annotations).To(HaveKeyWithValue(annotationKey, annotationValue))
  340. Expect(secret.ObjectMeta.Annotations).To(HaveKeyWithValue("existing-annotation-key", "existing-annotation-value"))
  341. }
  342. }
  343. removeOutdatedLabelsAnnotations := func(tc *testCase) {
  344. tc.externalSecret.ObjectMeta.Labels = map[string]string{
  345. labelKey: labelValue,
  346. }
  347. tc.externalSecret.ObjectMeta.Annotations = map[string]string{
  348. annotationKey: annotationValue,
  349. }
  350. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  351. // Create a secret owned by the operator to test if the outdated pre-existing metadata is removed
  352. Expect(k8sClient.Create(context.Background(), &v1.Secret{
  353. ObjectMeta: metav1.ObjectMeta{
  354. Name: ExternalSecretTargetSecretName,
  355. Namespace: ExternalSecretNamespace,
  356. Labels: map[string]string{
  357. existingLabelKey: existingLabelValue,
  358. },
  359. Annotations: map[string]string{
  360. "existing-annotation-key": "existing-annotation-value",
  361. },
  362. },
  363. }, client.FieldOwner(ExternalSecretFQDN))).To(Succeed())
  364. tc.checkSecret = func(es *esv1.ExternalSecret, secret *v1.Secret) {
  365. Expect(secret.ObjectMeta.Labels).To(HaveKeyWithValue(labelKey, labelValue))
  366. Expect(secret.ObjectMeta.Labels).NotTo(HaveKeyWithValue(existingLabelKey, existingLabelValue))
  367. Expect(secret.ObjectMeta.Annotations).To(HaveKeyWithValue(annotationKey, annotationValue))
  368. Expect(secret.ObjectMeta.Annotations).NotTo(HaveKeyWithValue("existing-annotation-key", "existing-annotation-value"))
  369. }
  370. }
  371. checkPrometheusCounters := func(tc *testCase) {
  372. const secretVal = "someValue"
  373. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  374. tc.checkSecret = func(es *esv1.ExternalSecret, secret *v1.Secret) {
  375. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1.ExternalSecretReady, v1.ConditionFalse, 0.0)).To(BeTrue())
  376. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1.ExternalSecretReady, v1.ConditionTrue, 1.0)).To(BeTrue())
  377. Eventually(func() bool {
  378. Expect(testSyncCallsTotal.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metric)).To(Succeed())
  379. Expect(testExternalSecretReconcileDuration.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metricDuration)).To(Succeed())
  380. // three reconciliations: initial sync, status update, secret update
  381. return metric.GetCounter().GetValue() >= 2.0 && metricDuration.GetGauge().GetValue() > 0.0
  382. }, timeout, interval).Should(BeTrue())
  383. }
  384. }
  385. // merge with existing secret using creationPolicy=Merge
  386. // it should NOT have a ownerReference
  387. // metadata.managedFields with the correct owner should be added to the secret
  388. mergeWithSecret := func(tc *testCase) {
  389. const secretVal = "someValue"
  390. tc.externalSecret.Spec.Target.CreationPolicy = esv1.CreatePolicyMerge
  391. tc.externalSecret.Labels = map[string]string{
  392. "es-label-key": "es-label-value",
  393. }
  394. tc.externalSecret.Annotations = map[string]string{
  395. "es-annotation-key": "es-annotation-value",
  396. }
  397. // create secret beforehand
  398. Expect(k8sClient.Create(context.Background(), &v1.Secret{
  399. ObjectMeta: metav1.ObjectMeta{
  400. Name: ExternalSecretTargetSecretName,
  401. Namespace: ExternalSecretNamespace,
  402. Labels: map[string]string{
  403. existingLabelKey: existingLabelValue,
  404. },
  405. Annotations: map[string]string{
  406. "existing-annotation-key": "existing-annotation-value",
  407. },
  408. },
  409. Data: map[string][]byte{
  410. existingKey: []byte(existingVal),
  411. },
  412. }, client.FieldOwner(FakeManager))).To(Succeed())
  413. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  414. tc.checkSecret = func(es *esv1.ExternalSecret, secret *v1.Secret) {
  415. // check value
  416. Expect(string(secret.Data[existingKey])).To(Equal(existingVal))
  417. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  418. Expect(secret.ObjectMeta.Labels).To(HaveLen(3))
  419. Expect(secret.ObjectMeta.Labels).To(HaveKeyWithValue(existingLabelKey, existingLabelValue))
  420. Expect(secret.ObjectMeta.Labels).To(HaveKeyWithValue("es-label-key", "es-label-value"))
  421. Expect(secret.ObjectMeta.Labels).To(HaveKeyWithValue(esv1.LabelManaged, esv1.LabelManagedValue))
  422. Expect(secret.ObjectMeta.Annotations).To(HaveLen(3))
  423. Expect(secret.ObjectMeta.Annotations).To(HaveKeyWithValue("existing-annotation-key", "existing-annotation-value"))
  424. Expect(secret.ObjectMeta.Annotations).To(HaveKeyWithValue("es-annotation-key", "es-annotation-value"))
  425. Expect(secret.ObjectMeta.Annotations).To(HaveKey(esv1.AnnotationDataHash))
  426. Expect(ctest.HasOwnerRef(secret.ObjectMeta, "ExternalSecret", ExternalSecretFQDN)).To(BeFalse())
  427. Expect(secret.ObjectMeta.ManagedFields).To(HaveLen(2))
  428. oldCharactersAroundMismatchToInclude := format.CharactersAroundMismatchToInclude
  429. format.CharactersAroundMismatchToInclude = 10
  430. Expect(ctest.FirstManagedFieldForManager(secret.ObjectMeta, ExternalSecretFQDN)).To(
  431. Equal(fmt.Sprintf(`{"f:data":{"f:targetProperty":{}},"f:metadata":{"f:annotations":{"f:es-annotation-key":{},"f:%s":{}},"f:labels":{"f:es-label-key":{},"f:%s":{}}}}`, esv1.AnnotationDataHash, esv1.LabelManaged)),
  432. )
  433. Expect(ctest.FirstManagedFieldForManager(secret.ObjectMeta, FakeManager)).To(
  434. Equal(`{"f:data":{".":{},"f:pre-existing-key":{}},"f:metadata":{"f:annotations":{".":{},"f:existing-annotation-key":{}},"f:labels":{".":{},"f:existing-label-key":{}}},"f:type":{}}`),
  435. )
  436. format.CharactersAroundMismatchToInclude = oldCharactersAroundMismatchToInclude
  437. }
  438. }
  439. mergeWithSecretUpdate := func(tc *testCase) {
  440. const secretVal = "someValue"
  441. tc.externalSecret.Spec.Target.CreationPolicy = esv1.CreatePolicyMerge
  442. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Hour}
  443. Expect(k8sClient.Create(context.Background(), &v1.Secret{
  444. ObjectMeta: metav1.ObjectMeta{
  445. Name: ExternalSecretTargetSecretName,
  446. Namespace: ExternalSecretNamespace,
  447. },
  448. Data: map[string][]byte{
  449. existingKey: []byte(existingVal),
  450. },
  451. }, client.FieldOwner(FakeManager))).To(Succeed())
  452. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  453. tc.checkSecret = func(es *esv1.ExternalSecret, secret *v1.Secret) {
  454. // Overwrite the secret value to check if the change kicks reconciliation and overwrites it again
  455. Expect(k8sClient.Update(context.Background(), &v1.Secret{
  456. ObjectMeta: metav1.ObjectMeta{
  457. Name: ExternalSecretTargetSecretName,
  458. Namespace: ExternalSecretNamespace,
  459. },
  460. Data: map[string][]byte{
  461. existingKey: []byte("differentValue"),
  462. },
  463. }, client.FieldOwner(FakeManager))).To(Succeed())
  464. Expect(string(secret.Data[existingKey])).To(Equal(existingVal))
  465. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  466. }
  467. }
  468. // should not update if no changes
  469. mergeWithSecretNoChange := func(tc *testCase) {
  470. tc.externalSecret.Spec.Target.CreationPolicy = esv1.CreatePolicyMerge
  471. // create secret beforehand
  472. Expect(k8sClient.Create(context.Background(), &v1.Secret{
  473. ObjectMeta: metav1.ObjectMeta{
  474. Name: ExternalSecretTargetSecretName,
  475. Namespace: ExternalSecretNamespace,
  476. },
  477. Data: map[string][]byte{
  478. existingKey: []byte(existingVal),
  479. },
  480. }, client.FieldOwner(FakeManager))).To(Succeed())
  481. tc.checkSecret = func(es *esv1.ExternalSecret, secret *v1.Secret) {
  482. oldResourceVersion := secret.ResourceVersion
  483. cleanSecret := secret.DeepCopy()
  484. Expect(k8sClient.Patch(context.Background(), secret, client.MergeFrom(cleanSecret))).To(Succeed())
  485. newSecret := &v1.Secret{}
  486. Eventually(func() bool {
  487. secretLookupKey := types.NamespacedName{
  488. Name: ExternalSecretTargetSecretName,
  489. Namespace: ExternalSecretNamespace,
  490. }
  491. err := k8sClient.Get(context.Background(), secretLookupKey, newSecret)
  492. if err != nil {
  493. return false
  494. }
  495. return oldResourceVersion == newSecret.ResourceVersion
  496. }, timeout, interval).Should(Equal(true))
  497. }
  498. }
  499. // should not merge with secret if it doesn't exist
  500. mergeWithSecretErr := func(tc *testCase) {
  501. const secretVal = "someValue"
  502. tc.externalSecret.Spec.Target.CreationPolicy = esv1.CreatePolicyMerge
  503. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  504. tc.checkCondition = func(es *esv1.ExternalSecret) bool {
  505. expected := []esv1.ExternalSecretStatusCondition{
  506. {
  507. Type: esv1.ExternalSecretReady,
  508. Status: v1.ConditionTrue,
  509. Reason: esv1.ConditionReasonSecretMissing,
  510. Message: msgMissing,
  511. },
  512. }
  513. opts := cmpopts.IgnoreFields(esv1.ExternalSecretStatusCondition{}, "LastTransitionTime")
  514. if diff := cmp.Diff(expected, es.Status.Conditions, opts); diff != "" {
  515. GinkgoLogr.Info("(-got, +want)\n%s", "diff", diff)
  516. return false
  517. }
  518. return true
  519. }
  520. tc.checkExternalSecret = func(es *esv1.ExternalSecret) {
  521. Eventually(func() bool {
  522. Expect(testSyncCallsError.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metric)).To(Succeed())
  523. Expect(testExternalSecretReconcileDuration.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metricDuration)).To(Succeed())
  524. return metric.GetCounter().GetValue() == 0 && metricDuration.GetGauge().GetValue() > 0.0
  525. }, timeout, interval).Should(BeTrue())
  526. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1.ExternalSecretReady, v1.ConditionFalse, 0.0)).To(BeTrue())
  527. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1.ExternalSecretReady, v1.ConditionTrue, 1.0)).To(BeTrue())
  528. }
  529. }
  530. // controller should force ownership
  531. mergeWithConflict := func(tc *testCase) {
  532. const secretVal = "someValue"
  533. // this should confict
  534. const existingKey = targetProp
  535. tc.externalSecret.Spec.Target.CreationPolicy = esv1.CreatePolicyMerge
  536. // create secret beforehand
  537. Expect(k8sClient.Create(context.Background(), &v1.Secret{
  538. ObjectMeta: metav1.ObjectMeta{
  539. Name: ExternalSecretTargetSecretName,
  540. Namespace: ExternalSecretNamespace,
  541. },
  542. Data: map[string][]byte{
  543. existingKey: []byte(existingVal),
  544. },
  545. }, client.FieldOwner(FakeManager))).To(Succeed())
  546. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  547. tc.checkSecret = func(es *esv1.ExternalSecret, secret *v1.Secret) {
  548. // check that value stays the same
  549. Expect(string(secret.Data[existingKey])).To(Equal(secretVal))
  550. // check owner/managedFields
  551. Expect(ctest.HasOwnerRef(secret.ObjectMeta, "ExternalSecret", ExternalSecretFQDN)).To(BeFalse())
  552. Expect(secret.ObjectMeta.ManagedFields).To(HaveLen(2))
  553. oldCharactersAroundMismatchToInclude := format.CharactersAroundMismatchToInclude
  554. format.CharactersAroundMismatchToInclude = 10
  555. Expect(ctest.FirstManagedFieldForManager(secret.ObjectMeta, ExternalSecretFQDN)).To(
  556. Equal(fmt.Sprintf(`{"f:data":{"f:targetProperty":{}},"f:metadata":{"f:annotations":{".":{},"f:%s":{}},"f:labels":{".":{},"f:%s":{}}}}`, esv1.AnnotationDataHash, esv1.LabelManaged)),
  557. )
  558. format.CharactersAroundMismatchToInclude = oldCharactersAroundMismatchToInclude
  559. }
  560. }
  561. syncWithGeneratorRef := func(tc *testCase) {
  562. const secretKey = "somekey"
  563. const secretVal = "someValue"
  564. Expect(k8sClient.Create(context.Background(), &genv1alpha1.Fake{
  565. ObjectMeta: metav1.ObjectMeta{
  566. Name: "mytestfake",
  567. Namespace: ExternalSecretNamespace,
  568. },
  569. Spec: genv1alpha1.FakeSpec{
  570. Data: map[string]string{
  571. secretKey: secretVal,
  572. },
  573. },
  574. })).To(Succeed())
  575. // reset secretStoreRef
  576. tc.externalSecret.Spec.SecretStoreRef = esv1.SecretStoreRef{}
  577. tc.externalSecret.Spec.Data = nil
  578. tc.externalSecret.Spec.DataFrom = []esv1.ExternalSecretDataFromRemoteRef{
  579. {
  580. SourceRef: &esv1.StoreGeneratorSourceRef{
  581. GeneratorRef: &esv1.GeneratorRef{
  582. APIVersion: genv1alpha1.Group + "/" + genv1alpha1.Version,
  583. Kind: "Fake",
  584. Name: "mytestfake",
  585. },
  586. },
  587. },
  588. }
  589. tc.checkSecret = func(es *esv1.ExternalSecret, secret *v1.Secret) {
  590. // check values
  591. Expect(string(secret.Data[secretKey])).To(Equal(secretVal))
  592. }
  593. }
  594. syncWithClusterGeneratorRef := func(tc *testCase) {
  595. const secretKey = "somekey2"
  596. const secretVal = "someValue2"
  597. Expect(k8sClient.Create(context.Background(), &genv1alpha1.ClusterGenerator{
  598. ObjectMeta: metav1.ObjectMeta{
  599. Name: "mytestfake",
  600. },
  601. Spec: genv1alpha1.ClusterGeneratorSpec{
  602. Kind: "Fake",
  603. Generator: genv1alpha1.GeneratorSpec{
  604. FakeSpec: &genv1alpha1.FakeSpec{
  605. Data: map[string]string{
  606. secretKey: secretVal,
  607. },
  608. },
  609. },
  610. },
  611. })).To(Succeed())
  612. // reset secretStoreRef
  613. tc.externalSecret.Spec.SecretStoreRef = esv1.SecretStoreRef{}
  614. tc.externalSecret.Spec.Data = nil
  615. tc.externalSecret.Spec.DataFrom = []esv1.ExternalSecretDataFromRemoteRef{
  616. {
  617. SourceRef: &esv1.StoreGeneratorSourceRef{
  618. GeneratorRef: &esv1.GeneratorRef{
  619. APIVersion: genv1alpha1.Group + "/" + genv1alpha1.Version,
  620. Kind: "ClusterGenerator",
  621. Name: "mytestfake",
  622. },
  623. },
  624. },
  625. }
  626. tc.checkSecret = func(es *esv1.ExternalSecret, secret *v1.Secret) {
  627. // check values
  628. Expect(string(secret.Data[secretKey])).To(Equal(secretVal))
  629. }
  630. }
  631. deleteOrphanedSecrets := func(tc *testCase) {
  632. tc.checkSecret = func(es *esv1.ExternalSecret, secret *v1.Secret) {
  633. cleanEs := es.DeepCopy()
  634. oldSecret := v1.Secret{}
  635. oldSecretName := types.NamespacedName{
  636. Name: "test-secret",
  637. Namespace: secret.Namespace,
  638. }
  639. newSecret := v1.Secret{}
  640. secretName := types.NamespacedName{
  641. Name: "new-foo",
  642. Namespace: secret.Namespace,
  643. }
  644. Eventually(func() bool {
  645. err := k8sClient.Get(context.Background(), oldSecretName, &oldSecret)
  646. return err == nil
  647. }, time.Second*10, time.Millisecond*200).Should(BeTrue())
  648. es.Spec.Target.Name = "new-foo"
  649. Expect(k8sClient.Patch(context.Background(), es, client.MergeFrom(cleanEs))).To(Succeed())
  650. Eventually(func() bool {
  651. err := k8sClient.Get(context.Background(), secretName, &newSecret)
  652. return err == nil
  653. }, time.Second*10, time.Millisecond*200).Should(BeTrue())
  654. Eventually(func() bool {
  655. err := k8sClient.Get(context.Background(), oldSecretName, &oldSecret)
  656. return apierrors.IsNotFound(err)
  657. }, time.Second*10, time.Millisecond*200).Should(BeTrue())
  658. }
  659. }
  660. ignoreMismatchControllerForGeneratorRef := func(tc *testCase) {
  661. const secretKey = "somekey"
  662. const secretVal = "someValue"
  663. fakeGenerator := &genv1alpha1.Fake{
  664. ObjectMeta: metav1.ObjectMeta{
  665. Name: "mytestfake2",
  666. Namespace: ExternalSecretNamespace,
  667. },
  668. Spec: genv1alpha1.FakeSpec{
  669. Data: map[string]string{
  670. secretKey: secretVal,
  671. },
  672. Controller: "fakeControllerClass",
  673. },
  674. }
  675. fakeGeneratorJSON, _ := json.Marshal(fakeGenerator)
  676. Expect(shouldSkipGenerator(
  677. &Reconciler{
  678. ControllerClass: "default",
  679. },
  680. &apiextensions.JSON{Raw: fakeGeneratorJSON},
  681. )).To(BeTrue())
  682. }
  683. syncWithMultipleSecretStores := func(tc *testCase) {
  684. Expect(k8sClient.Create(context.Background(), &esv1.SecretStore{
  685. ObjectMeta: metav1.ObjectMeta{
  686. Name: "foo",
  687. Namespace: ExternalSecretNamespace,
  688. },
  689. Spec: esv1.SecretStoreSpec{
  690. Provider: &esv1.SecretStoreProvider{
  691. Fake: &esv1.FakeProvider{
  692. Data: []esv1.FakeProviderData{
  693. {
  694. Key: "foo",
  695. Version: "",
  696. Value: `{"foo":"bar","foo2":"bar2"}`,
  697. },
  698. },
  699. },
  700. },
  701. },
  702. })).To(Succeed())
  703. Expect(k8sClient.Create(context.Background(), &esv1.SecretStore{
  704. ObjectMeta: metav1.ObjectMeta{
  705. Name: "baz",
  706. Namespace: ExternalSecretNamespace,
  707. },
  708. Spec: esv1.SecretStoreSpec{
  709. Provider: &esv1.SecretStoreProvider{
  710. Fake: &esv1.FakeProvider{
  711. Data: []esv1.FakeProviderData{
  712. {
  713. Key: "baz",
  714. Version: "",
  715. Value: `{"baz":"bang","baz2":"bang2"}`,
  716. },
  717. },
  718. },
  719. },
  720. },
  721. })).To(Succeed())
  722. tc.externalSecret.Spec.DataFrom = []esv1.ExternalSecretDataFromRemoteRef{
  723. {
  724. Extract: &esv1.ExternalSecretDataRemoteRef{
  725. Key: "foo",
  726. },
  727. SourceRef: &esv1.StoreGeneratorSourceRef{
  728. SecretStoreRef: &esv1.SecretStoreRef{
  729. Name: "foo",
  730. Kind: esv1.SecretStoreKind,
  731. },
  732. },
  733. },
  734. {
  735. Extract: &esv1.ExternalSecretDataRemoteRef{
  736. Key: "baz",
  737. },
  738. SourceRef: &esv1.StoreGeneratorSourceRef{
  739. SecretStoreRef: &esv1.SecretStoreRef{
  740. Name: "baz",
  741. Kind: esv1.SecretStoreKind,
  742. },
  743. },
  744. },
  745. }
  746. tc.checkSecret = func(es *esv1.ExternalSecret, secret *v1.Secret) {
  747. // check values
  748. Expect(string(secret.Data["foo"])).To(Equal("bar"))
  749. Expect(string(secret.Data["foo2"])).To(Equal("bar2"))
  750. Expect(string(secret.Data["baz"])).To(Equal("bang"))
  751. Expect(string(secret.Data["baz2"])).To(Equal("bang2"))
  752. }
  753. }
  754. // when using a template it should be used as a blueprint
  755. // to construct a new secret: labels, annotations and type
  756. syncWithTemplate := func(tc *testCase) {
  757. const secretVal = "someValue"
  758. const tplStaticKey = "tplstatickey"
  759. const tplStaticVal = "tplstaticvalue"
  760. tc.externalSecret.ObjectMeta.Labels = map[string]string{
  761. "fooobar": "bazz",
  762. }
  763. tc.externalSecret.ObjectMeta.Annotations = map[string]string{
  764. "hihihih": "hehehe",
  765. }
  766. tc.externalSecret.Spec.Target.Template = &esv1.ExternalSecretTemplate{
  767. Metadata: esv1.ExternalSecretTemplateMetadata{
  768. Labels: map[string]string{
  769. "foos": "ball",
  770. },
  771. Annotations: map[string]string{
  772. "hihi": "ga",
  773. },
  774. },
  775. Type: v1.SecretTypeOpaque,
  776. EngineVersion: esv1.TemplateEngineV2,
  777. Data: map[string]string{
  778. targetProp: targetPropObj,
  779. tplStaticKey: tplStaticVal,
  780. },
  781. }
  782. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  783. tc.checkSecret = func(es *esv1.ExternalSecret, secret *v1.Secret) {
  784. // check values
  785. Expect(string(secret.Data[targetProp])).To(Equal(expectedSecretVal))
  786. Expect(string(secret.Data[tplStaticKey])).To(Equal(tplStaticVal))
  787. // labels/annotations should be taken from the template
  788. for k, v := range es.Spec.Target.Template.Metadata.Labels {
  789. Expect(secret.ObjectMeta.Labels).To(HaveKeyWithValue(k, v))
  790. }
  791. for k, v := range es.Spec.Target.Template.Metadata.Annotations {
  792. Expect(secret.ObjectMeta.Annotations).To(HaveKeyWithValue(k, v))
  793. }
  794. }
  795. }
  796. // when using a v2 template it should use the v2 engine version
  797. syncWithTemplateV2 := func(tc *testCase) {
  798. const secretVal = "someValue"
  799. tc.externalSecret.Spec.Target.Template = &esv1.ExternalSecretTemplate{
  800. Type: v1.SecretTypeOpaque,
  801. // it should default to v2 for beta11
  802. // EngineVersion: esv1.TemplateEngineV2,
  803. Data: map[string]string{
  804. targetProp: "{{ .targetProperty | upper }} was templated",
  805. },
  806. }
  807. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  808. tc.checkSecret = func(es *esv1.ExternalSecret, secret *v1.Secret) {
  809. // check values
  810. Expect(string(secret.Data[targetProp])).To(Equal(expectedSecretVal))
  811. }
  812. }
  813. // // secret should be synced with correct value precedence:
  814. // // * fromString
  815. // // * template data
  816. // // * templateFrom
  817. // // * data
  818. // // * dataFrom
  819. syncWithTemplatePrecedence := func(tc *testCase) {
  820. const secretVal = "someValue"
  821. const tplStaticKey = "tplstatickey"
  822. const tplStaticVal = "tplstaticvalue"
  823. const tplFromCMName = "template-cm"
  824. const tplFromSecretName = "template-secret"
  825. const tplFromKey = "tpl-from-key"
  826. const tplFromSecKey = "tpl-from-sec-key"
  827. const tplFromVal = "tpl-from-value: {{ .targetProperty | toString }} // {{ .bar | toString }}"
  828. const tplFromSecVal = "tpl-from-sec-value: {{ .targetProperty | toString }} // {{ .bar | toString }}"
  829. Expect(k8sClient.Create(context.Background(), &v1.ConfigMap{
  830. ObjectMeta: metav1.ObjectMeta{
  831. Name: tplFromCMName,
  832. Namespace: ExternalSecretNamespace,
  833. },
  834. Data: map[string]string{
  835. tplFromKey: tplFromVal,
  836. },
  837. })).To(Succeed())
  838. Expect(k8sClient.Create(context.Background(), &v1.Secret{
  839. ObjectMeta: metav1.ObjectMeta{
  840. Name: tplFromSecretName,
  841. Namespace: ExternalSecretNamespace,
  842. },
  843. Data: map[string][]byte{
  844. tplFromSecKey: []byte(tplFromSecVal),
  845. },
  846. })).To(Succeed())
  847. tc.externalSecret.Spec.Target.Template = &esv1.ExternalSecretTemplate{
  848. Metadata: esv1.ExternalSecretTemplateMetadata{},
  849. Type: v1.SecretTypeOpaque,
  850. TemplateFrom: []esv1.TemplateFrom{
  851. {
  852. ConfigMap: &esv1.TemplateRef{
  853. Name: tplFromCMName,
  854. Items: []esv1.TemplateRefItem{
  855. {
  856. Key: tplFromKey,
  857. },
  858. },
  859. },
  860. },
  861. {
  862. Secret: &esv1.TemplateRef{
  863. Name: tplFromSecretName,
  864. Items: []esv1.TemplateRefItem{
  865. {
  866. Key: tplFromSecKey,
  867. },
  868. },
  869. },
  870. },
  871. },
  872. Data: map[string]string{
  873. // this should be the data value, not dataFrom
  874. targetProp: targetPropObj,
  875. // this should use the value from the map
  876. "bar": "value from map: {{ .bar | toString }}",
  877. // just a static value
  878. tplStaticKey: tplStaticVal,
  879. },
  880. }
  881. tc.externalSecret.Spec.DataFrom = []esv1.ExternalSecretDataFromRemoteRef{
  882. {
  883. Extract: &esv1.ExternalSecretDataRemoteRef{
  884. Key: "datamap",
  885. },
  886. },
  887. }
  888. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  889. fakeProvider.WithGetSecretMap(map[string][]byte{
  890. "targetProperty": []byte(FooValue),
  891. "bar": []byte(BarValue),
  892. }, nil)
  893. tc.checkSecret = func(es *esv1.ExternalSecret, secret *v1.Secret) {
  894. // check values
  895. Expect(string(secret.Data[targetProp])).To(Equal(expectedSecretVal))
  896. Expect(string(secret.Data[tplStaticKey])).To(Equal(tplStaticVal))
  897. Expect(string(secret.Data["bar"])).To(Equal("value from map: map-bar-value"))
  898. Expect(string(secret.Data[tplFromKey])).To(Equal("tpl-from-value: someValue // map-bar-value"))
  899. Expect(string(secret.Data[tplFromSecKey])).To(Equal("tpl-from-sec-value: someValue // map-bar-value"))
  900. }
  901. }
  902. syncTemplateFromKeysAndValues := func(tc *testCase) {
  903. const tplFromCMName = "template-cm"
  904. const tplFromSecretName = "template-secret"
  905. const tplFromKey = "tpl-from-key"
  906. const tplFromSecKey = "tpl-from-sec-key"
  907. const tplFromVal = "{{ .targetKey }}-cm: {{ .targetValue }}"
  908. const tplFromSecVal = "{{ .targetKey }}-sec: {{ .targetValue }}"
  909. Expect(k8sClient.Create(context.Background(), &v1.ConfigMap{
  910. ObjectMeta: metav1.ObjectMeta{
  911. Name: tplFromCMName,
  912. Namespace: ExternalSecretNamespace,
  913. },
  914. Data: map[string]string{
  915. tplFromKey: tplFromVal,
  916. },
  917. })).To(Succeed())
  918. Expect(k8sClient.Create(context.Background(), &v1.Secret{
  919. ObjectMeta: metav1.ObjectMeta{
  920. Name: tplFromSecretName,
  921. Namespace: ExternalSecretNamespace,
  922. },
  923. Data: map[string][]byte{
  924. tplFromSecKey: []byte(tplFromSecVal),
  925. },
  926. })).To(Succeed())
  927. tc.externalSecret.Spec.Target.Template = &esv1.ExternalSecretTemplate{
  928. Metadata: esv1.ExternalSecretTemplateMetadata{},
  929. Type: v1.SecretTypeOpaque,
  930. TemplateFrom: []esv1.TemplateFrom{
  931. {
  932. ConfigMap: &esv1.TemplateRef{
  933. Name: tplFromCMName,
  934. Items: []esv1.TemplateRefItem{
  935. {
  936. Key: tplFromKey,
  937. TemplateAs: esv1.TemplateScopeKeysAndValues,
  938. },
  939. },
  940. },
  941. },
  942. {
  943. Secret: &esv1.TemplateRef{
  944. Name: tplFromSecretName,
  945. Items: []esv1.TemplateRefItem{
  946. {
  947. Key: tplFromSecKey,
  948. TemplateAs: esv1.TemplateScopeKeysAndValues,
  949. },
  950. },
  951. },
  952. },
  953. },
  954. }
  955. tc.externalSecret.Spec.DataFrom = []esv1.ExternalSecretDataFromRemoteRef{
  956. {
  957. Extract: &esv1.ExternalSecretDataRemoteRef{
  958. Key: "datamap",
  959. },
  960. },
  961. }
  962. fakeProvider.WithGetSecretMap(map[string][]byte{
  963. "targetKey": []byte(FooValue),
  964. "targetValue": []byte(BarValue),
  965. }, nil)
  966. tc.checkSecret = func(es *esv1.ExternalSecret, secret *v1.Secret) {
  967. // check values
  968. Expect(string(secret.Data["map-foo-value-cm"])).To(Equal(BarValue))
  969. Expect(string(secret.Data["map-foo-value-sec"])).To(Equal(BarValue))
  970. }
  971. }
  972. syncTemplateFromLiteral := func(tc *testCase) {
  973. tplDataVal := "{{ .targetKey }}-literal: {{ .targetValue }}"
  974. tplAnnotationsVal := "{{ .targetKey }}-annotations: {{ .targetValue }}"
  975. tplLabelsVal := "{{ .targetKey }}-labels: {{ .targetValue }}"
  976. tplComplexVal := `
  977. {{- range $k, $v := ( .complex | fromJson )}}
  978. {{ $k }}: {{ $v }}
  979. {{- end }}
  980. `
  981. tc.externalSecret.Spec.Target.Template = &esv1.ExternalSecretTemplate{
  982. Metadata: esv1.ExternalSecretTemplateMetadata{},
  983. Type: v1.SecretTypeOpaque,
  984. TemplateFrom: []esv1.TemplateFrom{
  985. {
  986. Literal: &tplDataVal,
  987. },
  988. {
  989. Literal: &tplComplexVal,
  990. },
  991. {
  992. Target: esv1.TemplateTargetAnnotations,
  993. Literal: &tplAnnotationsVal,
  994. },
  995. {
  996. Target: esv1.TemplateTargetLabels,
  997. Literal: &tplLabelsVal,
  998. },
  999. },
  1000. }
  1001. tc.externalSecret.Spec.DataFrom = []esv1.ExternalSecretDataFromRemoteRef{
  1002. {
  1003. Extract: &esv1.ExternalSecretDataRemoteRef{
  1004. Key: "datamap",
  1005. },
  1006. },
  1007. }
  1008. fakeProvider.WithGetSecretMap(map[string][]byte{
  1009. "targetKey": []byte(FooValue),
  1010. "targetValue": []byte(BarValue),
  1011. "complex": []byte("{\"nested\":\"json\",\"can\":\"be\",\"templated\":\"successfully\"}"),
  1012. }, nil)
  1013. tc.checkSecret = func(es *esv1.ExternalSecret, secret *v1.Secret) {
  1014. // check values
  1015. Expect(string(secret.Data["map-foo-value-literal"])).To(Equal(BarValue))
  1016. Expect(string(secret.Data["nested"])).To(Equal("json"))
  1017. Expect(string(secret.Data["can"])).To(Equal("be"))
  1018. Expect(string(secret.Data["templated"])).To(Equal("successfully"))
  1019. Expect(secret.ObjectMeta.Annotations["map-foo-value-annotations"]).To(Equal(BarValue))
  1020. Expect(secret.ObjectMeta.Labels["map-foo-value-labels"]).To(Equal(BarValue))
  1021. }
  1022. }
  1023. refreshWithTemplate := func(tc *testCase) {
  1024. const secretVal = "someValue"
  1025. const tplStaticKey = "tplstatickey"
  1026. const tplStaticVal = "tplstaticvalue"
  1027. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Second}
  1028. tc.externalSecret.Spec.Target.Template = &esv1.ExternalSecretTemplate{
  1029. Metadata: esv1.ExternalSecretTemplateMetadata{
  1030. Labels: map[string]string{"foo": "bar"},
  1031. Annotations: map[string]string{"foo": "bar"},
  1032. },
  1033. Type: v1.SecretTypeOpaque,
  1034. Data: map[string]string{
  1035. targetProp: targetPropObj,
  1036. tplStaticKey: tplStaticVal,
  1037. },
  1038. }
  1039. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  1040. tc.checkSecret = func(es *esv1.ExternalSecret, secret *v1.Secret) {
  1041. // check values
  1042. Expect(string(secret.Data[targetProp])).To(Equal(expectedSecretVal))
  1043. Expect(string(secret.Data[tplStaticKey])).To(Equal(tplStaticVal))
  1044. // labels/annotations should be taken from the template
  1045. for k, v := range es.Spec.Target.Template.Metadata.Labels {
  1046. Expect(secret.ObjectMeta.Labels).To(HaveKeyWithValue(k, v))
  1047. }
  1048. // a secret will always have some extra annotations (i.e. hashmap check), so we only check for specific
  1049. // source annotations
  1050. for k, v := range es.Spec.Target.Template.Metadata.Annotations {
  1051. Expect(secret.ObjectMeta.Annotations).To(HaveKeyWithValue(k, v))
  1052. }
  1053. cleanEs := tc.externalSecret.DeepCopy()
  1054. // now update ExternalSecret
  1055. tc.externalSecret.Spec.Target.Template.Metadata.Annotations["fuzz"] = "buzz"
  1056. tc.externalSecret.Spec.Target.Template.Metadata.Labels["fuzz"] = "buzz"
  1057. tc.externalSecret.Spec.Target.Template.Data["new"] = "value"
  1058. Expect(k8sClient.Patch(context.Background(), tc.externalSecret, client.MergeFrom(cleanEs))).To(Succeed())
  1059. // wait for secret
  1060. sec := &v1.Secret{}
  1061. secretLookupKey := types.NamespacedName{
  1062. Name: ExternalSecretTargetSecretName,
  1063. Namespace: ExternalSecretNamespace,
  1064. }
  1065. Eventually(func() bool {
  1066. err := k8sClient.Get(context.Background(), secretLookupKey, sec)
  1067. if err != nil {
  1068. return false
  1069. }
  1070. // ensure new data value exist
  1071. return string(sec.Data["new"]) == "value"
  1072. }, time.Second*10, time.Millisecond*200).Should(BeTrue())
  1073. // also check labels/annotations have been updated
  1074. for k, v := range es.Spec.Target.Template.Metadata.Labels {
  1075. Expect(secret.ObjectMeta.Labels).To(HaveKeyWithValue(k, v))
  1076. }
  1077. for k, v := range es.Spec.Target.Template.Metadata.Annotations {
  1078. Expect(secret.ObjectMeta.Annotations).To(HaveKeyWithValue(k, v))
  1079. }
  1080. }
  1081. }
  1082. onlyMetadataFromTemplate := func(tc *testCase) {
  1083. const secretVal = "someValue"
  1084. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Second}
  1085. tc.externalSecret.Spec.Target.Template = &esv1.ExternalSecretTemplate{
  1086. Metadata: esv1.ExternalSecretTemplateMetadata{
  1087. Labels: map[string]string{"foo": "bar"},
  1088. Annotations: map[string]string{"foo": "bar"},
  1089. },
  1090. }
  1091. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  1092. tc.checkSecret = func(es *esv1.ExternalSecret, secret *v1.Secret) {
  1093. // check values
  1094. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  1095. // labels/annotations should be taken from the template
  1096. for k, v := range es.Spec.Target.Template.Metadata.Labels {
  1097. Expect(secret.ObjectMeta.Labels).To(HaveKeyWithValue(k, v))
  1098. }
  1099. for k, v := range es.Spec.Target.Template.Metadata.Annotations {
  1100. Expect(secret.ObjectMeta.Annotations).To(HaveKeyWithValue(k, v))
  1101. }
  1102. }
  1103. }
  1104. // when the provider secret changes the Kind=Secret value
  1105. // must change, too.
  1106. refreshSecretValue := func(tc *testCase) {
  1107. const targetProp = "targetProperty"
  1108. const secretVal = "someValue"
  1109. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  1110. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Second}
  1111. tc.checkSecret = func(es *esv1.ExternalSecret, secret *v1.Secret) {
  1112. // check values
  1113. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  1114. // update provider secret
  1115. newValue := "NEW VALUE"
  1116. sec := &v1.Secret{}
  1117. fakeProvider.WithGetSecret([]byte(newValue), nil)
  1118. secretLookupKey := types.NamespacedName{
  1119. Name: ExternalSecretTargetSecretName,
  1120. Namespace: ExternalSecretNamespace,
  1121. }
  1122. Eventually(func() bool {
  1123. err := k8sClient.Get(context.Background(), secretLookupKey, sec)
  1124. if err != nil {
  1125. return false
  1126. }
  1127. v := sec.Data[targetProp]
  1128. return string(v) == newValue
  1129. }, timeout, interval).Should(BeTrue())
  1130. }
  1131. }
  1132. // when a provider secret was deleted it must be deleted from
  1133. // the secret aswell
  1134. refreshSecretValueMap := func(tc *testCase) {
  1135. fakeProvider.WithGetSecretMap(map[string][]byte{
  1136. "foo": []byte("1111"),
  1137. "bar": []byte("2222"),
  1138. }, nil)
  1139. tc.externalSecret.Spec.Data = []esv1.ExternalSecretData{}
  1140. tc.externalSecret.Spec.DataFrom = []esv1.ExternalSecretDataFromRemoteRef{
  1141. {
  1142. Extract: &esv1.ExternalSecretDataRemoteRef{
  1143. Key: remoteKey,
  1144. },
  1145. },
  1146. }
  1147. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Second}
  1148. tc.checkSecret = func(es *esv1.ExternalSecret, secret *v1.Secret) {
  1149. // check values
  1150. Expect(string(secret.Data["foo"])).To(Equal("1111"))
  1151. Expect(string(secret.Data["bar"])).To(Equal("2222"))
  1152. // update provider secret
  1153. sec := &v1.Secret{}
  1154. fakeProvider.WithGetSecretMap(map[string][]byte{
  1155. "foo": []byte("1111"),
  1156. }, nil)
  1157. secretLookupKey := types.NamespacedName{
  1158. Name: ExternalSecretTargetSecretName,
  1159. Namespace: ExternalSecretNamespace,
  1160. }
  1161. Eventually(func() bool {
  1162. err := k8sClient.Get(context.Background(), secretLookupKey, sec)
  1163. if err != nil {
  1164. return false
  1165. }
  1166. return string(sec.Data["foo"]) == "1111" &&
  1167. sec.Data["bar"] == nil // must not be defined, it was deleted
  1168. }, timeout, interval).Should(BeTrue())
  1169. }
  1170. }
  1171. // when a provider secret was deleted it must be deleted from
  1172. // the secret aswell when using a template
  1173. refreshSecretValueMapTemplate := func(tc *testCase) {
  1174. fakeProvider.WithGetSecretMap(map[string][]byte{
  1175. "foo": []byte("1111"),
  1176. "bar": []byte("2222"),
  1177. }, nil)
  1178. tc.externalSecret.Spec.Target.Template = &esv1.ExternalSecretTemplate{}
  1179. tc.externalSecret.Spec.Data = []esv1.ExternalSecretData{}
  1180. tc.externalSecret.Spec.DataFrom = []esv1.ExternalSecretDataFromRemoteRef{
  1181. {
  1182. Extract: &esv1.ExternalSecretDataRemoteRef{
  1183. Key: remoteKey,
  1184. },
  1185. },
  1186. }
  1187. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Second}
  1188. tc.checkSecret = func(es *esv1.ExternalSecret, secret *v1.Secret) {
  1189. // check values
  1190. Expect(string(secret.Data["foo"])).To(Equal("1111"))
  1191. Expect(string(secret.Data["bar"])).To(Equal("2222"))
  1192. // update provider secret
  1193. sec := &v1.Secret{}
  1194. fakeProvider.WithGetSecretMap(map[string][]byte{
  1195. "foo": []byte("1111"),
  1196. }, nil)
  1197. secretLookupKey := types.NamespacedName{
  1198. Name: ExternalSecretTargetSecretName,
  1199. Namespace: ExternalSecretNamespace,
  1200. }
  1201. Eventually(func() bool {
  1202. err := k8sClient.Get(context.Background(), secretLookupKey, sec)
  1203. if err != nil {
  1204. return false
  1205. }
  1206. return string(sec.Data["foo"]) == "1111" &&
  1207. sec.Data["bar"] == nil // must not be defined, it was deleted
  1208. }, timeout, interval).Should(BeTrue())
  1209. }
  1210. }
  1211. refreshintervalZero := func(tc *testCase) {
  1212. const targetProp = "targetProperty"
  1213. const secretVal = "someValue"
  1214. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  1215. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: 0}
  1216. tc.checkSecret = func(es *esv1.ExternalSecret, secret *v1.Secret) {
  1217. // check values
  1218. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  1219. // update provider secret
  1220. newValue := "NEW VALUE"
  1221. sec := &v1.Secret{}
  1222. fakeProvider.WithGetSecret([]byte(newValue), nil)
  1223. secretLookupKey := types.NamespacedName{
  1224. Name: ExternalSecretTargetSecretName,
  1225. Namespace: ExternalSecretNamespace,
  1226. }
  1227. Consistently(func() bool {
  1228. err := k8sClient.Get(context.Background(), secretLookupKey, sec)
  1229. if err != nil {
  1230. return false
  1231. }
  1232. v := sec.Data[targetProp]
  1233. return string(v) == secretVal
  1234. }, time.Second*10, time.Second).Should(BeTrue())
  1235. }
  1236. }
  1237. deletionPolicyDelete := func(tc *testCase) {
  1238. expVal := []byte("1234")
  1239. // set initial value
  1240. fakeProvider.WithGetAllSecrets(map[string][]byte{
  1241. "foo": expVal,
  1242. "bar": expVal,
  1243. }, nil)
  1244. tc.externalSecret.Spec.Data = nil
  1245. tc.externalSecret.Spec.DataFrom = []esv1.ExternalSecretDataFromRemoteRef{
  1246. {
  1247. Find: &esv1.ExternalSecretFind{
  1248. Tags: map[string]string{},
  1249. },
  1250. },
  1251. }
  1252. tc.externalSecret.Spec.Target.DeletionPolicy = esv1.DeletionPolicyDelete
  1253. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Second}
  1254. tc.checkSecret = func(es *esv1.ExternalSecret, secret *v1.Secret) {
  1255. Expect(secret.Data["foo"]).To(Equal(expVal))
  1256. // update provider secret
  1257. fakeProvider.WithGetAllSecrets(map[string][]byte{
  1258. "foo": expVal,
  1259. }, nil)
  1260. sec := &v1.Secret{}
  1261. secretLookupKey := types.NamespacedName{
  1262. Name: ExternalSecretTargetSecretName,
  1263. Namespace: ExternalSecretNamespace,
  1264. }
  1265. Eventually(func() bool {
  1266. By("checking secret value for foo=1234 and bar=nil")
  1267. err := k8sClient.Get(context.Background(), secretLookupKey, sec)
  1268. if err != nil {
  1269. return false
  1270. }
  1271. return bytes.Equal(sec.Data["foo"], expVal) && sec.Data["bar"] == nil
  1272. }, time.Second*10, time.Second).Should(BeTrue())
  1273. // return specific delete err to indicate deletion
  1274. fakeProvider.WithGetAllSecrets(map[string][]byte{}, esv1.NoSecretErr)
  1275. Eventually(func() bool {
  1276. By("checking that secret has been deleted")
  1277. err := k8sClient.Get(context.Background(), secretLookupKey, sec)
  1278. return apierrors.IsNotFound(err)
  1279. }, time.Second*10, time.Second).Should(BeTrue())
  1280. }
  1281. }
  1282. deletionPolicyRetain := func(tc *testCase) {
  1283. expVal := []byte("1234")
  1284. // set initial value
  1285. fakeProvider.WithGetAllSecrets(map[string][]byte{
  1286. "foo": expVal,
  1287. "bar": expVal,
  1288. }, nil)
  1289. tc.externalSecret.Spec.DataFrom = []esv1.ExternalSecretDataFromRemoteRef{
  1290. {
  1291. Find: &esv1.ExternalSecretFind{
  1292. Tags: map[string]string{},
  1293. },
  1294. },
  1295. }
  1296. tc.externalSecret.Spec.Target.DeletionPolicy = esv1.DeletionPolicyRetain
  1297. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Second}
  1298. tc.checkSecret = func(es *esv1.ExternalSecret, secret *v1.Secret) {
  1299. Expect(secret.Data["foo"]).To(Equal(expVal))
  1300. sec := &v1.Secret{}
  1301. secretLookupKey := types.NamespacedName{
  1302. Name: ExternalSecretTargetSecretName,
  1303. Namespace: ExternalSecretNamespace,
  1304. }
  1305. // return specific delete err to indicate deletion
  1306. // however this should not trigger a delete
  1307. fakeProvider.WithGetAllSecrets(map[string][]byte{}, esv1.NoSecretErr)
  1308. Consistently(func() bool {
  1309. By("checking that secret has not been deleted")
  1310. err := k8sClient.Get(context.Background(), secretLookupKey, sec)
  1311. if err != nil {
  1312. GinkgoLogr.Error(err, "failed getting a secret")
  1313. return false
  1314. }
  1315. if got := sec.Data["foo"]; !bytes.Equal(got, expVal) {
  1316. GinkgoLogr.Info("received an unexpected secret value", "got", got, "expected", expVal)
  1317. return false
  1318. }
  1319. return true
  1320. }, time.Second*10, time.Second).Should(BeTrue())
  1321. }
  1322. }
  1323. deletionPolicyRetainEmptyData := func(tc *testCase) {
  1324. // set initial value
  1325. fakeProvider.WithGetAllSecrets(make(map[string][]byte), nil)
  1326. tc.externalSecret.Spec.Data = make([]esv1.ExternalSecretData, 0)
  1327. tc.externalSecret.Spec.DataFrom = []esv1.ExternalSecretDataFromRemoteRef{
  1328. {
  1329. Find: &esv1.ExternalSecretFind{
  1330. Tags: map[string]string{
  1331. "non-existing-key": "non-existing-value",
  1332. },
  1333. },
  1334. },
  1335. }
  1336. tc.externalSecret.Spec.Target.DeletionPolicy = esv1.DeletionPolicyRetain
  1337. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Second}
  1338. tc.checkCondition = func(es *esv1.ExternalSecret) bool {
  1339. expected := []esv1.ExternalSecretStatusCondition{
  1340. {
  1341. Type: esv1.ExternalSecretReady,
  1342. Status: v1.ConditionTrue,
  1343. Reason: esv1.ConditionReasonSecretSynced,
  1344. Message: msgSyncedRetain,
  1345. },
  1346. }
  1347. opts := cmpopts.IgnoreFields(esv1.ExternalSecretStatusCondition{}, "LastTransitionTime")
  1348. if diff := cmp.Diff(expected, es.Status.Conditions, opts); diff != "" {
  1349. GinkgoLogr.Info("(-got, +want)\n%s", "diff", diff)
  1350. return false
  1351. }
  1352. return true
  1353. }
  1354. }
  1355. // merge with existing secret using creationPolicy=Merge
  1356. // if provider secret gets deleted only the managed field should get deleted
  1357. deletionPolicyMerge := func(tc *testCase) {
  1358. const secretVal = "someValue"
  1359. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Second}
  1360. tc.externalSecret.Spec.Target.CreationPolicy = esv1.CreatePolicyMerge
  1361. tc.externalSecret.Spec.Target.DeletionPolicy = esv1.DeletionPolicyMerge
  1362. // create secret beforehand
  1363. Expect(k8sClient.Create(context.Background(), &v1.Secret{
  1364. ObjectMeta: metav1.ObjectMeta{
  1365. Name: ExternalSecretTargetSecretName,
  1366. Namespace: ExternalSecretNamespace,
  1367. },
  1368. Data: map[string][]byte{
  1369. existingKey: []byte(existingVal),
  1370. },
  1371. }, client.FieldOwner(FakeManager))).To(Succeed())
  1372. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  1373. tc.checkSecret = func(es *esv1.ExternalSecret, secret *v1.Secret) {
  1374. // check value
  1375. Expect(string(secret.Data[existingKey])).To(Equal(existingVal))
  1376. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  1377. sec := &v1.Secret{}
  1378. secretLookupKey := types.NamespacedName{
  1379. Name: ExternalSecretTargetSecretName,
  1380. Namespace: ExternalSecretNamespace,
  1381. }
  1382. // return specific delete err to indicate deletion
  1383. // however this should not trigger a delete
  1384. // instead expect that only the pre-existing value exists
  1385. fakeProvider.WithGetSecret(nil, esv1.NoSecretErr)
  1386. Eventually(func() bool {
  1387. By("checking that secret has not been deleted and pre-existing key exists")
  1388. err := k8sClient.Get(context.Background(), secretLookupKey, sec)
  1389. return !apierrors.IsNotFound(err) &&
  1390. len(sec.Data) == 1 &&
  1391. bytes.Equal(sec.Data[existingKey], []byte(existingVal))
  1392. }, time.Second*30, time.Second).Should(BeTrue())
  1393. }
  1394. }
  1395. // orphan the secret after the external secret has been deleted
  1396. createSecretPolicyOrphan := func(tc *testCase) {
  1397. const secretVal = "someValue"
  1398. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Second}
  1399. tc.externalSecret.Spec.Target.CreationPolicy = esv1.CreatePolicyOrphan
  1400. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  1401. tc.checkSecret = func(es *esv1.ExternalSecret, secret *v1.Secret) {
  1402. // check value
  1403. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  1404. sec := &v1.Secret{}
  1405. secretLookupKey := types.NamespacedName{
  1406. Name: ExternalSecretTargetSecretName,
  1407. Namespace: ExternalSecretNamespace,
  1408. }
  1409. err := k8sClient.Delete(context.Background(), tc.externalSecret)
  1410. Expect(err).ToNot(HaveOccurred())
  1411. Consistently(func() bool {
  1412. By("checking that secret has not been deleted")
  1413. err := k8sClient.Get(context.Background(), secretLookupKey, sec)
  1414. return !apierrors.IsNotFound(err)
  1415. }, time.Second*15, time.Second).Should(BeTrue())
  1416. }
  1417. }
  1418. // with rewrite all keys from a dataFrom operation
  1419. // should be put with new rewriting into the secret
  1420. syncAndRewriteWithDataFrom := func(tc *testCase) {
  1421. tc.externalSecret.Spec.Data = nil
  1422. tc.externalSecret.Spec.DataFrom = []esv1.ExternalSecretDataFromRemoteRef{
  1423. {
  1424. Extract: &esv1.ExternalSecretDataRemoteRef{
  1425. Key: remoteKey,
  1426. },
  1427. Rewrite: []esv1.ExternalSecretRewrite{{
  1428. Regexp: &esv1.ExternalSecretRewriteRegexp{
  1429. Source: "(.*)",
  1430. Target: "new-$1",
  1431. },
  1432. }},
  1433. },
  1434. {
  1435. Extract: &esv1.ExternalSecretDataRemoteRef{
  1436. Key: remoteKey,
  1437. },
  1438. Rewrite: []esv1.ExternalSecretRewrite{{
  1439. Regexp: &esv1.ExternalSecretRewriteRegexp{
  1440. Source: "(.*)",
  1441. Target: "old-$1",
  1442. },
  1443. }},
  1444. },
  1445. }
  1446. fakeProvider.WithGetSecretMap(map[string][]byte{
  1447. "foo": []byte(FooValue),
  1448. "bar": []byte(BarValue),
  1449. }, nil)
  1450. tc.checkSecret = func(es *esv1.ExternalSecret, secret *v1.Secret) {
  1451. // check values
  1452. Expect(string(secret.Data["new-foo"])).To(Equal(FooValue))
  1453. Expect(string(secret.Data["new-bar"])).To(Equal(BarValue))
  1454. Expect(string(secret.Data["old-foo"])).To(Equal(FooValue))
  1455. Expect(string(secret.Data["old-bar"])).To(Equal(BarValue))
  1456. }
  1457. }
  1458. // with rewrite keys from dataFrom
  1459. // should error if keys are not compliant
  1460. invalidExtractKeysErrCondition := func(tc *testCase) {
  1461. tc.externalSecret.Spec.Data = nil
  1462. tc.externalSecret.Spec.DataFrom = []esv1.ExternalSecretDataFromRemoteRef{
  1463. {
  1464. Extract: &esv1.ExternalSecretDataRemoteRef{
  1465. Key: remoteKey,
  1466. },
  1467. Rewrite: []esv1.ExternalSecretRewrite{{
  1468. Regexp: &esv1.ExternalSecretRewriteRegexp{
  1469. Source: "(.*)",
  1470. Target: "$1",
  1471. },
  1472. }},
  1473. },
  1474. }
  1475. fakeProvider.WithGetSecretMap(map[string][]byte{
  1476. "foo/bar": []byte(FooValue),
  1477. "bar/foo": []byte(BarValue),
  1478. }, nil)
  1479. tc.checkCondition = func(es *esv1.ExternalSecret) bool {
  1480. cond := GetExternalSecretCondition(es.Status, esv1.ExternalSecretReady)
  1481. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1.ConditionReasonSecretSyncedError {
  1482. return false
  1483. }
  1484. return true
  1485. }
  1486. tc.checkCondition = func(es *esv1.ExternalSecret) bool {
  1487. cond := GetExternalSecretCondition(es.Status, esv1.ExternalSecretReady)
  1488. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1.ConditionReasonSecretSyncedError {
  1489. return false
  1490. }
  1491. return true
  1492. }
  1493. tc.checkExternalSecret = func(es *esv1.ExternalSecret) {
  1494. Eventually(func() bool {
  1495. Expect(testSyncCallsError.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metric)).To(Succeed())
  1496. Expect(testExternalSecretReconcileDuration.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metricDuration)).To(Succeed())
  1497. return metric.GetCounter().GetValue() >= 2.0 && metricDuration.GetGauge().GetValue() > 0.0
  1498. }, timeout, interval).Should(BeTrue())
  1499. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1.ExternalSecretReady, v1.ConditionFalse, 1.0)).To(BeTrue())
  1500. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1.ExternalSecretReady, v1.ConditionTrue, 0.0)).To(BeTrue())
  1501. }
  1502. }
  1503. // with rewrite keys from dataFrom
  1504. // should error if keys are not compliant
  1505. invalidFindKeysErrCondition := func(tc *testCase) {
  1506. tc.externalSecret.Spec.Data = nil
  1507. tc.externalSecret.Spec.DataFrom = []esv1.ExternalSecretDataFromRemoteRef{
  1508. {
  1509. Find: &esv1.ExternalSecretFind{
  1510. Name: &esv1.FindName{
  1511. RegExp: ".*",
  1512. },
  1513. },
  1514. Rewrite: []esv1.ExternalSecretRewrite{{
  1515. Regexp: &esv1.ExternalSecretRewriteRegexp{
  1516. Source: "(.*)",
  1517. Target: "$1",
  1518. },
  1519. }},
  1520. },
  1521. }
  1522. fakeProvider.WithGetAllSecrets(map[string][]byte{
  1523. "foo/bar": []byte(FooValue),
  1524. "bar/foo": []byte(BarValue),
  1525. }, nil)
  1526. tc.checkCondition = func(es *esv1.ExternalSecret) bool {
  1527. cond := GetExternalSecretCondition(es.Status, esv1.ExternalSecretReady)
  1528. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1.ConditionReasonSecretSyncedError {
  1529. return false
  1530. }
  1531. return true
  1532. }
  1533. tc.checkCondition = func(es *esv1.ExternalSecret) bool {
  1534. cond := GetExternalSecretCondition(es.Status, esv1.ExternalSecretReady)
  1535. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1.ConditionReasonSecretSyncedError {
  1536. return false
  1537. }
  1538. return true
  1539. }
  1540. tc.checkExternalSecret = func(es *esv1.ExternalSecret) {
  1541. Eventually(func() bool {
  1542. Expect(testSyncCallsError.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metric)).To(Succeed())
  1543. Expect(testExternalSecretReconcileDuration.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metricDuration)).To(Succeed())
  1544. return metric.GetCounter().GetValue() >= 2.0 && metricDuration.GetGauge().GetValue() > 0.0
  1545. }, timeout, interval).Should(BeTrue())
  1546. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1.ExternalSecretReady, v1.ConditionFalse, 1.0)).To(BeTrue())
  1547. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1.ExternalSecretReady, v1.ConditionTrue, 0.0)).To(BeTrue())
  1548. }
  1549. }
  1550. // with dataFrom all properties from the specified secret
  1551. // should be put into the secret
  1552. syncWithDataFrom := func(tc *testCase) {
  1553. tc.externalSecret.Spec.Data = nil
  1554. tc.externalSecret.Spec.DataFrom = []esv1.ExternalSecretDataFromRemoteRef{
  1555. {
  1556. Extract: &esv1.ExternalSecretDataRemoteRef{
  1557. Key: remoteKey,
  1558. },
  1559. },
  1560. }
  1561. fakeProvider.WithGetSecretMap(map[string][]byte{
  1562. "foo": []byte(FooValue),
  1563. "bar": []byte(BarValue),
  1564. }, nil)
  1565. tc.checkSecret = func(es *esv1.ExternalSecret, secret *v1.Secret) {
  1566. // check values
  1567. Expect(string(secret.Data["foo"])).To(Equal(FooValue))
  1568. Expect(string(secret.Data["bar"])).To(Equal(BarValue))
  1569. }
  1570. }
  1571. // with dataFrom.Find the change is on the called method GetAllSecrets
  1572. // all keys should be put into the secret
  1573. syncAndRewriteDataFromFind := func(tc *testCase) {
  1574. tc.externalSecret.Spec.Data = nil
  1575. tc.externalSecret.Spec.DataFrom = []esv1.ExternalSecretDataFromRemoteRef{
  1576. {
  1577. Find: &esv1.ExternalSecretFind{
  1578. Name: &esv1.FindName{
  1579. RegExp: "foobar",
  1580. },
  1581. },
  1582. Rewrite: []esv1.ExternalSecretRewrite{
  1583. {
  1584. Regexp: &esv1.ExternalSecretRewriteRegexp{
  1585. Source: "(.*)",
  1586. Target: "new-$1",
  1587. },
  1588. },
  1589. },
  1590. },
  1591. }
  1592. fakeProvider.WithGetAllSecrets(map[string][]byte{
  1593. "foo": []byte(FooValue),
  1594. "bar": []byte(BarValue),
  1595. }, nil)
  1596. tc.checkSecret = func(es *esv1.ExternalSecret, secret *v1.Secret) {
  1597. // check values
  1598. Expect(string(secret.Data["new-foo"])).To(Equal(FooValue))
  1599. Expect(string(secret.Data["new-bar"])).To(Equal(BarValue))
  1600. }
  1601. }
  1602. // with dataFrom.Find the change is on the called method GetAllSecrets
  1603. // all keys should be put into the secret
  1604. syncDataFromFind := func(tc *testCase) {
  1605. tc.externalSecret.Spec.Data = nil
  1606. tc.externalSecret.Spec.DataFrom = []esv1.ExternalSecretDataFromRemoteRef{
  1607. {
  1608. Find: &esv1.ExternalSecretFind{
  1609. Name: &esv1.FindName{
  1610. RegExp: "foobar",
  1611. },
  1612. },
  1613. },
  1614. }
  1615. fakeProvider.WithGetAllSecrets(map[string][]byte{
  1616. "foo": []byte(FooValue),
  1617. "bar": []byte(BarValue),
  1618. }, nil)
  1619. tc.checkSecret = func(es *esv1.ExternalSecret, secret *v1.Secret) {
  1620. // check values
  1621. Expect(string(secret.Data["foo"])).To(Equal(FooValue))
  1622. Expect(string(secret.Data["bar"])).To(Equal(BarValue))
  1623. }
  1624. }
  1625. // with dataFrom and using a template
  1626. // should be put into the secret
  1627. syncWithDataFromTemplate := func(tc *testCase) {
  1628. tc.externalSecret.Spec.Data = nil
  1629. tc.externalSecret.Spec.Target = esv1.ExternalSecretTarget{
  1630. Name: ExternalSecretTargetSecretName,
  1631. Template: &esv1.ExternalSecretTemplate{
  1632. Type: v1.SecretTypeTLS,
  1633. },
  1634. }
  1635. tc.externalSecret.Spec.DataFrom = []esv1.ExternalSecretDataFromRemoteRef{
  1636. {
  1637. Extract: &esv1.ExternalSecretDataRemoteRef{
  1638. Key: remoteKey,
  1639. },
  1640. },
  1641. }
  1642. fakeProvider.WithGetSecretMap(map[string][]byte{
  1643. "tls.crt": []byte(FooValue),
  1644. "tls.key": []byte(BarValue),
  1645. }, nil)
  1646. tc.checkSecret = func(es *esv1.ExternalSecret, secret *v1.Secret) {
  1647. Expect(secret.Type).To(Equal(v1.SecretTypeTLS))
  1648. // check values
  1649. Expect(string(secret.Data["tls.crt"])).To(Equal(FooValue))
  1650. Expect(string(secret.Data["tls.key"])).To(Equal(BarValue))
  1651. }
  1652. }
  1653. // when a provider errors in a GetSecret call
  1654. // a error condition must be set.
  1655. providerErrCondition := func(tc *testCase) {
  1656. const secretVal = "foobar"
  1657. fakeProvider.WithGetSecret(nil, errors.New("boom"))
  1658. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Millisecond * 100}
  1659. tc.checkCondition = func(es *esv1.ExternalSecret) bool {
  1660. cond := GetExternalSecretCondition(es.Status, esv1.ExternalSecretReady)
  1661. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1.ConditionReasonSecretSyncedError {
  1662. return false
  1663. }
  1664. return true
  1665. }
  1666. tc.checkExternalSecret = func(es *esv1.ExternalSecret) {
  1667. Eventually(func() bool {
  1668. Expect(testSyncCallsError.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metric)).To(Succeed())
  1669. Expect(testExternalSecretReconcileDuration.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metricDuration)).To(Succeed())
  1670. return metric.GetCounter().GetValue() >= 2.0 && metricDuration.GetGauge().GetValue() > 0.0
  1671. }, timeout, interval).Should(BeTrue())
  1672. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1.ExternalSecretReady, v1.ConditionFalse, 1.0)).To(BeTrue())
  1673. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1.ExternalSecretReady, v1.ConditionTrue, 0.0)).To(BeTrue())
  1674. // es condition should reflect recovered provider error
  1675. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  1676. esKey := types.NamespacedName{Name: ExternalSecretName, Namespace: ExternalSecretNamespace}
  1677. Eventually(func() bool {
  1678. err := k8sClient.Get(context.Background(), esKey, es)
  1679. if err != nil {
  1680. return false
  1681. }
  1682. // condition must now be true!
  1683. cond := GetExternalSecretCondition(es.Status, esv1.ExternalSecretReady)
  1684. if cond == nil && cond.Status != v1.ConditionTrue {
  1685. return false
  1686. }
  1687. return true
  1688. }, timeout, interval).Should(BeTrue())
  1689. }
  1690. }
  1691. // When a ExternalSecret references an non-existing SecretStore
  1692. // a error condition must be set.
  1693. storeMissingErrCondition := func(tc *testCase) {
  1694. tc.externalSecret.Spec.SecretStoreRef.Name = "nonexistent"
  1695. tc.checkCondition = func(es *esv1.ExternalSecret) bool {
  1696. cond := GetExternalSecretCondition(es.Status, esv1.ExternalSecretReady)
  1697. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1.ConditionReasonSecretSyncedError {
  1698. return false
  1699. }
  1700. return true
  1701. }
  1702. tc.checkExternalSecret = func(es *esv1.ExternalSecret) {
  1703. Eventually(func() bool {
  1704. Expect(testSyncCallsError.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metric)).To(Succeed())
  1705. Expect(testExternalSecretReconcileDuration.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metricDuration)).To(Succeed())
  1706. return metric.GetCounter().GetValue() >= 2.0 && metricDuration.GetGauge().GetValue() > 0.0
  1707. }, timeout, interval).Should(BeTrue())
  1708. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1.ExternalSecretReady, v1.ConditionFalse, 1.0)).To(BeTrue())
  1709. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1.ExternalSecretReady, v1.ConditionTrue, 0.0)).To(BeTrue())
  1710. }
  1711. }
  1712. // when the provider constructor errors (e.g. invalid configuration)
  1713. // a SecretSyncedError status condition must be set
  1714. storeConstructErrCondition := func(tc *testCase) {
  1715. fakeProvider.WithNew(func(context.Context, esv1.GenericStore, client.Client,
  1716. string) (esv1.SecretsClient, error) {
  1717. return nil, errors.New("artificial constructor error")
  1718. })
  1719. tc.checkCondition = func(es *esv1.ExternalSecret) bool {
  1720. // condition must be false
  1721. cond := GetExternalSecretCondition(es.Status, esv1.ExternalSecretReady)
  1722. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1.ConditionReasonSecretSyncedError {
  1723. return false
  1724. }
  1725. return true
  1726. }
  1727. tc.checkExternalSecret = func(es *esv1.ExternalSecret) {
  1728. Eventually(func() bool {
  1729. Expect(testSyncCallsError.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metric)).To(Succeed())
  1730. Expect(testExternalSecretReconcileDuration.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metricDuration)).To(Succeed())
  1731. return metric.GetCounter().GetValue() >= 2.0 && metricDuration.GetGauge().GetValue() > 0.0
  1732. }, timeout, interval).Should(BeTrue())
  1733. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1.ExternalSecretReady, v1.ConditionFalse, 1.0)).To(BeTrue())
  1734. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1.ExternalSecretReady, v1.ConditionTrue, 0.0)).To(BeTrue())
  1735. }
  1736. }
  1737. // when a SecretStore has a controller field set which we don't care about
  1738. // the externalSecret must not be touched
  1739. ignoreMismatchController := func(tc *testCase) {
  1740. tc.secretStore.GetSpec().Controller = "nop"
  1741. tc.checkCondition = func(es *esv1.ExternalSecret) bool {
  1742. cond := GetExternalSecretCondition(es.Status, esv1.ExternalSecretReady)
  1743. return cond == nil
  1744. }
  1745. tc.checkExternalSecret = func(es *esv1.ExternalSecret) {
  1746. // Condition True and False should be 0, since the Condition was not created
  1747. Eventually(func() float64 {
  1748. Expect(testExternalSecretCondition.WithLabelValues(ExternalSecretName, ExternalSecretNamespace, string(esv1.ExternalSecretReady), string(v1.ConditionTrue)).Write(&metric)).To(Succeed())
  1749. return metric.GetGauge().GetValue()
  1750. }, timeout, interval).Should(Equal(0.0))
  1751. Eventually(func() float64 {
  1752. Expect(testExternalSecretCondition.WithLabelValues(ExternalSecretName, ExternalSecretNamespace, string(esv1.ExternalSecretReady), string(v1.ConditionFalse)).Write(&metric)).To(Succeed())
  1753. return metric.GetGauge().GetValue()
  1754. }, timeout, interval).Should(Equal(0.0))
  1755. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1.ExternalSecretReady, v1.ConditionFalse, 0.0)).To(BeTrue())
  1756. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1.ExternalSecretReady, v1.ConditionTrue, 0.0)).To(BeTrue())
  1757. }
  1758. }
  1759. ignoreClusterSecretStoreWhenDisabled := func(tc *testCase) {
  1760. tc.externalSecret.Spec.SecretStoreRef.Kind = esv1.ClusterSecretStoreKind
  1761. Expect(shouldSkipClusterSecretStore(
  1762. &Reconciler{
  1763. ClusterSecretStoreEnabled: false,
  1764. },
  1765. tc.externalSecret,
  1766. )).To(BeTrue())
  1767. tc.checkCondition = func(es *esv1.ExternalSecret) bool {
  1768. cond := GetExternalSecretCondition(es.Status, esv1.ExternalSecretReady)
  1769. return cond == nil
  1770. }
  1771. }
  1772. // When the ownership is set to owner, and we delete a dependent child kind=secret
  1773. // it should be recreated without waiting for refresh interval
  1774. checkDeletion := func(tc *testCase) {
  1775. const secretVal = "someValue"
  1776. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  1777. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Minute * 10}
  1778. tc.checkSecret = func(es *esv1.ExternalSecret, secret *v1.Secret) {
  1779. // check values
  1780. oldUID := secret.UID
  1781. Expect(oldUID).NotTo(BeEmpty())
  1782. // delete the related config
  1783. Expect(k8sClient.Delete(context.TODO(), secret))
  1784. var newSecret v1.Secret
  1785. secretLookupKey := types.NamespacedName{
  1786. Name: ExternalSecretTargetSecretName,
  1787. Namespace: ExternalSecretNamespace,
  1788. }
  1789. Eventually(func() bool {
  1790. err := k8sClient.Get(context.Background(), secretLookupKey, &newSecret)
  1791. if err != nil {
  1792. return false
  1793. }
  1794. // new secret should be a new, recreated object with a different UID
  1795. return newSecret.UID != oldUID
  1796. }, timeout, interval).Should(BeTrue())
  1797. }
  1798. }
  1799. // Checks that secret annotation has been written based on the data
  1800. checkSecretDataHashAnnotation := func(tc *testCase) {
  1801. const secretVal = "someValue"
  1802. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  1803. tc.checkSecret = func(es *esv1.ExternalSecret, secret *v1.Secret) {
  1804. expectedHash := utils.ObjectHash(map[string][]byte{
  1805. targetProp: []byte(secretVal),
  1806. })
  1807. Expect(secret.Annotations[esv1.AnnotationDataHash]).To(Equal(expectedHash))
  1808. }
  1809. }
  1810. // Checks that secret annotation has been written based on the all the data for merge keys
  1811. checkMergeSecretDataHashAnnotation := func(tc *testCase) {
  1812. const secretVal = "someValue"
  1813. tc.externalSecret.Spec.Target.CreationPolicy = esv1.CreatePolicyMerge
  1814. // create secret beforehand
  1815. Expect(k8sClient.Create(context.Background(), &v1.Secret{
  1816. ObjectMeta: metav1.ObjectMeta{
  1817. Name: ExternalSecretTargetSecretName,
  1818. Namespace: ExternalSecretNamespace,
  1819. },
  1820. Data: map[string][]byte{
  1821. existingKey: []byte(existingVal),
  1822. },
  1823. }, client.FieldOwner(FakeManager))).To(Succeed())
  1824. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  1825. tc.checkSecret = func(es *esv1.ExternalSecret, secret *v1.Secret) {
  1826. expectedHash := utils.ObjectHash(map[string][]byte{
  1827. existingKey: []byte(existingVal),
  1828. targetProp: []byte(secretVal),
  1829. })
  1830. Expect(secret.Annotations[esv1.AnnotationDataHash]).To(Equal(expectedHash))
  1831. }
  1832. }
  1833. // When we amend the created kind=secret, refresh operation should be run again regardless of refresh interval
  1834. checkSecretDataHashAnnotationChange := func(tc *testCase) {
  1835. fakeData := map[string][]byte{
  1836. "targetProperty": []byte(FooValue),
  1837. }
  1838. fakeProvider.WithGetSecretMap(fakeData, nil)
  1839. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Minute * 10}
  1840. tc.checkSecret = func(es *esv1.ExternalSecret, secret *v1.Secret) {
  1841. oldHash := secret.Annotations[esv1.AnnotationDataHash]
  1842. oldResourceVersion := secret.ResourceVersion
  1843. Expect(oldHash).NotTo(BeEmpty())
  1844. cleanSecret := secret.DeepCopy()
  1845. secret.Data["new"] = []byte("value")
  1846. secret.ObjectMeta.Annotations[esv1.AnnotationDataHash] = "thisiswronghash"
  1847. Expect(k8sClient.Patch(context.Background(), secret, client.MergeFrom(cleanSecret))).To(Succeed())
  1848. var refreshedSecret v1.Secret
  1849. secretLookupKey := types.NamespacedName{
  1850. Name: ExternalSecretTargetSecretName,
  1851. Namespace: ExternalSecretNamespace,
  1852. }
  1853. Eventually(func() bool {
  1854. err := k8sClient.Get(context.Background(), secretLookupKey, &refreshedSecret)
  1855. if err != nil {
  1856. return false
  1857. }
  1858. // refreshed secret should have a different generation (sign that it was updated), but since
  1859. // the secret source is the same (not changed), the hash should be reverted to an old value
  1860. return refreshedSecret.ResourceVersion != oldResourceVersion && refreshedSecret.Annotations[esv1.AnnotationDataHash] == oldHash
  1861. }, timeout, interval).Should(BeTrue())
  1862. }
  1863. }
  1864. // When we update the template, remaining keys should not be preserved
  1865. templateShouldRewrite := func(tc *testCase) {
  1866. const secretVal = "someValue"
  1867. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  1868. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Minute * 10}
  1869. tc.externalSecret.Spec.Target.Template = &esv1.ExternalSecretTemplate{
  1870. Data: map[string]string{
  1871. "key": `{{.targetProperty}}-foo`,
  1872. },
  1873. }
  1874. tc.checkSecret = func(es *esv1.ExternalSecret, secret *v1.Secret) {
  1875. Expect(secret.Data["key"]).To(Equal([]byte("someValue-foo")))
  1876. newEs := es.DeepCopy()
  1877. newEs.Spec.Target.Template.Data = map[string]string{
  1878. "new": "foo",
  1879. }
  1880. Expect(k8sClient.Patch(context.Background(), newEs, client.MergeFrom(es))).To(Succeed())
  1881. var refreshedSecret v1.Secret
  1882. secretLookupKey := types.NamespacedName{
  1883. Name: ExternalSecretTargetSecretName,
  1884. Namespace: ExternalSecretNamespace,
  1885. }
  1886. Eventually(func() bool {
  1887. err := k8sClient.Get(context.Background(), secretLookupKey, &refreshedSecret)
  1888. if err != nil {
  1889. return false
  1890. }
  1891. _, ok := refreshedSecret.Data["key"]
  1892. return !ok && bytes.Equal(refreshedSecret.Data["new"], []byte("foo"))
  1893. }, timeout, interval).Should(BeTrue())
  1894. }
  1895. }
  1896. // When we update the template, remaining keys should not be preserved
  1897. templateShouldMerge := func(tc *testCase) {
  1898. const secretVal = "someValue"
  1899. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  1900. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Minute * 10}
  1901. tc.externalSecret.Spec.Target.Template = &esv1.ExternalSecretTemplate{
  1902. MergePolicy: esv1.MergePolicyMerge,
  1903. Data: map[string]string{
  1904. "key": `{{.targetProperty}}-foo`,
  1905. },
  1906. }
  1907. tc.checkSecret = func(es *esv1.ExternalSecret, secret *v1.Secret) {
  1908. Expect(secret.Data["key"]).To(Equal([]byte("someValue-foo")))
  1909. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  1910. }
  1911. }
  1912. useClusterSecretStore := func(tc *testCase) {
  1913. tc.secretStore = &esv1.ClusterSecretStore{
  1914. ObjectMeta: metav1.ObjectMeta{
  1915. Name: ExternalSecretStore,
  1916. },
  1917. Spec: esv1.SecretStoreSpec{
  1918. Provider: &esv1.SecretStoreProvider{
  1919. AWS: &esv1.AWSProvider{
  1920. Service: esv1.AWSServiceSecretsManager,
  1921. },
  1922. },
  1923. },
  1924. }
  1925. tc.externalSecret.Spec.SecretStoreRef.Kind = esv1.ClusterSecretStoreKind
  1926. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  1927. }
  1928. // Secret is created when ClusterSecretStore has no conditions
  1929. noConditionsSecretCreated := func(tc *testCase) {
  1930. tc.checkSecret = func(es *esv1.ExternalSecret, secret *v1.Secret) {
  1931. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  1932. }
  1933. }
  1934. // Secret is not created when ClusterSecretStore has a single non-matching string condition
  1935. noSecretCreatedWhenNamespaceDoesntMatchStringCondition := func(tc *testCase) {
  1936. tc.secretStore.GetSpec().Conditions = []esv1.ClusterSecretStoreCondition{
  1937. {
  1938. Namespaces: []string{"some-other-ns"},
  1939. },
  1940. }
  1941. tc.checkCondition = func(es *esv1.ExternalSecret) bool {
  1942. cond := GetExternalSecretCondition(es.Status, esv1.ExternalSecretReady)
  1943. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1.ConditionReasonSecretSyncedError {
  1944. return false
  1945. }
  1946. return true
  1947. }
  1948. }
  1949. // Secret is not created when ClusterSecretStore has a single non-matching string condition with multiple names
  1950. noSecretCreatedWhenNamespaceDoesntMatchStringConditionWithMultipleNames := func(tc *testCase) {
  1951. tc.secretStore.GetSpec().Conditions = []esv1.ClusterSecretStoreCondition{
  1952. {
  1953. Namespaces: []string{"some-other-ns", "another-ns"},
  1954. },
  1955. }
  1956. tc.checkCondition = func(es *esv1.ExternalSecret) bool {
  1957. cond := GetExternalSecretCondition(es.Status, esv1.ExternalSecretReady)
  1958. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1.ConditionReasonSecretSyncedError {
  1959. return false
  1960. }
  1961. return true
  1962. }
  1963. }
  1964. // Secret is not created when ClusterSecretStore has a multiple non-matching string condition
  1965. noSecretCreatedWhenNamespaceDoesntMatchMultipleStringCondition := func(tc *testCase) {
  1966. tc.secretStore.GetSpec().Conditions = []esv1.ClusterSecretStoreCondition{
  1967. {
  1968. Namespaces: []string{"some-other-ns"},
  1969. },
  1970. {
  1971. Namespaces: []string{"another-ns"},
  1972. },
  1973. }
  1974. tc.checkCondition = func(es *esv1.ExternalSecret) bool {
  1975. cond := GetExternalSecretCondition(es.Status, esv1.ExternalSecretReady)
  1976. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1.ConditionReasonSecretSyncedError {
  1977. return false
  1978. }
  1979. return true
  1980. }
  1981. }
  1982. // Secret is created when ClusterSecretStore has a single matching string condition
  1983. secretCreatedWhenNamespaceMatchesSingleStringCondition := func(tc *testCase) {
  1984. tc.secretStore.GetSpec().Conditions = []esv1.ClusterSecretStoreCondition{
  1985. {
  1986. Namespaces: []string{ExternalSecretNamespace},
  1987. },
  1988. }
  1989. tc.checkSecret = func(es *esv1.ExternalSecret, secret *v1.Secret) {
  1990. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  1991. }
  1992. }
  1993. // Secret is created when ClusterSecretStore has a multiple string conditions, one matching
  1994. secretCreatedWhenNamespaceMatchesMultipleStringConditions := func(tc *testCase) {
  1995. tc.secretStore.GetSpec().Conditions = []esv1.ClusterSecretStoreCondition{
  1996. {
  1997. Namespaces: []string{ExternalSecretNamespace, "some-other-ns"},
  1998. },
  1999. }
  2000. tc.checkSecret = func(es *esv1.ExternalSecret, secret *v1.Secret) {
  2001. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  2002. }
  2003. }
  2004. // Secret is not created when ClusterSecretStore has a single non-matching label condition
  2005. noSecretCreatedWhenNamespaceDoesntMatchLabelCondition := func(tc *testCase) {
  2006. tc.secretStore.GetSpec().Conditions = []esv1.ClusterSecretStoreCondition{
  2007. {
  2008. NamespaceSelector: &metav1.LabelSelector{MatchLabels: map[string]string{"some-label-key": "some-label-value"}},
  2009. },
  2010. }
  2011. tc.checkCondition = func(es *esv1.ExternalSecret) bool {
  2012. cond := GetExternalSecretCondition(es.Status, esv1.ExternalSecretReady)
  2013. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1.ConditionReasonSecretSyncedError {
  2014. return false
  2015. }
  2016. return true
  2017. }
  2018. }
  2019. // Secret is created when ClusterSecretStore has a single matching label condition
  2020. secretCreatedWhenNamespaceMatchOnlyLabelCondition := func(tc *testCase) {
  2021. tc.secretStore.GetSpec().Conditions = []esv1.ClusterSecretStoreCondition{
  2022. {
  2023. NamespaceSelector: &metav1.LabelSelector{MatchLabels: map[string]string{NamespaceLabelKey: NamespaceLabelValue}},
  2024. },
  2025. }
  2026. tc.checkSecret = func(es *esv1.ExternalSecret, secret *v1.Secret) {
  2027. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  2028. }
  2029. }
  2030. // Secret is not created when ClusterSecretStore has a partially matching label condition
  2031. noSecretCreatedWhenNamespacePartiallyMatchLabelCondition := func(tc *testCase) {
  2032. tc.secretStore.GetSpec().Conditions = []esv1.ClusterSecretStoreCondition{
  2033. {
  2034. NamespaceSelector: &metav1.LabelSelector{MatchLabels: map[string]string{NamespaceLabelKey: NamespaceLabelValue, "some-label-key": "some-label-value"}},
  2035. },
  2036. }
  2037. tc.checkCondition = func(es *esv1.ExternalSecret) bool {
  2038. cond := GetExternalSecretCondition(es.Status, esv1.ExternalSecretReady)
  2039. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1.ConditionReasonSecretSyncedError {
  2040. return false
  2041. }
  2042. return true
  2043. }
  2044. }
  2045. // Secret is created when ClusterSecretStore has at least one matching label condition
  2046. secretCreatedWhenNamespaceMatchOneLabelCondition := func(tc *testCase) {
  2047. tc.secretStore.GetSpec().Conditions = []esv1.ClusterSecretStoreCondition{
  2048. {
  2049. NamespaceSelector: &metav1.LabelSelector{MatchLabels: map[string]string{NamespaceLabelKey: NamespaceLabelValue}},
  2050. },
  2051. {
  2052. NamespaceSelector: &metav1.LabelSelector{MatchLabels: map[string]string{"some-label-key": "some-label-value"}},
  2053. },
  2054. }
  2055. tc.checkSecret = func(es *esv1.ExternalSecret, secret *v1.Secret) {
  2056. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  2057. }
  2058. }
  2059. // Secret is created when ClusterSecretStore has multiple matching conditions
  2060. secretCreatedWhenNamespaceMatchMultipleConditions := func(tc *testCase) {
  2061. tc.secretStore.GetSpec().Conditions = []esv1.ClusterSecretStoreCondition{
  2062. {
  2063. NamespaceSelector: &metav1.LabelSelector{MatchLabels: map[string]string{NamespaceLabelKey: NamespaceLabelValue}},
  2064. },
  2065. {
  2066. Namespaces: []string{ExternalSecretNamespace},
  2067. },
  2068. }
  2069. tc.checkSecret = func(es *esv1.ExternalSecret, secret *v1.Secret) {
  2070. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  2071. }
  2072. }
  2073. // Secret is not created when ClusterSecretStore has multiple non-matching conditions
  2074. noSecretCreatedWhenNamespaceMatchMultipleNonMatchingConditions := func(tc *testCase) {
  2075. tc.secretStore.GetSpec().Conditions = []esv1.ClusterSecretStoreCondition{
  2076. {
  2077. NamespaceSelector: &metav1.LabelSelector{MatchLabels: map[string]string{"some-label-key": "some-label-value"}},
  2078. },
  2079. {
  2080. Namespaces: []string{"some-other-ns"},
  2081. },
  2082. }
  2083. tc.checkCondition = func(es *esv1.ExternalSecret) bool {
  2084. cond := GetExternalSecretCondition(es.Status, esv1.ExternalSecretReady)
  2085. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1.ConditionReasonSecretSyncedError {
  2086. return false
  2087. }
  2088. return true
  2089. }
  2090. }
  2091. DescribeTable("When reconciling an ExternalSecret",
  2092. func(tweaks ...testTweaks) {
  2093. tc := makeDefaultTestcase()
  2094. for _, tweak := range tweaks {
  2095. tweak(tc)
  2096. }
  2097. ctx := context.Background()
  2098. By("creating a secret store and external secret")
  2099. Expect(k8sClient.Create(ctx, tc.secretStore)).To(Succeed())
  2100. Expect(k8sClient.Create(ctx, tc.externalSecret)).Should(Succeed())
  2101. esKey := types.NamespacedName{Name: ExternalSecretName, Namespace: ExternalSecretNamespace}
  2102. createdES := &esv1.ExternalSecret{}
  2103. By("checking the es condition")
  2104. Eventually(func() bool {
  2105. err := k8sClient.Get(ctx, esKey, createdES)
  2106. if err != nil {
  2107. return false
  2108. }
  2109. return tc.checkCondition(createdES)
  2110. }, timeout, interval).Should(BeTrue())
  2111. tc.checkExternalSecret(createdES)
  2112. // this must be optional so we can test faulty es configuration
  2113. if tc.checkSecret != nil {
  2114. syncedSecret := &v1.Secret{}
  2115. secretLookupKey := types.NamespacedName{
  2116. Name: tc.targetSecretName,
  2117. Namespace: ExternalSecretNamespace,
  2118. }
  2119. if createdES.Spec.Target.Name == "" {
  2120. secretLookupKey = types.NamespacedName{
  2121. Name: ExternalSecretName,
  2122. Namespace: ExternalSecretNamespace,
  2123. }
  2124. }
  2125. Eventually(func() bool {
  2126. err := k8sClient.Get(ctx, secretLookupKey, syncedSecret)
  2127. return err == nil
  2128. }, timeout, interval).Should(BeTrue())
  2129. tc.checkSecret(createdES, syncedSecret)
  2130. }
  2131. },
  2132. Entry("should recreate deleted secret", checkDeletion),
  2133. Entry("should create proper hash annotation for the external secret", checkSecretDataHashAnnotation),
  2134. Entry("should create proper hash annotation for the external secret with creationPolicy=Merge", checkMergeSecretDataHashAnnotation),
  2135. Entry("es deletes orphaned secrets", deleteOrphanedSecrets),
  2136. Entry("should refresh when the hash annotation doesn't correspond to secret data", checkSecretDataHashAnnotationChange),
  2137. Entry("should use external secret name if target secret name isn't defined", syncWithoutTargetName),
  2138. Entry("should sync to target secrets with naming bigger than 63 characters", syncBigNames),
  2139. Entry("should expose the secret as a provisioned service binding secret", syncBindingSecret),
  2140. Entry("should not expose a provisioned service when no secret is synced", skipBindingSecret),
  2141. Entry("should set labels and annotations from the ExternalSecret", syncLabelsAnnotations),
  2142. Entry("should merge labels and annotations to the ones owned by other entity", mergeLabelsAnnotations),
  2143. Entry("should removed outdated labels and annotations", removeOutdatedLabelsAnnotations),
  2144. Entry("should set prometheus counters", checkPrometheusCounters),
  2145. Entry("should merge with existing secret using creationPolicy=Merge", mergeWithSecret),
  2146. Entry("should kick reconciliation when secret changes using creationPolicy=Merge", mergeWithSecretUpdate),
  2147. Entry("should error if secret doesn't exist when using creationPolicy=Merge", mergeWithSecretErr),
  2148. Entry("should not resolve conflicts with creationPolicy=Merge", mergeWithConflict),
  2149. Entry("should not update unchanged secret using creationPolicy=Merge", mergeWithSecretNoChange),
  2150. Entry("should not delete pre-existing secret with creationPolicy=Orphan", createSecretPolicyOrphan),
  2151. Entry("should sync cluster generator ref", syncWithClusterGeneratorRef),
  2152. Entry("should sync with generatorRef", syncWithGeneratorRef),
  2153. Entry("should not process generatorRef with mismatching controller field", ignoreMismatchControllerForGeneratorRef),
  2154. Entry("should sync with multiple secret stores via sourceRef", syncWithMultipleSecretStores),
  2155. Entry("should sync with template", syncWithTemplate),
  2156. Entry("should sync with template engine v2", syncWithTemplateV2),
  2157. Entry("should sync template with correct value precedence", syncWithTemplatePrecedence),
  2158. Entry("should sync template from keys and values", syncTemplateFromKeysAndValues),
  2159. Entry("should sync template from literal", syncTemplateFromLiteral),
  2160. Entry("should update template if ExternalSecret is updated", templateShouldRewrite),
  2161. Entry("should keep data with templates if MergePolicy=Merge", templateShouldMerge),
  2162. Entry("should refresh secret from template", refreshWithTemplate),
  2163. Entry("should be able to use only metadata from template", onlyMetadataFromTemplate),
  2164. Entry("should refresh secret value when provider secret changes", refreshSecretValue),
  2165. Entry("should refresh secret map when provider secret changes", refreshSecretValueMap),
  2166. Entry("should refresh secret map when provider secret changes when using a template", refreshSecretValueMapTemplate),
  2167. Entry("should not refresh secret value when provider secret changes but refreshInterval is zero", refreshintervalZero),
  2168. Entry("should fetch secret using dataFrom", syncWithDataFrom),
  2169. Entry("should rewrite secret using dataFrom", syncAndRewriteWithDataFrom),
  2170. Entry("should not automatically convert from extract if rewrite is used", invalidExtractKeysErrCondition),
  2171. Entry("should fetch secret using dataFrom.find", syncDataFromFind),
  2172. Entry("should rewrite secret using dataFrom.find", syncAndRewriteDataFromFind),
  2173. Entry("should not automatically convert from find if rewrite is used", invalidFindKeysErrCondition),
  2174. Entry("should fetch secret using dataFrom and a template", syncWithDataFromTemplate),
  2175. Entry("should set error condition when provider errors", providerErrCondition),
  2176. Entry("should set an error condition when store does not exist", storeMissingErrCondition),
  2177. Entry("should set an error condition when store provider constructor fails", storeConstructErrCondition),
  2178. Entry("should not process store with mismatching controller field", ignoreMismatchController),
  2179. Entry("should not process cluster secret store when it is disabled", ignoreClusterSecretStoreWhenDisabled),
  2180. Entry("should eventually delete target secret with deletionPolicy=Delete", deletionPolicyDelete),
  2181. Entry("should not delete target secret with deletionPolicy=Retain", deletionPolicyRetain),
  2182. Entry("should update the status properly even if the deletionPolicy is Retain and the data is empty", deletionPolicyRetainEmptyData),
  2183. Entry("should not delete pre-existing secret with deletionPolicy=Merge", deletionPolicyMerge),
  2184. Entry("secret is created when there are no conditions for the cluster secret store", useClusterSecretStore, noConditionsSecretCreated),
  2185. Entry("secret is not created when the condition for the cluster secret store states a different namespace single string condition", useClusterSecretStore, noSecretCreatedWhenNamespaceDoesntMatchStringCondition),
  2186. Entry("secret is not created when the condition for the cluster secret store states a different namespace single string condition with multiple names", useClusterSecretStore, noSecretCreatedWhenNamespaceDoesntMatchStringConditionWithMultipleNames),
  2187. Entry("secret is not created when the condition for the cluster secret store states a different namespace multiple string conditions", useClusterSecretStore, noSecretCreatedWhenNamespaceDoesntMatchMultipleStringCondition),
  2188. Entry("secret is created when the condition for the cluster secret store has only one matching namespace by string condition", useClusterSecretStore, secretCreatedWhenNamespaceMatchesSingleStringCondition),
  2189. Entry("secret is created when the condition for the cluster secret store has one matching namespace of multiple namespaces by string condition", useClusterSecretStore, secretCreatedWhenNamespaceMatchesMultipleStringConditions),
  2190. Entry("secret is not created when the condition for the cluster secret store states a non-matching label condition", useClusterSecretStore, noSecretCreatedWhenNamespaceDoesntMatchLabelCondition),
  2191. Entry("secret is created when the condition for the cluster secret store states a single matching label condition", useClusterSecretStore, secretCreatedWhenNamespaceMatchOnlyLabelCondition),
  2192. Entry("secret is not created when the condition for the cluster secret store states a partially-matching label condition", useClusterSecretStore, noSecretCreatedWhenNamespacePartiallyMatchLabelCondition),
  2193. Entry("secret is created when one of the label conditions for the cluster secret store matches", useClusterSecretStore, secretCreatedWhenNamespaceMatchOneLabelCondition),
  2194. Entry("secret is created when the namespaces matches multiple cluster secret store conditions", useClusterSecretStore, secretCreatedWhenNamespaceMatchMultipleConditions),
  2195. Entry("secret is not created when the namespaces doesn't match any of multiple cluster secret store conditions", useClusterSecretStore, noSecretCreatedWhenNamespaceMatchMultipleNonMatchingConditions),
  2196. )
  2197. })
  2198. var _ = Describe("ExternalSecret refresh logic", func() {
  2199. Context("secret refresh", func() {
  2200. It("should refresh when resource version does not match", func() {
  2201. Expect(shouldRefresh(&esv1.ExternalSecret{
  2202. Spec: esv1.ExternalSecretSpec{
  2203. RefreshInterval: &metav1.Duration{Duration: time.Minute},
  2204. },
  2205. Status: esv1.ExternalSecretStatus{
  2206. SyncedResourceVersion: "some resource version",
  2207. },
  2208. })).To(BeTrue())
  2209. })
  2210. It("should refresh when labels change", func() {
  2211. es := &esv1.ExternalSecret{
  2212. ObjectMeta: metav1.ObjectMeta{
  2213. Generation: 1,
  2214. Labels: map[string]string{
  2215. "foo": "bar",
  2216. },
  2217. },
  2218. Spec: esv1.ExternalSecretSpec{
  2219. RefreshInterval: &metav1.Duration{Duration: time.Minute},
  2220. },
  2221. Status: esv1.ExternalSecretStatus{
  2222. RefreshTime: metav1.Now(),
  2223. },
  2224. }
  2225. es.Status.SyncedResourceVersion = util.GetResourceVersion(es.ObjectMeta)
  2226. // this should not refresh, rv matches object
  2227. Expect(shouldRefresh(es)).To(BeFalse())
  2228. // change labels without changing the syncedResourceVersion and expect refresh
  2229. es.ObjectMeta.Labels["new"] = "w00t"
  2230. Expect(shouldRefresh(es)).To(BeTrue())
  2231. })
  2232. It("should refresh when annotations change", func() {
  2233. es := &esv1.ExternalSecret{
  2234. ObjectMeta: metav1.ObjectMeta{
  2235. Generation: 1,
  2236. Annotations: map[string]string{
  2237. "foo": "bar",
  2238. },
  2239. },
  2240. Spec: esv1.ExternalSecretSpec{
  2241. RefreshInterval: &metav1.Duration{Duration: time.Minute},
  2242. },
  2243. Status: esv1.ExternalSecretStatus{
  2244. RefreshTime: metav1.Now(),
  2245. },
  2246. }
  2247. es.Status.SyncedResourceVersion = util.GetResourceVersion(es.ObjectMeta)
  2248. // this should not refresh, rv matches object
  2249. Expect(shouldRefresh(es)).To(BeFalse())
  2250. // change annotations without changing the syncedResourceVersion and expect refresh
  2251. es.ObjectMeta.Annotations["new"] = "w00t"
  2252. Expect(shouldRefresh(es)).To(BeTrue())
  2253. })
  2254. It("should refresh when generation has changed", func() {
  2255. es := &esv1.ExternalSecret{
  2256. ObjectMeta: metav1.ObjectMeta{
  2257. Generation: 1,
  2258. },
  2259. Spec: esv1.ExternalSecretSpec{
  2260. RefreshInterval: &metav1.Duration{Duration: time.Minute},
  2261. },
  2262. Status: esv1.ExternalSecretStatus{
  2263. RefreshTime: metav1.Now(),
  2264. },
  2265. }
  2266. es.Status.SyncedResourceVersion = util.GetResourceVersion(es.ObjectMeta)
  2267. Expect(shouldRefresh(es)).To(BeFalse())
  2268. // update gen -> refresh
  2269. es.ObjectMeta.Generation = 2
  2270. Expect(shouldRefresh(es)).To(BeTrue())
  2271. })
  2272. It("should skip refresh when refreshInterval is 0", func() {
  2273. es := &esv1.ExternalSecret{
  2274. ObjectMeta: metav1.ObjectMeta{
  2275. Generation: 1,
  2276. },
  2277. Spec: esv1.ExternalSecretSpec{
  2278. RefreshInterval: &metav1.Duration{Duration: 0},
  2279. },
  2280. Status: esv1.ExternalSecretStatus{},
  2281. }
  2282. // resource version matches
  2283. es.Status.SyncedResourceVersion = util.GetResourceVersion(es.ObjectMeta)
  2284. Expect(shouldRefresh(es)).To(BeFalse())
  2285. })
  2286. It("should refresh when refresh interval has passed", func() {
  2287. es := &esv1.ExternalSecret{
  2288. ObjectMeta: metav1.ObjectMeta{
  2289. Generation: 1,
  2290. },
  2291. Spec: esv1.ExternalSecretSpec{
  2292. RefreshInterval: &metav1.Duration{Duration: time.Second},
  2293. },
  2294. Status: esv1.ExternalSecretStatus{
  2295. RefreshTime: metav1.NewTime(metav1.Now().Add(-time.Second * 5)),
  2296. },
  2297. }
  2298. // resource version matches
  2299. es.Status.SyncedResourceVersion = util.GetResourceVersion(es.ObjectMeta)
  2300. Expect(shouldRefresh(es)).To(BeTrue())
  2301. })
  2302. It("should refresh when no refresh time was set", func() {
  2303. es := &esv1.ExternalSecret{
  2304. ObjectMeta: metav1.ObjectMeta{
  2305. Generation: 1,
  2306. },
  2307. Spec: esv1.ExternalSecretSpec{
  2308. RefreshInterval: &metav1.Duration{Duration: time.Second},
  2309. },
  2310. Status: esv1.ExternalSecretStatus{},
  2311. }
  2312. // resource version matches
  2313. es.Status.SyncedResourceVersion = util.GetResourceVersion(es.ObjectMeta)
  2314. Expect(shouldRefresh(es)).To(BeTrue())
  2315. })
  2316. })
  2317. Context("objectmeta hash", func() {
  2318. It("should produce different hashes for different k/v pairs", func() {
  2319. h1 := util.HashMeta(metav1.ObjectMeta{
  2320. Generation: 1,
  2321. Annotations: map[string]string{
  2322. "foo": "bar",
  2323. },
  2324. })
  2325. h2 := util.HashMeta(metav1.ObjectMeta{
  2326. Generation: 1,
  2327. Annotations: map[string]string{
  2328. "foo": "bing",
  2329. },
  2330. })
  2331. Expect(h1).ToNot(Equal(h2))
  2332. })
  2333. It("should produce different hashes for different generations but same label/annotations", func() {
  2334. h1 := util.HashMeta(metav1.ObjectMeta{
  2335. Generation: 1,
  2336. Annotations: map[string]string{
  2337. "foo": "bar",
  2338. },
  2339. Labels: map[string]string{
  2340. "foo": "bar",
  2341. },
  2342. })
  2343. h2 := util.HashMeta(metav1.ObjectMeta{
  2344. Generation: 2,
  2345. Annotations: map[string]string{
  2346. "foo": "bar",
  2347. },
  2348. Labels: map[string]string{
  2349. "foo": "bar",
  2350. },
  2351. })
  2352. Expect(h1).To(Equal(h2))
  2353. })
  2354. It("should produce the same hash for the same k/v pairs", func() {
  2355. h1 := util.HashMeta(metav1.ObjectMeta{
  2356. Generation: 1,
  2357. })
  2358. h2 := util.HashMeta(metav1.ObjectMeta{
  2359. Generation: 1,
  2360. })
  2361. Expect(h1).To(Equal(h2))
  2362. h1 = util.HashMeta(metav1.ObjectMeta{
  2363. Generation: 1,
  2364. Annotations: map[string]string{
  2365. "foo": "bar",
  2366. },
  2367. })
  2368. h2 = util.HashMeta(metav1.ObjectMeta{
  2369. Generation: 1,
  2370. Annotations: map[string]string{
  2371. "foo": "bar",
  2372. },
  2373. })
  2374. Expect(h1).To(Equal(h2))
  2375. })
  2376. })
  2377. })
  2378. var _ = Describe("ExternalSecret refresh policy", func() {
  2379. Context("RefreshPolicy=CreatedOnce", func() {
  2380. It("should refresh when SyncedResourceVersion is empty", func() {
  2381. es := &esv1.ExternalSecret{
  2382. Spec: esv1.ExternalSecretSpec{
  2383. RefreshPolicy: esv1.RefreshPolicyCreatedOnce,
  2384. },
  2385. Status: esv1.ExternalSecretStatus{
  2386. SyncedResourceVersion: "",
  2387. },
  2388. }
  2389. Expect(shouldRefresh(es)).To(BeTrue())
  2390. })
  2391. It("should refresh when RefreshTime is zero", func() {
  2392. es := &esv1.ExternalSecret{
  2393. Spec: esv1.ExternalSecretSpec{
  2394. RefreshPolicy: esv1.RefreshPolicyCreatedOnce,
  2395. },
  2396. Status: esv1.ExternalSecretStatus{
  2397. SyncedResourceVersion: "some-version",
  2398. RefreshTime: metav1.Time{},
  2399. },
  2400. }
  2401. Expect(shouldRefresh(es)).To(BeTrue())
  2402. })
  2403. It("should not refresh when already synced", func() {
  2404. es := &esv1.ExternalSecret{
  2405. Spec: esv1.ExternalSecretSpec{
  2406. RefreshPolicy: esv1.RefreshPolicyCreatedOnce,
  2407. },
  2408. Status: esv1.ExternalSecretStatus{
  2409. SyncedResourceVersion: "some-version",
  2410. RefreshTime: metav1.Now(),
  2411. },
  2412. }
  2413. Expect(shouldRefresh(es)).To(BeFalse())
  2414. })
  2415. })
  2416. Context("RefreshPolicy=OnChange", func() {
  2417. It("should refresh when SyncedResourceVersion is empty", func() {
  2418. es := &esv1.ExternalSecret{
  2419. Spec: esv1.ExternalSecretSpec{
  2420. RefreshPolicy: esv1.RefreshPolicyOnChange,
  2421. },
  2422. Status: esv1.ExternalSecretStatus{
  2423. SyncedResourceVersion: "",
  2424. },
  2425. }
  2426. Expect(shouldRefresh(es)).To(BeTrue())
  2427. })
  2428. It("should refresh when RefreshTime is zero", func() {
  2429. es := &esv1.ExternalSecret{
  2430. Spec: esv1.ExternalSecretSpec{
  2431. RefreshPolicy: esv1.RefreshPolicyOnChange,
  2432. },
  2433. Status: esv1.ExternalSecretStatus{
  2434. RefreshTime: metav1.Time{},
  2435. },
  2436. }
  2437. Expect(shouldRefresh(es)).To(BeTrue())
  2438. })
  2439. It("should refresh when resource version changes", func() {
  2440. es := &esv1.ExternalSecret{
  2441. ObjectMeta: metav1.ObjectMeta{
  2442. Generation: 1,
  2443. Annotations: map[string]string{
  2444. "foo": "bar",
  2445. },
  2446. },
  2447. Spec: esv1.ExternalSecretSpec{
  2448. RefreshPolicy: esv1.RefreshPolicyOnChange,
  2449. },
  2450. Status: esv1.ExternalSecretStatus{
  2451. RefreshTime: metav1.Now(),
  2452. SyncedResourceVersion: "old-version",
  2453. },
  2454. }
  2455. // The temp annotation is added in the shouldRefresh function
  2456. Expect(shouldRefresh(es)).To(BeTrue())
  2457. })
  2458. It("should not refresh when resource version matches", func() {
  2459. es := &esv1.ExternalSecret{
  2460. ObjectMeta: metav1.ObjectMeta{
  2461. Generation: 1,
  2462. },
  2463. Spec: esv1.ExternalSecretSpec{
  2464. RefreshPolicy: esv1.RefreshPolicyOnChange,
  2465. },
  2466. Status: esv1.ExternalSecretStatus{
  2467. RefreshTime: metav1.Now(),
  2468. },
  2469. }
  2470. // Set the synced resource version to match the current resource version
  2471. es.Status.SyncedResourceVersion = util.GetResourceVersion(es.ObjectMeta)
  2472. Expect(shouldRefresh(es)).To(BeFalse())
  2473. })
  2474. It("should refresh when annotations change", func() {
  2475. es := &esv1.ExternalSecret{
  2476. ObjectMeta: metav1.ObjectMeta{
  2477. Generation: 1,
  2478. Annotations: map[string]string{
  2479. "foo": "bar",
  2480. },
  2481. },
  2482. Spec: esv1.ExternalSecretSpec{
  2483. RefreshPolicy: esv1.RefreshPolicyOnChange,
  2484. },
  2485. Status: esv1.ExternalSecretStatus{
  2486. RefreshTime: metav1.Now(),
  2487. },
  2488. }
  2489. // Set the synced resource version to match the current resource version
  2490. es.Status.SyncedResourceVersion = util.GetResourceVersion(es.ObjectMeta)
  2491. Expect(shouldRefresh(es)).To(BeFalse())
  2492. es.Annotations["foo"] = "bar1"
  2493. Expect(shouldRefresh(es)).To(BeTrue())
  2494. })
  2495. It("should refresh when spec changes", func() {
  2496. es := &esv1.ExternalSecret{
  2497. ObjectMeta: metav1.ObjectMeta{
  2498. Generation: 1,
  2499. },
  2500. Spec: esv1.ExternalSecretSpec{
  2501. RefreshPolicy: esv1.RefreshPolicyOnChange,
  2502. Data: []esv1.ExternalSecretData{
  2503. {
  2504. SecretKey: "key1",
  2505. RemoteRef: esv1.ExternalSecretDataRemoteRef{
  2506. Key: "remote-key1",
  2507. },
  2508. },
  2509. },
  2510. },
  2511. Status: esv1.ExternalSecretStatus{
  2512. RefreshTime: metav1.Now(),
  2513. },
  2514. }
  2515. // Set the synced resource version to match the current resource version
  2516. es.Status.SyncedResourceVersion = util.GetResourceVersion(es.ObjectMeta)
  2517. // Initially should not refresh
  2518. Expect(shouldRefresh(es)).To(BeFalse())
  2519. // Update the spec by adding a new data item
  2520. es.ObjectMeta.Generation = 2
  2521. es.Spec.Data = append(es.Spec.Data, esv1.ExternalSecretData{
  2522. SecretKey: "key2",
  2523. RemoteRef: esv1.ExternalSecretDataRemoteRef{
  2524. Key: "remote-key2",
  2525. },
  2526. })
  2527. // The temp annotation is added in the shouldRefresh function to track spec hash
  2528. Expect(shouldRefresh(es)).To(BeTrue())
  2529. })
  2530. })
  2531. Context("Default refresh policy (Periodic)", func() {
  2532. It("should behave like Periodic when RefreshPolicy is not set", func() {
  2533. es := &esv1.ExternalSecret{
  2534. ObjectMeta: metav1.ObjectMeta{
  2535. Generation: 1,
  2536. },
  2537. Spec: esv1.ExternalSecretSpec{
  2538. // No RefreshPolicy set, should default to Periodic behavior
  2539. RefreshInterval: &metav1.Duration{Duration: time.Minute},
  2540. },
  2541. Status: esv1.ExternalSecretStatus{
  2542. RefreshTime: metav1.Now(),
  2543. },
  2544. }
  2545. es.Status.SyncedResourceVersion = util.GetResourceVersion(es.ObjectMeta)
  2546. Expect(shouldRefresh(es)).To(BeFalse())
  2547. // When refresh interval has passed
  2548. es.Status.RefreshTime = metav1.NewTime(metav1.Now().Add(-time.Minute * 2))
  2549. Expect(shouldRefresh(es)).To(BeTrue())
  2550. })
  2551. })
  2552. Context("RefreshPolicy=Periodic", func() {
  2553. It("should not refresh when refreshInterval is 0 and already synced", func() {
  2554. es := &esv1.ExternalSecret{
  2555. ObjectMeta: metav1.ObjectMeta{
  2556. Generation: 1,
  2557. },
  2558. Spec: esv1.ExternalSecretSpec{
  2559. RefreshPolicy: esv1.RefreshPolicyPeriodic,
  2560. RefreshInterval: &metav1.Duration{Duration: 0},
  2561. },
  2562. Status: esv1.ExternalSecretStatus{
  2563. SyncedResourceVersion: "some-version",
  2564. },
  2565. }
  2566. // Set the synced resource version to match the current resource version
  2567. es.Status.SyncedResourceVersion = util.GetResourceVersion(es.ObjectMeta)
  2568. Expect(shouldRefresh(es)).To(BeFalse())
  2569. })
  2570. It("should refresh when resource version changes", func() {
  2571. es := &esv1.ExternalSecret{
  2572. ObjectMeta: metav1.ObjectMeta{
  2573. Generation: 2,
  2574. },
  2575. Spec: esv1.ExternalSecretSpec{
  2576. RefreshPolicy: esv1.RefreshPolicyPeriodic,
  2577. RefreshInterval: &metav1.Duration{Duration: time.Minute},
  2578. },
  2579. Status: esv1.ExternalSecretStatus{
  2580. RefreshTime: metav1.Now(),
  2581. SyncedResourceVersion: "old-version",
  2582. },
  2583. }
  2584. Expect(shouldRefresh(es)).To(BeTrue())
  2585. })
  2586. It("should refresh when refresh interval has passed", func() {
  2587. es := &esv1.ExternalSecret{
  2588. ObjectMeta: metav1.ObjectMeta{
  2589. Generation: 1,
  2590. },
  2591. Spec: esv1.ExternalSecretSpec{
  2592. RefreshPolicy: esv1.RefreshPolicyPeriodic,
  2593. RefreshInterval: &metav1.Duration{Duration: time.Second},
  2594. },
  2595. Status: esv1.ExternalSecretStatus{
  2596. RefreshTime: metav1.NewTime(metav1.Now().Add(-time.Second * 5)),
  2597. },
  2598. }
  2599. // Resource version matches
  2600. es.Status.SyncedResourceVersion = util.GetResourceVersion(es.ObjectMeta)
  2601. Expect(shouldRefresh(es)).To(BeTrue())
  2602. })
  2603. It("should refresh when no refresh time was set", func() {
  2604. es := &esv1.ExternalSecret{
  2605. ObjectMeta: metav1.ObjectMeta{
  2606. Generation: 1,
  2607. },
  2608. Spec: esv1.ExternalSecretSpec{
  2609. RefreshPolicy: esv1.RefreshPolicyPeriodic,
  2610. RefreshInterval: &metav1.Duration{Duration: time.Second},
  2611. },
  2612. Status: esv1.ExternalSecretStatus{},
  2613. }
  2614. // Resource version matches
  2615. es.Status.SyncedResourceVersion = util.GetResourceVersion(es.ObjectMeta)
  2616. Expect(shouldRefresh(es)).To(BeTrue())
  2617. })
  2618. It("should refresh when refresh time is in the future", func() {
  2619. es := &esv1.ExternalSecret{
  2620. ObjectMeta: metav1.ObjectMeta{
  2621. Generation: 1,
  2622. },
  2623. Spec: esv1.ExternalSecretSpec{
  2624. RefreshPolicy: esv1.RefreshPolicyPeriodic,
  2625. RefreshInterval: &metav1.Duration{Duration: time.Second},
  2626. },
  2627. Status: esv1.ExternalSecretStatus{
  2628. RefreshTime: metav1.NewTime(time.Now().Add(time.Hour)), // Future time
  2629. },
  2630. }
  2631. // Resource version matches
  2632. es.Status.SyncedResourceVersion = util.GetResourceVersion(es.ObjectMeta)
  2633. Expect(shouldRefresh(es)).To(BeTrue())
  2634. })
  2635. It("should refresh when refreshInterval not 0 and spec changes", func() {
  2636. es := &esv1.ExternalSecret{
  2637. ObjectMeta: metav1.ObjectMeta{
  2638. Generation: 1,
  2639. },
  2640. Spec: esv1.ExternalSecretSpec{
  2641. RefreshPolicy: esv1.RefreshPolicyPeriodic,
  2642. RefreshInterval: &metav1.Duration{Duration: 10 * time.Second},
  2643. Data: []esv1.ExternalSecretData{
  2644. {
  2645. SecretKey: "key1",
  2646. RemoteRef: esv1.ExternalSecretDataRemoteRef{
  2647. Key: "remote-key1",
  2648. },
  2649. },
  2650. },
  2651. },
  2652. Status: esv1.ExternalSecretStatus{
  2653. SyncedResourceVersion: "some-version",
  2654. RefreshTime: metav1.NewTime(metav1.Now().Add(-time.Second * 5)),
  2655. },
  2656. }
  2657. es.Status.SyncedResourceVersion = util.GetResourceVersion(es.ObjectMeta)
  2658. Expect(shouldRefresh(es)).To(BeFalse())
  2659. es.ObjectMeta.Generation = 2
  2660. es.Spec.Data = append(es.Spec.Data, esv1.ExternalSecretData{
  2661. SecretKey: "key2",
  2662. RemoteRef: esv1.ExternalSecretDataRemoteRef{
  2663. Key: "remote-key2",
  2664. },
  2665. })
  2666. Expect(shouldRefresh(es)).To(BeTrue())
  2667. })
  2668. It("should not refresh when refreshInterval is 0 even if spec changes", func() {
  2669. es := &esv1.ExternalSecret{
  2670. ObjectMeta: metav1.ObjectMeta{
  2671. Generation: 1,
  2672. },
  2673. Spec: esv1.ExternalSecretSpec{
  2674. RefreshPolicy: esv1.RefreshPolicyPeriodic,
  2675. RefreshInterval: &metav1.Duration{Duration: 0},
  2676. Data: []esv1.ExternalSecretData{
  2677. {
  2678. SecretKey: "key1",
  2679. RemoteRef: esv1.ExternalSecretDataRemoteRef{
  2680. Key: "remote-key1",
  2681. },
  2682. },
  2683. },
  2684. },
  2685. Status: esv1.ExternalSecretStatus{
  2686. SyncedResourceVersion: "some-version",
  2687. RefreshTime: metav1.Now(),
  2688. },
  2689. }
  2690. // Set the synced resource version to match the current resource version
  2691. es.Status.SyncedResourceVersion = util.GetResourceVersion(es.ObjectMeta)
  2692. Expect(shouldRefresh(es)).To(BeFalse())
  2693. // Update the spec by adding a new data item
  2694. es.ObjectMeta.Generation = 2
  2695. es.Spec.Data = append(es.Spec.Data, esv1.ExternalSecretData{
  2696. SecretKey: "key2",
  2697. RemoteRef: esv1.ExternalSecretDataRemoteRef{
  2698. Key: "remote-key2",
  2699. },
  2700. })
  2701. // Should still not refresh because interval is 0
  2702. Expect(shouldRefresh(es)).To(BeFalse())
  2703. })
  2704. It("should not refresh when refreshInterval is 0 even if labels or annotations change", func() {
  2705. es := &esv1.ExternalSecret{
  2706. ObjectMeta: metav1.ObjectMeta{
  2707. Generation: 1,
  2708. Labels: map[string]string{
  2709. "original-label": "value",
  2710. },
  2711. Annotations: map[string]string{
  2712. "original-annotation": "value",
  2713. },
  2714. },
  2715. Spec: esv1.ExternalSecretSpec{
  2716. RefreshPolicy: esv1.RefreshPolicyPeriodic,
  2717. RefreshInterval: &metav1.Duration{Duration: 0},
  2718. },
  2719. Status: esv1.ExternalSecretStatus{
  2720. SyncedResourceVersion: "some-version",
  2721. RefreshTime: metav1.Now(),
  2722. },
  2723. }
  2724. // Set the synced resource version to match the current resource version
  2725. es.Status.SyncedResourceVersion = util.GetResourceVersion(es.ObjectMeta)
  2726. Expect(shouldRefresh(es)).To(BeFalse())
  2727. // Update labels and annotations
  2728. es.ObjectMeta.Labels["new-label"] = "new-value"
  2729. es.ObjectMeta.Annotations["new-annotation"] = "new-value"
  2730. // Should still not refresh because interval is 0
  2731. Expect(shouldRefresh(es)).To(BeFalse())
  2732. })
  2733. })
  2734. })
  2735. func externalSecretConditionShouldBe(name, ns string, ct esv1.ExternalSecretConditionType, cs v1.ConditionStatus, v float64) bool {
  2736. return Eventually(func() float64 {
  2737. Expect(testExternalSecretCondition.WithLabelValues(name, ns, string(ct), string(cs)).Write(&metric)).To(Succeed())
  2738. return metric.GetGauge().GetValue()
  2739. }, timeout, interval).Should(Equal(v))
  2740. }
  2741. func init() {
  2742. fakeProvider = fake.New()
  2743. esv1.ForceRegister(fakeProvider, &esv1.SecretStoreProvider{
  2744. AWS: &esv1.AWSProvider{
  2745. Service: esv1.AWSServiceSecretsManager,
  2746. },
  2747. }, esv1.MaintenanceStatusMaintained)
  2748. ctrlmetrics.SetUpLabelNames(false)
  2749. esmetrics.SetUpMetrics()
  2750. testSyncCallsTotal = esmetrics.GetCounterVec(esmetrics.SyncCallsKey)
  2751. testSyncCallsError = esmetrics.GetCounterVec(esmetrics.SyncCallsErrorKey)
  2752. testExternalSecretCondition = esmetrics.GetGaugeVec(esmetrics.ExternalSecretStatusConditionKey)
  2753. testExternalSecretReconcileDuration = esmetrics.GetGaugeVec(esmetrics.ExternalSecretReconcileDurationKey)
  2754. }