externalsecret_controller_test.go 114 KB

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