externalsecret_controller_test.go 89 KB

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