externalsecret_controller_test.go 95 KB

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