externalsecret_controller_test.go 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952
  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. "fmt"
  17. "os"
  18. "strconv"
  19. "time"
  20. . "github.com/onsi/ginkgo/v2"
  21. . "github.com/onsi/gomega"
  22. dto "github.com/prometheus/client_model/go"
  23. v1 "k8s.io/api/core/v1"
  24. apierrors "k8s.io/apimachinery/pkg/api/errors"
  25. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  26. "k8s.io/apimachinery/pkg/types"
  27. "sigs.k8s.io/controller-runtime/pkg/client"
  28. esv1beta1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1beta1"
  29. ctest "github.com/external-secrets/external-secrets/pkg/controllers/commontest"
  30. "github.com/external-secrets/external-secrets/pkg/provider/testing/fake"
  31. )
  32. var (
  33. fakeProvider *fake.Client
  34. metric dto.Metric
  35. metricDuration dto.Metric
  36. timeout = time.Second * 10
  37. interval = time.Millisecond * 250
  38. )
  39. type testCase struct {
  40. secretStore esv1beta1.GenericStore
  41. externalSecret *esv1beta1.ExternalSecret
  42. // checkCondition should return true if the externalSecret
  43. // has the expected condition
  44. checkCondition func(*esv1beta1.ExternalSecret) bool
  45. // checkExternalSecret is called after the condition has been verified
  46. // use this to verify the externalSecret
  47. checkExternalSecret func(*esv1beta1.ExternalSecret)
  48. // optional. use this to test the secret value
  49. checkSecret func(*esv1beta1.ExternalSecret, *v1.Secret)
  50. }
  51. type testTweaks func(*testCase)
  52. var _ = Describe("Kind=secret existence logic", func() {
  53. type testCase struct {
  54. Name string
  55. Input v1.Secret
  56. ExpectedOutput bool
  57. }
  58. tests := []testCase{
  59. {
  60. Name: "Should not be valid in case of missing uid",
  61. Input: v1.Secret{},
  62. ExpectedOutput: false,
  63. },
  64. {
  65. Name: "A nil annotation should not be valid",
  66. Input: v1.Secret{
  67. ObjectMeta: metav1.ObjectMeta{
  68. UID: "xxx",
  69. Annotations: map[string]string{},
  70. },
  71. },
  72. ExpectedOutput: false,
  73. },
  74. {
  75. Name: "A nil annotation should not be valid",
  76. Input: v1.Secret{
  77. ObjectMeta: metav1.ObjectMeta{
  78. UID: "xxx",
  79. Annotations: map[string]string{},
  80. },
  81. },
  82. ExpectedOutput: false,
  83. },
  84. {
  85. Name: "An invalid annotation hash should not be valid",
  86. Input: v1.Secret{
  87. ObjectMeta: metav1.ObjectMeta{
  88. UID: "xxx",
  89. Annotations: map[string]string{
  90. esv1beta1.AnnotationDataHash: "xxxxxx",
  91. },
  92. },
  93. },
  94. ExpectedOutput: false,
  95. },
  96. {
  97. Name: "A valid config map should return true",
  98. Input: v1.Secret{
  99. ObjectMeta: metav1.ObjectMeta{
  100. UID: "xxx",
  101. Annotations: map[string]string{
  102. esv1beta1.AnnotationDataHash: "caa0155759a6a9b3b6ada5a6883ee2bb",
  103. },
  104. },
  105. Data: map[string][]byte{
  106. "foo": []byte("value1"),
  107. "bar": []byte("value2"),
  108. },
  109. },
  110. ExpectedOutput: true,
  111. },
  112. }
  113. for _, tt := range tests {
  114. It(tt.Name, func() {
  115. Expect(isSecretValid(tt.Input)).To(BeEquivalentTo(tt.ExpectedOutput))
  116. })
  117. }
  118. })
  119. var _ = Describe("ExternalSecret controller", func() {
  120. const (
  121. ExternalSecretName = "test-es"
  122. ExternalSecretFQDN = "externalsecrets.external-secrets.io/test-es"
  123. ExternalSecretStore = "test-store"
  124. ExternalSecretTargetSecretName = "test-secret"
  125. FakeManager = "fake.manager"
  126. expectedSecretVal = "SOMEVALUE was templated"
  127. targetPropObj = "{{ .targetProperty | toString | upper }} was templated"
  128. FooValue = "map-foo-value"
  129. BarValue = "map-bar-value"
  130. NamespaceLabelKey = "css-test-label-key"
  131. NamespaceLabelValue = "css-test-label-value"
  132. )
  133. var ExternalSecretNamespace string
  134. // if we are in debug and need to increase the timeout for testing, we can do so by using an env var
  135. if customTimeout := os.Getenv("TEST_CUSTOM_TIMEOUT_SEC"); customTimeout != "" {
  136. if t, err := strconv.Atoi(customTimeout); err == nil {
  137. timeout = time.Second * time.Duration(t)
  138. }
  139. }
  140. BeforeEach(func() {
  141. var err error
  142. ExternalSecretNamespace, err = ctest.CreateNamespaceWithLabels("test-ns", k8sClient, map[string]string{NamespaceLabelKey: NamespaceLabelValue})
  143. Expect(err).ToNot(HaveOccurred())
  144. metric.Reset()
  145. syncCallsTotal.Reset()
  146. syncCallsError.Reset()
  147. externalSecretCondition.Reset()
  148. externalSecretReconcileDuration.Reset()
  149. fakeProvider.Reset()
  150. })
  151. AfterEach(
  152. func() {
  153. secretStore := &esv1beta1.SecretStore{}
  154. secretStoreLookupKey := types.NamespacedName{
  155. Name: ExternalSecretStore,
  156. Namespace: ExternalSecretNamespace,
  157. }
  158. if err := k8sClient.Get(context.Background(), secretStoreLookupKey, secretStore); err == nil {
  159. Expect(k8sClient.Delete(context.Background(), secretStore)).To(Succeed())
  160. }
  161. clusterSecretStore := &esv1beta1.ClusterSecretStore{}
  162. clusterSecretStoreLookupKey := types.NamespacedName{
  163. Name: ExternalSecretStore,
  164. }
  165. if err := k8sClient.Get(context.Background(), clusterSecretStoreLookupKey, clusterSecretStore); err == nil {
  166. Expect(k8sClient.Delete(context.Background(), clusterSecretStore)).To(Succeed())
  167. }
  168. Expect(k8sClient.Delete(context.Background(), &v1.Namespace{
  169. ObjectMeta: metav1.ObjectMeta{
  170. Name: ExternalSecretNamespace,
  171. },
  172. })).To(Succeed())
  173. },
  174. )
  175. const secretVal = "some-value"
  176. const targetProp = "targetProperty"
  177. const remoteKey = "barz"
  178. const remoteProperty = "bang"
  179. makeDefaultTestcase := func() *testCase {
  180. return &testCase{
  181. // default condition: es should be ready
  182. checkCondition: func(es *esv1beta1.ExternalSecret) bool {
  183. cond := GetExternalSecretCondition(es.Status, esv1beta1.ExternalSecretReady)
  184. if cond == nil || cond.Status != v1.ConditionTrue {
  185. return false
  186. }
  187. return true
  188. },
  189. checkExternalSecret: func(es *esv1beta1.ExternalSecret) {
  190. // noop by default
  191. },
  192. secretStore: &esv1beta1.SecretStore{
  193. ObjectMeta: metav1.ObjectMeta{
  194. Name: ExternalSecretStore,
  195. Namespace: ExternalSecretNamespace,
  196. },
  197. Spec: esv1beta1.SecretStoreSpec{
  198. Provider: &esv1beta1.SecretStoreProvider{
  199. AWS: &esv1beta1.AWSProvider{
  200. Service: esv1beta1.AWSServiceSecretsManager,
  201. },
  202. },
  203. },
  204. },
  205. externalSecret: &esv1beta1.ExternalSecret{
  206. ObjectMeta: metav1.ObjectMeta{
  207. Name: ExternalSecretName,
  208. Namespace: ExternalSecretNamespace,
  209. },
  210. Spec: esv1beta1.ExternalSecretSpec{
  211. SecretStoreRef: esv1beta1.SecretStoreRef{
  212. Name: ExternalSecretStore,
  213. },
  214. Target: esv1beta1.ExternalSecretTarget{
  215. Name: ExternalSecretTargetSecretName,
  216. },
  217. Data: []esv1beta1.ExternalSecretData{
  218. {
  219. SecretKey: targetProp,
  220. RemoteRef: esv1beta1.ExternalSecretDataRemoteRef{
  221. Key: remoteKey,
  222. Property: remoteProperty,
  223. },
  224. },
  225. },
  226. },
  227. },
  228. }
  229. }
  230. // if target Secret name is not specified it should use the ExternalSecret name.
  231. syncWithoutTargetName := func(tc *testCase) {
  232. tc.externalSecret.Spec.Target.Name = ""
  233. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  234. // check secret name
  235. Expect(secret.ObjectMeta.Name).To(Equal(ExternalSecretName))
  236. }
  237. }
  238. // labels and annotations from the Kind=ExternalSecret
  239. // should be copied over to the Kind=Secret
  240. syncLabelsAnnotations := func(tc *testCase) {
  241. const secretVal = "someValue"
  242. tc.externalSecret.ObjectMeta.Labels = map[string]string{
  243. "fooobar": "bazz",
  244. }
  245. tc.externalSecret.ObjectMeta.Annotations = map[string]string{
  246. "hihihih": "hehehe",
  247. }
  248. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  249. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  250. // check value
  251. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  252. // check labels & annotations
  253. Expect(secret.ObjectMeta.Labels).To(BeEquivalentTo(es.ObjectMeta.Labels))
  254. for k, v := range es.ObjectMeta.Annotations {
  255. Expect(secret.ObjectMeta.Annotations).To(HaveKeyWithValue(k, v))
  256. }
  257. // ownerRef must not not be set!
  258. Expect(ctest.HasOwnerRef(secret.ObjectMeta, "ExternalSecret", ExternalSecretName)).To(BeTrue())
  259. }
  260. }
  261. checkPrometheusCounters := func(tc *testCase) {
  262. const secretVal = "someValue"
  263. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  264. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  265. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1beta1.ExternalSecretReady, v1.ConditionFalse, 0.0)).To(BeTrue())
  266. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1beta1.ExternalSecretReady, v1.ConditionTrue, 1.0)).To(BeTrue())
  267. Eventually(func() bool {
  268. Expect(syncCallsTotal.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metric)).To(Succeed())
  269. Expect(externalSecretReconcileDuration.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metricDuration)).To(Succeed())
  270. return metric.GetCounter().GetValue() == 1.0 && metricDuration.GetGauge().GetValue() > 0.0
  271. }, timeout, interval).Should(BeTrue())
  272. }
  273. }
  274. // merge with existing secret using creationPolicy=Merge
  275. // it should NOT have a ownerReference
  276. // metadata.managedFields with the correct owner should be added to the secret
  277. mergeWithSecret := func(tc *testCase) {
  278. const secretVal = "someValue"
  279. const existingKey = "pre-existing-key"
  280. existingVal := "pre-existing-value"
  281. tc.externalSecret.Spec.Target.CreationPolicy = esv1beta1.CreatePolicyMerge
  282. // create secret beforehand
  283. Expect(k8sClient.Create(context.Background(), &v1.Secret{
  284. ObjectMeta: metav1.ObjectMeta{
  285. Name: ExternalSecretTargetSecretName,
  286. Namespace: ExternalSecretNamespace,
  287. },
  288. Data: map[string][]byte{
  289. existingKey: []byte(existingVal),
  290. },
  291. }, client.FieldOwner(FakeManager))).To(Succeed())
  292. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  293. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  294. // check value
  295. Expect(string(secret.Data[existingKey])).To(Equal(existingVal))
  296. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  297. // check labels & annotations
  298. Expect(secret.ObjectMeta.Labels).To(BeEquivalentTo(es.ObjectMeta.Labels))
  299. for k, v := range es.ObjectMeta.Annotations {
  300. Expect(secret.ObjectMeta.Annotations).To(HaveKeyWithValue(k, v))
  301. }
  302. Expect(ctest.HasOwnerRef(secret.ObjectMeta, "ExternalSecret", ExternalSecretFQDN)).To(BeFalse())
  303. Expect(secret.ObjectMeta.ManagedFields).To(HaveLen(2))
  304. Expect(ctest.HasFieldOwnership(
  305. secret.ObjectMeta,
  306. ExternalSecretFQDN,
  307. fmt.Sprintf("{\"f:data\":{\"f:targetProperty\":{}},\"f:immutable\":{},\"f:metadata\":{\"f:annotations\":{\"f:%s\":{}}}}", esv1beta1.AnnotationDataHash)),
  308. ).To(BeTrue())
  309. Expect(ctest.HasFieldOwnership(secret.ObjectMeta, FakeManager, "{\"f:data\":{\".\":{},\"f:pre-existing-key\":{}},\"f:type\":{}}")).To(BeTrue())
  310. }
  311. }
  312. // should not update if no changes
  313. mergeWithSecretNoChange := func(tc *testCase) {
  314. const existingKey = "pre-existing-key"
  315. existingVal := "someValue"
  316. tc.externalSecret.Spec.Target.CreationPolicy = esv1beta1.CreatePolicyMerge
  317. // create secret beforehand
  318. Expect(k8sClient.Create(context.Background(), &v1.Secret{
  319. ObjectMeta: metav1.ObjectMeta{
  320. Name: ExternalSecretTargetSecretName,
  321. Namespace: ExternalSecretNamespace,
  322. },
  323. Data: map[string][]byte{
  324. existingKey: []byte(existingVal),
  325. },
  326. }, client.FieldOwner(FakeManager))).To(Succeed())
  327. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  328. oldResourceVersion := secret.ResourceVersion
  329. cleanSecret := secret.DeepCopy()
  330. Expect(k8sClient.Patch(context.Background(), secret, client.MergeFrom(cleanSecret))).To(Succeed())
  331. newSecret := &v1.Secret{}
  332. Eventually(func() bool {
  333. secretLookupKey := types.NamespacedName{
  334. Name: ExternalSecretTargetSecretName,
  335. Namespace: ExternalSecretNamespace,
  336. }
  337. err := k8sClient.Get(context.Background(), secretLookupKey, newSecret)
  338. if err != nil {
  339. return false
  340. }
  341. return oldResourceVersion == newSecret.ResourceVersion
  342. }, timeout, interval).Should(Equal(true))
  343. }
  344. }
  345. // should not merge with secret if it doesn't exist
  346. mergeWithSecretErr := func(tc *testCase) {
  347. const secretVal = "someValue"
  348. tc.externalSecret.Spec.Target.CreationPolicy = esv1beta1.CreatePolicyMerge
  349. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  350. tc.checkCondition = func(es *esv1beta1.ExternalSecret) bool {
  351. cond := GetExternalSecretCondition(es.Status, esv1beta1.ExternalSecretReady)
  352. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1beta1.ConditionReasonSecretSyncedError {
  353. return false
  354. }
  355. return true
  356. }
  357. tc.checkExternalSecret = func(es *esv1beta1.ExternalSecret) {
  358. Eventually(func() bool {
  359. Expect(syncCallsError.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metric)).To(Succeed())
  360. Expect(externalSecretReconcileDuration.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metricDuration)).To(Succeed())
  361. return metric.GetCounter().GetValue() >= 2.0 && metricDuration.GetGauge().GetValue() > 0.0
  362. }, timeout, interval).Should(BeTrue())
  363. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1beta1.ExternalSecretReady, v1.ConditionFalse, 1.0)).To(BeTrue())
  364. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1beta1.ExternalSecretReady, v1.ConditionTrue, 0.0)).To(BeTrue())
  365. }
  366. }
  367. // controller should force ownership
  368. mergeWithConflict := func(tc *testCase) {
  369. const secretVal = "someValue"
  370. // this should confict
  371. const existingKey = targetProp
  372. existingVal := "pre-existing-value"
  373. tc.externalSecret.Spec.Target.CreationPolicy = esv1beta1.CreatePolicyMerge
  374. // create secret beforehand
  375. Expect(k8sClient.Create(context.Background(), &v1.Secret{
  376. ObjectMeta: metav1.ObjectMeta{
  377. Name: ExternalSecretTargetSecretName,
  378. Namespace: ExternalSecretNamespace,
  379. },
  380. Data: map[string][]byte{
  381. existingKey: []byte(existingVal),
  382. },
  383. }, client.FieldOwner(FakeManager))).To(Succeed())
  384. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  385. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  386. // check that value stays the same
  387. Expect(string(secret.Data[existingKey])).To(Equal(secretVal))
  388. // check owner/managedFields
  389. Expect(ctest.HasOwnerRef(secret.ObjectMeta, "ExternalSecret", ExternalSecretFQDN)).To(BeFalse())
  390. Expect(secret.ObjectMeta.ManagedFields).To(HaveLen(2))
  391. Expect(ctest.HasFieldOwnership(secret.ObjectMeta, ExternalSecretFQDN, "{\"f:data\":{\"f:targetProperty\":{}},\"f:immutable\":{},\"f:metadata\":{\"f:annotations\":{\"f:reconcile.external-secrets.io/data-hash\":{}}}}")).To(BeTrue())
  392. }
  393. }
  394. // when using a template it should be used as a blueprint
  395. // to construct a new secret: labels, annotations and type
  396. syncWithTemplate := func(tc *testCase) {
  397. const secretVal = "someValue"
  398. const tplStaticKey = "tplstatickey"
  399. const tplStaticVal = "tplstaticvalue"
  400. tc.externalSecret.ObjectMeta.Labels = map[string]string{
  401. "fooobar": "bazz",
  402. }
  403. tc.externalSecret.ObjectMeta.Annotations = map[string]string{
  404. "hihihih": "hehehe",
  405. }
  406. tc.externalSecret.Spec.Target.Template = &esv1beta1.ExternalSecretTemplate{
  407. Metadata: esv1beta1.ExternalSecretTemplateMetadata{
  408. Labels: map[string]string{
  409. "foos": "ball",
  410. },
  411. Annotations: map[string]string{
  412. "hihi": "ga",
  413. },
  414. },
  415. Type: v1.SecretTypeOpaque,
  416. EngineVersion: esv1beta1.TemplateEngineV1,
  417. Data: map[string]string{
  418. targetProp: targetPropObj,
  419. tplStaticKey: tplStaticVal,
  420. },
  421. }
  422. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  423. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  424. // check values
  425. Expect(string(secret.Data[targetProp])).To(Equal(expectedSecretVal))
  426. Expect(string(secret.Data[tplStaticKey])).To(Equal(tplStaticVal))
  427. // labels/annotations should be taken from the template
  428. Expect(secret.ObjectMeta.Labels).To(BeEquivalentTo(es.Spec.Target.Template.Metadata.Labels))
  429. for k, v := range es.Spec.Target.Template.Metadata.Annotations {
  430. Expect(secret.ObjectMeta.Annotations).To(HaveKeyWithValue(k, v))
  431. }
  432. }
  433. }
  434. // when using a v2 template it should use the v2 engine version
  435. syncWithTemplateV2 := func(tc *testCase) {
  436. const secretVal = "someValue"
  437. tc.externalSecret.Spec.Target.Template = &esv1beta1.ExternalSecretTemplate{
  438. Type: v1.SecretTypeOpaque,
  439. // it should default to v2 for beta11
  440. // EngineVersion: esv1beta1.TemplateEngineV2,
  441. Data: map[string]string{
  442. targetProp: "{{ .targetProperty | upper }} was templated",
  443. },
  444. }
  445. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  446. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  447. // check values
  448. Expect(string(secret.Data[targetProp])).To(Equal(expectedSecretVal))
  449. }
  450. }
  451. // secret should be synced with correct value precedence:
  452. // * template
  453. // * templateFrom
  454. // * data
  455. // * dataFrom
  456. syncWithTemplatePrecedence := func(tc *testCase) {
  457. const secretVal = "someValue"
  458. const tplStaticKey = "tplstatickey"
  459. const tplStaticVal = "tplstaticvalue"
  460. const tplFromCMName = "template-cm"
  461. const tplFromSecretName = "template-secret"
  462. const tplFromKey = "tpl-from-key"
  463. const tplFromSecKey = "tpl-from-sec-key"
  464. const tplFromVal = "tpl-from-value: {{ .targetProperty | toString }} // {{ .bar | toString }}"
  465. const tplFromSecVal = "tpl-from-sec-value: {{ .targetProperty | toString }} // {{ .bar | toString }}"
  466. Expect(k8sClient.Create(context.Background(), &v1.ConfigMap{
  467. ObjectMeta: metav1.ObjectMeta{
  468. Name: tplFromCMName,
  469. Namespace: ExternalSecretNamespace,
  470. },
  471. Data: map[string]string{
  472. tplFromKey: tplFromVal,
  473. },
  474. })).To(Succeed())
  475. Expect(k8sClient.Create(context.Background(), &v1.Secret{
  476. ObjectMeta: metav1.ObjectMeta{
  477. Name: tplFromSecretName,
  478. Namespace: ExternalSecretNamespace,
  479. },
  480. Data: map[string][]byte{
  481. tplFromSecKey: []byte(tplFromSecVal),
  482. },
  483. })).To(Succeed())
  484. tc.externalSecret.Spec.Target.Template = &esv1beta1.ExternalSecretTemplate{
  485. Metadata: esv1beta1.ExternalSecretTemplateMetadata{},
  486. Type: v1.SecretTypeOpaque,
  487. TemplateFrom: []esv1beta1.TemplateFrom{
  488. {
  489. ConfigMap: &esv1beta1.TemplateRef{
  490. Name: tplFromCMName,
  491. Items: []esv1beta1.TemplateRefItem{
  492. {
  493. Key: tplFromKey,
  494. },
  495. },
  496. },
  497. },
  498. {
  499. Secret: &esv1beta1.TemplateRef{
  500. Name: tplFromSecretName,
  501. Items: []esv1beta1.TemplateRefItem{
  502. {
  503. Key: tplFromSecKey,
  504. },
  505. },
  506. },
  507. },
  508. },
  509. Data: map[string]string{
  510. // this should be the data value, not dataFrom
  511. targetProp: targetPropObj,
  512. // this should use the value from the map
  513. "bar": "value from map: {{ .bar | toString }}",
  514. // just a static value
  515. tplStaticKey: tplStaticVal,
  516. },
  517. }
  518. tc.externalSecret.Spec.DataFrom = []esv1beta1.ExternalSecretDataFromRemoteRef{
  519. {
  520. Extract: &esv1beta1.ExternalSecretDataRemoteRef{
  521. Key: "datamap",
  522. },
  523. },
  524. }
  525. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  526. fakeProvider.WithGetSecretMap(map[string][]byte{
  527. "targetProperty": []byte(FooValue),
  528. "bar": []byte(BarValue),
  529. }, nil)
  530. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  531. // check values
  532. Expect(string(secret.Data[targetProp])).To(Equal(expectedSecretVal))
  533. Expect(string(secret.Data[tplStaticKey])).To(Equal(tplStaticVal))
  534. Expect(string(secret.Data["bar"])).To(Equal("value from map: map-bar-value"))
  535. Expect(string(secret.Data[tplFromKey])).To(Equal("tpl-from-value: someValue // map-bar-value"))
  536. Expect(string(secret.Data[tplFromSecKey])).To(Equal("tpl-from-sec-value: someValue // map-bar-value"))
  537. }
  538. }
  539. refreshWithTemplate := func(tc *testCase) {
  540. const secretVal = "someValue"
  541. const tplStaticKey = "tplstatickey"
  542. const tplStaticVal = "tplstaticvalue"
  543. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Second}
  544. tc.externalSecret.Spec.Target.Template = &esv1beta1.ExternalSecretTemplate{
  545. Metadata: esv1beta1.ExternalSecretTemplateMetadata{
  546. Labels: map[string]string{"foo": "bar"},
  547. Annotations: map[string]string{"foo": "bar"},
  548. },
  549. Type: v1.SecretTypeOpaque,
  550. Data: map[string]string{
  551. targetProp: targetPropObj,
  552. tplStaticKey: tplStaticVal,
  553. },
  554. }
  555. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  556. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  557. // check values
  558. Expect(string(secret.Data[targetProp])).To(Equal(expectedSecretVal))
  559. Expect(string(secret.Data[tplStaticKey])).To(Equal(tplStaticVal))
  560. // labels/annotations should be taken from the template
  561. Expect(secret.ObjectMeta.Labels).To(BeEquivalentTo(es.Spec.Target.Template.Metadata.Labels))
  562. // a secret will always have some extra annotations (i.e. hashmap check), so we only check for specific
  563. // source annotations
  564. for k, v := range es.Spec.Target.Template.Metadata.Annotations {
  565. Expect(secret.ObjectMeta.Annotations).To(HaveKeyWithValue(k, v))
  566. }
  567. cleanEs := tc.externalSecret.DeepCopy()
  568. // now update ExternalSecret
  569. tc.externalSecret.Spec.Target.Template.Metadata.Annotations["fuzz"] = "buzz"
  570. tc.externalSecret.Spec.Target.Template.Metadata.Labels["fuzz"] = "buzz"
  571. tc.externalSecret.Spec.Target.Template.Data["new"] = "value"
  572. Expect(k8sClient.Patch(context.Background(), tc.externalSecret, client.MergeFrom(cleanEs))).To(Succeed())
  573. // wait for secret
  574. sec := &v1.Secret{}
  575. secretLookupKey := types.NamespacedName{
  576. Name: ExternalSecretTargetSecretName,
  577. Namespace: ExternalSecretNamespace,
  578. }
  579. Eventually(func() bool {
  580. err := k8sClient.Get(context.Background(), secretLookupKey, sec)
  581. if err != nil {
  582. return false
  583. }
  584. // ensure new data value exist
  585. return string(sec.Data["new"]) == "value"
  586. }, time.Second*10, time.Millisecond*200).Should(BeTrue())
  587. // also check labels/annotations have been updated
  588. Expect(secret.ObjectMeta.Labels).To(BeEquivalentTo(es.Spec.Target.Template.Metadata.Labels))
  589. for k, v := range es.Spec.Target.Template.Metadata.Annotations {
  590. Expect(secret.ObjectMeta.Annotations).To(HaveKeyWithValue(k, v))
  591. }
  592. }
  593. }
  594. onlyMetadataFromTemplate := func(tc *testCase) {
  595. const secretVal = "someValue"
  596. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Second}
  597. tc.externalSecret.Spec.Target.Template = &esv1beta1.ExternalSecretTemplate{
  598. Metadata: esv1beta1.ExternalSecretTemplateMetadata{
  599. Labels: map[string]string{"foo": "bar"},
  600. Annotations: map[string]string{"foo": "bar"},
  601. },
  602. }
  603. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  604. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  605. // check values
  606. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  607. // labels/annotations should be taken from the template
  608. Expect(secret.ObjectMeta.Labels).To(BeEquivalentTo(es.Spec.Target.Template.Metadata.Labels))
  609. for k, v := range es.Spec.Target.Template.Metadata.Annotations {
  610. Expect(secret.ObjectMeta.Annotations).To(HaveKeyWithValue(k, v))
  611. }
  612. }
  613. }
  614. // when the provider secret changes the Kind=Secret value
  615. // must change, too.
  616. refreshSecretValue := func(tc *testCase) {
  617. const targetProp = "targetProperty"
  618. const secretVal = "someValue"
  619. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  620. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Second}
  621. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  622. // check values
  623. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  624. // update provider secret
  625. newValue := "NEW VALUE"
  626. sec := &v1.Secret{}
  627. fakeProvider.WithGetSecret([]byte(newValue), nil)
  628. secretLookupKey := types.NamespacedName{
  629. Name: ExternalSecretTargetSecretName,
  630. Namespace: ExternalSecretNamespace,
  631. }
  632. Eventually(func() bool {
  633. err := k8sClient.Get(context.Background(), secretLookupKey, sec)
  634. if err != nil {
  635. return false
  636. }
  637. v := sec.Data[targetProp]
  638. return string(v) == newValue
  639. }, timeout, interval).Should(BeTrue())
  640. }
  641. }
  642. // when a provider secret was deleted it must be deleted from
  643. // the secret aswell
  644. refreshSecretValueMap := func(tc *testCase) {
  645. fakeProvider.WithGetSecretMap(map[string][]byte{
  646. "foo": []byte("1111"),
  647. "bar": []byte("2222"),
  648. }, nil)
  649. tc.externalSecret.Spec.Data = []esv1beta1.ExternalSecretData{}
  650. tc.externalSecret.Spec.DataFrom = []esv1beta1.ExternalSecretDataFromRemoteRef{
  651. {
  652. Extract: &esv1beta1.ExternalSecretDataRemoteRef{
  653. Key: remoteKey,
  654. },
  655. },
  656. }
  657. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Second}
  658. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  659. // check values
  660. Expect(string(secret.Data["foo"])).To(Equal("1111"))
  661. Expect(string(secret.Data["bar"])).To(Equal("2222"))
  662. // update provider secret
  663. sec := &v1.Secret{}
  664. fakeProvider.WithGetSecretMap(map[string][]byte{
  665. "foo": []byte("1111"),
  666. }, nil)
  667. secretLookupKey := types.NamespacedName{
  668. Name: ExternalSecretTargetSecretName,
  669. Namespace: ExternalSecretNamespace,
  670. }
  671. Eventually(func() bool {
  672. err := k8sClient.Get(context.Background(), secretLookupKey, sec)
  673. if err != nil {
  674. return false
  675. }
  676. return string(sec.Data["foo"]) == "1111" &&
  677. sec.Data["bar"] == nil // must not be defined, it was deleted
  678. }, timeout, interval).Should(BeTrue())
  679. }
  680. }
  681. // when a provider secret was deleted it must be deleted from
  682. // the secret aswell when using a template
  683. refreshSecretValueMapTemplate := func(tc *testCase) {
  684. fakeProvider.WithGetSecretMap(map[string][]byte{
  685. "foo": []byte("1111"),
  686. "bar": []byte("2222"),
  687. }, nil)
  688. tc.externalSecret.Spec.Target.Template = &esv1beta1.ExternalSecretTemplate{}
  689. tc.externalSecret.Spec.Data = []esv1beta1.ExternalSecretData{}
  690. tc.externalSecret.Spec.DataFrom = []esv1beta1.ExternalSecretDataFromRemoteRef{
  691. {
  692. Extract: &esv1beta1.ExternalSecretDataRemoteRef{
  693. Key: remoteKey,
  694. },
  695. },
  696. }
  697. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Second}
  698. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  699. // check values
  700. Expect(string(secret.Data["foo"])).To(Equal("1111"))
  701. Expect(string(secret.Data["bar"])).To(Equal("2222"))
  702. // update provider secret
  703. sec := &v1.Secret{}
  704. fakeProvider.WithGetSecretMap(map[string][]byte{
  705. "foo": []byte("1111"),
  706. }, nil)
  707. secretLookupKey := types.NamespacedName{
  708. Name: ExternalSecretTargetSecretName,
  709. Namespace: ExternalSecretNamespace,
  710. }
  711. Eventually(func() bool {
  712. err := k8sClient.Get(context.Background(), secretLookupKey, sec)
  713. if err != nil {
  714. return false
  715. }
  716. return string(sec.Data["foo"]) == "1111" &&
  717. sec.Data["bar"] == nil // must not be defined, it was deleted
  718. }, timeout, interval).Should(BeTrue())
  719. }
  720. }
  721. refreshintervalZero := func(tc *testCase) {
  722. const targetProp = "targetProperty"
  723. const secretVal = "someValue"
  724. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  725. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: 0}
  726. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  727. // check values
  728. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  729. // update provider secret
  730. newValue := "NEW VALUE"
  731. sec := &v1.Secret{}
  732. fakeProvider.WithGetSecret([]byte(newValue), nil)
  733. secretLookupKey := types.NamespacedName{
  734. Name: ExternalSecretTargetSecretName,
  735. Namespace: ExternalSecretNamespace,
  736. }
  737. Consistently(func() bool {
  738. err := k8sClient.Get(context.Background(), secretLookupKey, sec)
  739. if err != nil {
  740. return false
  741. }
  742. v := sec.Data[targetProp]
  743. return string(v) == secretVal
  744. }, time.Second*10, time.Second).Should(BeTrue())
  745. }
  746. }
  747. deleteSecretPolicy := func(tc *testCase) {
  748. expVal := []byte("1234")
  749. // set initial value
  750. fakeProvider.WithGetAllSecrets(map[string][]byte{
  751. "foo": expVal,
  752. "bar": expVal,
  753. }, nil)
  754. tc.externalSecret.Spec.Data = nil
  755. tc.externalSecret.Spec.DataFrom = []esv1beta1.ExternalSecretDataFromRemoteRef{
  756. {
  757. Find: &esv1beta1.ExternalSecretFind{
  758. Tags: map[string]string{},
  759. },
  760. },
  761. }
  762. tc.externalSecret.Spec.Target.DeletionPolicy = esv1beta1.DeletionPolicyDelete
  763. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Second}
  764. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  765. Expect(secret.Data["foo"]).To(Equal(expVal))
  766. // update provider secret
  767. fakeProvider.WithGetAllSecrets(map[string][]byte{
  768. "foo": expVal,
  769. }, nil)
  770. sec := &v1.Secret{}
  771. secretLookupKey := types.NamespacedName{
  772. Name: ExternalSecretTargetSecretName,
  773. Namespace: ExternalSecretNamespace,
  774. }
  775. Eventually(func() bool {
  776. By("checking secret value for foo=1234 and bar=nil")
  777. err := k8sClient.Get(context.Background(), secretLookupKey, sec)
  778. if err != nil {
  779. return false
  780. }
  781. return bytes.Equal(sec.Data["foo"], expVal) && sec.Data["bar"] == nil
  782. }, time.Second*10, time.Second).Should(BeTrue())
  783. // return specific delete err to indicate deletion
  784. fakeProvider.WithGetAllSecrets(map[string][]byte{}, esv1beta1.NoSecretErr)
  785. Eventually(func() bool {
  786. By("checking that secret has been deleted")
  787. err := k8sClient.Get(context.Background(), secretLookupKey, sec)
  788. return apierrors.IsNotFound(err)
  789. }, time.Second*10, time.Second).Should(BeTrue())
  790. }
  791. }
  792. deleteSecretPolicyRetain := func(tc *testCase) {
  793. expVal := []byte("1234")
  794. // set initial value
  795. fakeProvider.WithGetAllSecrets(map[string][]byte{
  796. "foo": expVal,
  797. "bar": expVal,
  798. }, nil)
  799. tc.externalSecret.Spec.DataFrom = []esv1beta1.ExternalSecretDataFromRemoteRef{
  800. {
  801. Find: &esv1beta1.ExternalSecretFind{
  802. Tags: map[string]string{},
  803. },
  804. },
  805. }
  806. tc.externalSecret.Spec.Target.DeletionPolicy = esv1beta1.DeletionPolicyRetain
  807. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Second}
  808. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  809. Expect(secret.Data["foo"]).To(Equal(expVal))
  810. sec := &v1.Secret{}
  811. secretLookupKey := types.NamespacedName{
  812. Name: ExternalSecretTargetSecretName,
  813. Namespace: ExternalSecretNamespace,
  814. }
  815. // return specific delete err to indicate deletion
  816. // however this should not trigger a delete
  817. fakeProvider.WithGetAllSecrets(map[string][]byte{}, esv1beta1.NoSecretErr)
  818. Consistently(func() bool {
  819. By("checking that secret has not been deleted")
  820. err := k8sClient.Get(context.Background(), secretLookupKey, sec)
  821. return apierrors.IsNotFound(err) && bytes.Equal(sec.Data["foo"], expVal)
  822. }, time.Second*10, time.Second).Should(BeFalse())
  823. }
  824. }
  825. // merge with existing secret using creationPolicy=Merge
  826. // if provider secret gets deleted only the managed field should get deleted
  827. deleteSecretPolicyMerge := func(tc *testCase) {
  828. const secretVal = "someValue"
  829. const existingKey = "some-existing-key"
  830. existingVal := "some-existing-value"
  831. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Second}
  832. tc.externalSecret.Spec.Target.CreationPolicy = esv1beta1.CreatePolicyMerge
  833. tc.externalSecret.Spec.Target.DeletionPolicy = esv1beta1.DeletionPolicyMerge
  834. // create secret beforehand
  835. Expect(k8sClient.Create(context.Background(), &v1.Secret{
  836. ObjectMeta: metav1.ObjectMeta{
  837. Name: ExternalSecretTargetSecretName,
  838. Namespace: ExternalSecretNamespace,
  839. },
  840. Data: map[string][]byte{
  841. existingKey: []byte(existingVal),
  842. },
  843. }, client.FieldOwner(FakeManager))).To(Succeed())
  844. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  845. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  846. // check value
  847. Expect(string(secret.Data[existingKey])).To(Equal(existingVal))
  848. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  849. sec := &v1.Secret{}
  850. secretLookupKey := types.NamespacedName{
  851. Name: ExternalSecretTargetSecretName,
  852. Namespace: ExternalSecretNamespace,
  853. }
  854. // return specific delete err to indicate deletion
  855. // however this should not trigger a delete
  856. // instead expect that only the pre-existing value exists
  857. fakeProvider.WithGetSecret(nil, esv1beta1.NoSecretErr)
  858. Eventually(func() bool {
  859. By("checking that secret has not been deleted and pre-existing key exists")
  860. err := k8sClient.Get(context.Background(), secretLookupKey, sec)
  861. return !apierrors.IsNotFound(err) &&
  862. len(sec.Data) == 1 &&
  863. bytes.Equal(sec.Data[existingKey], []byte(existingVal))
  864. }, time.Second*30, time.Second).Should(BeTrue())
  865. }
  866. }
  867. // orphan the secret after the external secret has been deleted
  868. createSecretPolicyOrphan := func(tc *testCase) {
  869. const secretVal = "someValue"
  870. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Second}
  871. tc.externalSecret.Spec.Target.CreationPolicy = esv1beta1.CreatePolicyOrphan
  872. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  873. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  874. // check value
  875. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  876. sec := &v1.Secret{}
  877. secretLookupKey := types.NamespacedName{
  878. Name: ExternalSecretTargetSecretName,
  879. Namespace: ExternalSecretNamespace,
  880. }
  881. err := k8sClient.Delete(context.Background(), tc.externalSecret)
  882. Expect(err).ToNot(HaveOccurred())
  883. Consistently(func() bool {
  884. By("checking that secret has not been deleted")
  885. err := k8sClient.Get(context.Background(), secretLookupKey, sec)
  886. return !apierrors.IsNotFound(err)
  887. }, time.Second*15, time.Second).Should(BeTrue())
  888. }
  889. }
  890. // with rewrite all keys from a dataFrom operation
  891. // should be put with new rewriting into the secret
  892. syncAndRewriteWithDataFrom := func(tc *testCase) {
  893. tc.externalSecret.Spec.Data = nil
  894. tc.externalSecret.Spec.DataFrom = []esv1beta1.ExternalSecretDataFromRemoteRef{
  895. {
  896. Extract: &esv1beta1.ExternalSecretDataRemoteRef{
  897. Key: remoteKey,
  898. },
  899. Rewrite: []esv1beta1.ExternalSecretRewrite{{
  900. Regexp: &esv1beta1.ExternalSecretRewriteRegexp{
  901. Source: "(.*)",
  902. Target: "new-$1",
  903. },
  904. }},
  905. },
  906. {
  907. Extract: &esv1beta1.ExternalSecretDataRemoteRef{
  908. Key: remoteKey,
  909. },
  910. Rewrite: []esv1beta1.ExternalSecretRewrite{{
  911. Regexp: &esv1beta1.ExternalSecretRewriteRegexp{
  912. Source: "(.*)",
  913. Target: "old-$1",
  914. },
  915. }},
  916. },
  917. }
  918. fakeProvider.WithGetSecretMap(map[string][]byte{
  919. "foo": []byte(FooValue),
  920. "bar": []byte(BarValue),
  921. }, nil)
  922. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  923. // check values
  924. Expect(string(secret.Data["new-foo"])).To(Equal(FooValue))
  925. Expect(string(secret.Data["new-bar"])).To(Equal(BarValue))
  926. Expect(string(secret.Data["old-foo"])).To(Equal(FooValue))
  927. Expect(string(secret.Data["old-bar"])).To(Equal(BarValue))
  928. }
  929. }
  930. // with rewrite keys from dataFrom
  931. // should error if keys are not compliant
  932. invalidExtractKeysErrCondition := func(tc *testCase) {
  933. tc.externalSecret.Spec.Data = nil
  934. tc.externalSecret.Spec.DataFrom = []esv1beta1.ExternalSecretDataFromRemoteRef{
  935. {
  936. Extract: &esv1beta1.ExternalSecretDataRemoteRef{
  937. Key: remoteKey,
  938. },
  939. Rewrite: []esv1beta1.ExternalSecretRewrite{{
  940. Regexp: &esv1beta1.ExternalSecretRewriteRegexp{
  941. Source: "(.*)",
  942. Target: "$1",
  943. },
  944. }},
  945. },
  946. }
  947. fakeProvider.WithGetSecretMap(map[string][]byte{
  948. "foo/bar": []byte(FooValue),
  949. "bar/foo": []byte(BarValue),
  950. }, nil)
  951. tc.checkCondition = func(es *esv1beta1.ExternalSecret) bool {
  952. cond := GetExternalSecretCondition(es.Status, esv1beta1.ExternalSecretReady)
  953. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1beta1.ConditionReasonSecretSyncedError {
  954. return false
  955. }
  956. return true
  957. }
  958. tc.checkCondition = func(es *esv1beta1.ExternalSecret) bool {
  959. cond := GetExternalSecretCondition(es.Status, esv1beta1.ExternalSecretReady)
  960. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1beta1.ConditionReasonSecretSyncedError {
  961. return false
  962. }
  963. return true
  964. }
  965. tc.checkExternalSecret = func(es *esv1beta1.ExternalSecret) {
  966. Eventually(func() bool {
  967. Expect(syncCallsError.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metric)).To(Succeed())
  968. Expect(externalSecretReconcileDuration.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metricDuration)).To(Succeed())
  969. return metric.GetCounter().GetValue() >= 2.0 && metricDuration.GetGauge().GetValue() > 0.0
  970. }, timeout, interval).Should(BeTrue())
  971. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1beta1.ExternalSecretReady, v1.ConditionFalse, 1.0)).To(BeTrue())
  972. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1beta1.ExternalSecretReady, v1.ConditionTrue, 0.0)).To(BeTrue())
  973. }
  974. }
  975. // with rewrite keys from dataFrom
  976. // should error if keys are not compliant
  977. invalidFindKeysErrCondition := func(tc *testCase) {
  978. tc.externalSecret.Spec.Data = nil
  979. tc.externalSecret.Spec.DataFrom = []esv1beta1.ExternalSecretDataFromRemoteRef{
  980. {
  981. Find: &esv1beta1.ExternalSecretFind{
  982. Name: &esv1beta1.FindName{
  983. RegExp: ".*",
  984. },
  985. },
  986. Rewrite: []esv1beta1.ExternalSecretRewrite{{
  987. Regexp: &esv1beta1.ExternalSecretRewriteRegexp{
  988. Source: "(.*)",
  989. Target: "$1",
  990. },
  991. }},
  992. },
  993. }
  994. fakeProvider.WithGetAllSecrets(map[string][]byte{
  995. "foo/bar": []byte(FooValue),
  996. "bar/foo": []byte(BarValue),
  997. }, nil)
  998. tc.checkCondition = func(es *esv1beta1.ExternalSecret) bool {
  999. cond := GetExternalSecretCondition(es.Status, esv1beta1.ExternalSecretReady)
  1000. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1beta1.ConditionReasonSecretSyncedError {
  1001. return false
  1002. }
  1003. return true
  1004. }
  1005. tc.checkCondition = func(es *esv1beta1.ExternalSecret) bool {
  1006. cond := GetExternalSecretCondition(es.Status, esv1beta1.ExternalSecretReady)
  1007. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1beta1.ConditionReasonSecretSyncedError {
  1008. return false
  1009. }
  1010. return true
  1011. }
  1012. tc.checkExternalSecret = func(es *esv1beta1.ExternalSecret) {
  1013. Eventually(func() bool {
  1014. Expect(syncCallsError.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metric)).To(Succeed())
  1015. Expect(externalSecretReconcileDuration.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metricDuration)).To(Succeed())
  1016. return metric.GetCounter().GetValue() >= 2.0 && metricDuration.GetGauge().GetValue() > 0.0
  1017. }, timeout, interval).Should(BeTrue())
  1018. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1beta1.ExternalSecretReady, v1.ConditionFalse, 1.0)).To(BeTrue())
  1019. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1beta1.ExternalSecretReady, v1.ConditionTrue, 0.0)).To(BeTrue())
  1020. }
  1021. }
  1022. // with dataFrom all properties from the specified secret
  1023. // should be put into the secret
  1024. syncWithDataFrom := func(tc *testCase) {
  1025. tc.externalSecret.Spec.Data = nil
  1026. tc.externalSecret.Spec.DataFrom = []esv1beta1.ExternalSecretDataFromRemoteRef{
  1027. {
  1028. Extract: &esv1beta1.ExternalSecretDataRemoteRef{
  1029. Key: remoteKey,
  1030. },
  1031. },
  1032. }
  1033. fakeProvider.WithGetSecretMap(map[string][]byte{
  1034. "foo": []byte(FooValue),
  1035. "bar": []byte(BarValue),
  1036. }, nil)
  1037. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  1038. // check values
  1039. Expect(string(secret.Data["foo"])).To(Equal(FooValue))
  1040. Expect(string(secret.Data["bar"])).To(Equal(BarValue))
  1041. }
  1042. }
  1043. // with dataFrom.Find the change is on the called method GetAllSecrets
  1044. // all keys should be put into the secret
  1045. syncAndRewriteDataFromFind := func(tc *testCase) {
  1046. tc.externalSecret.Spec.Data = nil
  1047. tc.externalSecret.Spec.DataFrom = []esv1beta1.ExternalSecretDataFromRemoteRef{
  1048. {
  1049. Find: &esv1beta1.ExternalSecretFind{
  1050. Name: &esv1beta1.FindName{
  1051. RegExp: "foobar",
  1052. },
  1053. },
  1054. Rewrite: []esv1beta1.ExternalSecretRewrite{
  1055. {
  1056. Regexp: &esv1beta1.ExternalSecretRewriteRegexp{
  1057. Source: "(.*)",
  1058. Target: "new-$1",
  1059. },
  1060. },
  1061. },
  1062. },
  1063. }
  1064. fakeProvider.WithGetAllSecrets(map[string][]byte{
  1065. "foo": []byte(FooValue),
  1066. "bar": []byte(BarValue),
  1067. }, nil)
  1068. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  1069. // check values
  1070. Expect(string(secret.Data["new-foo"])).To(Equal(FooValue))
  1071. Expect(string(secret.Data["new-bar"])).To(Equal(BarValue))
  1072. }
  1073. }
  1074. // with dataFrom.Find the change is on the called method GetAllSecrets
  1075. // all keys should be put into the secret
  1076. syncDataFromFind := func(tc *testCase) {
  1077. tc.externalSecret.Spec.Data = nil
  1078. tc.externalSecret.Spec.DataFrom = []esv1beta1.ExternalSecretDataFromRemoteRef{
  1079. {
  1080. Find: &esv1beta1.ExternalSecretFind{
  1081. Name: &esv1beta1.FindName{
  1082. RegExp: "foobar",
  1083. },
  1084. },
  1085. },
  1086. }
  1087. fakeProvider.WithGetAllSecrets(map[string][]byte{
  1088. "foo": []byte(FooValue),
  1089. "bar": []byte(BarValue),
  1090. }, nil)
  1091. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  1092. // check values
  1093. Expect(string(secret.Data["foo"])).To(Equal(FooValue))
  1094. Expect(string(secret.Data["bar"])).To(Equal(BarValue))
  1095. }
  1096. }
  1097. // with dataFrom and using a template
  1098. // should be put into the secret
  1099. syncWithDataFromTemplate := func(tc *testCase) {
  1100. tc.externalSecret.Spec.Data = nil
  1101. tc.externalSecret.Spec.Target = esv1beta1.ExternalSecretTarget{
  1102. Name: ExternalSecretTargetSecretName,
  1103. Template: &esv1beta1.ExternalSecretTemplate{
  1104. Type: v1.SecretTypeTLS,
  1105. },
  1106. }
  1107. tc.externalSecret.Spec.DataFrom = []esv1beta1.ExternalSecretDataFromRemoteRef{
  1108. {
  1109. Extract: &esv1beta1.ExternalSecretDataRemoteRef{
  1110. Key: remoteKey,
  1111. },
  1112. },
  1113. }
  1114. fakeProvider.WithGetSecretMap(map[string][]byte{
  1115. "tls.crt": []byte(FooValue),
  1116. "tls.key": []byte(BarValue),
  1117. }, nil)
  1118. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  1119. Expect(secret.Type).To(Equal(v1.SecretTypeTLS))
  1120. // check values
  1121. Expect(string(secret.Data["tls.crt"])).To(Equal(FooValue))
  1122. Expect(string(secret.Data["tls.key"])).To(Equal(BarValue))
  1123. }
  1124. }
  1125. // when a provider errors in a GetSecret call
  1126. // a error condition must be set.
  1127. providerErrCondition := func(tc *testCase) {
  1128. const secretVal = "foobar"
  1129. fakeProvider.WithGetSecret(nil, fmt.Errorf("boom"))
  1130. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Millisecond * 100}
  1131. tc.checkCondition = func(es *esv1beta1.ExternalSecret) bool {
  1132. cond := GetExternalSecretCondition(es.Status, esv1beta1.ExternalSecretReady)
  1133. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1beta1.ConditionReasonSecretSyncedError {
  1134. return false
  1135. }
  1136. return true
  1137. }
  1138. tc.checkExternalSecret = func(es *esv1beta1.ExternalSecret) {
  1139. Eventually(func() bool {
  1140. Expect(syncCallsError.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metric)).To(Succeed())
  1141. Expect(externalSecretReconcileDuration.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metricDuration)).To(Succeed())
  1142. return metric.GetCounter().GetValue() >= 2.0 && metricDuration.GetGauge().GetValue() > 0.0
  1143. }, timeout, interval).Should(BeTrue())
  1144. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1beta1.ExternalSecretReady, v1.ConditionFalse, 1.0)).To(BeTrue())
  1145. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1beta1.ExternalSecretReady, v1.ConditionTrue, 0.0)).To(BeTrue())
  1146. // es condition should reflect recovered provider error
  1147. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  1148. esKey := types.NamespacedName{Name: ExternalSecretName, Namespace: ExternalSecretNamespace}
  1149. Eventually(func() bool {
  1150. err := k8sClient.Get(context.Background(), esKey, es)
  1151. if err != nil {
  1152. return false
  1153. }
  1154. // condition must now be true!
  1155. cond := GetExternalSecretCondition(es.Status, esv1beta1.ExternalSecretReady)
  1156. if cond == nil && cond.Status != v1.ConditionTrue {
  1157. return false
  1158. }
  1159. return true
  1160. }, timeout, interval).Should(BeTrue())
  1161. }
  1162. }
  1163. // When a ExternalSecret references an non-existing SecretStore
  1164. // a error condition must be set.
  1165. storeMissingErrCondition := func(tc *testCase) {
  1166. tc.externalSecret.Spec.SecretStoreRef.Name = "nonexistent"
  1167. tc.checkCondition = func(es *esv1beta1.ExternalSecret) bool {
  1168. cond := GetExternalSecretCondition(es.Status, esv1beta1.ExternalSecretReady)
  1169. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1beta1.ConditionReasonSecretSyncedError {
  1170. return false
  1171. }
  1172. return true
  1173. }
  1174. tc.checkExternalSecret = func(es *esv1beta1.ExternalSecret) {
  1175. Eventually(func() bool {
  1176. Expect(syncCallsError.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metric)).To(Succeed())
  1177. Expect(externalSecretReconcileDuration.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metricDuration)).To(Succeed())
  1178. return metric.GetCounter().GetValue() >= 2.0 && metricDuration.GetGauge().GetValue() > 0.0
  1179. }, timeout, interval).Should(BeTrue())
  1180. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1beta1.ExternalSecretReady, v1.ConditionFalse, 1.0)).To(BeTrue())
  1181. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1beta1.ExternalSecretReady, v1.ConditionTrue, 0.0)).To(BeTrue())
  1182. }
  1183. }
  1184. // when the provider constructor errors (e.g. invalid configuration)
  1185. // a SecretSyncedError status condition must be set
  1186. storeConstructErrCondition := func(tc *testCase) {
  1187. fakeProvider.WithNew(func(context.Context, esv1beta1.GenericStore, client.Client,
  1188. string) (esv1beta1.SecretsClient, error) {
  1189. return nil, fmt.Errorf("artificial constructor error")
  1190. })
  1191. tc.checkCondition = func(es *esv1beta1.ExternalSecret) bool {
  1192. // condition must be false
  1193. cond := GetExternalSecretCondition(es.Status, esv1beta1.ExternalSecretReady)
  1194. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1beta1.ConditionReasonSecretSyncedError {
  1195. return false
  1196. }
  1197. return true
  1198. }
  1199. tc.checkExternalSecret = func(es *esv1beta1.ExternalSecret) {
  1200. Eventually(func() bool {
  1201. Expect(syncCallsError.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metric)).To(Succeed())
  1202. Expect(externalSecretReconcileDuration.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metricDuration)).To(Succeed())
  1203. return metric.GetCounter().GetValue() >= 2.0 && metricDuration.GetGauge().GetValue() > 0.0
  1204. }, timeout, interval).Should(BeTrue())
  1205. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1beta1.ExternalSecretReady, v1.ConditionFalse, 1.0)).To(BeTrue())
  1206. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1beta1.ExternalSecretReady, v1.ConditionTrue, 0.0)).To(BeTrue())
  1207. }
  1208. }
  1209. // when a SecretStore has a controller field set which we don't care about
  1210. // the externalSecret must not be touched
  1211. ignoreMismatchController := func(tc *testCase) {
  1212. tc.secretStore.GetSpec().Controller = "nop"
  1213. tc.checkCondition = func(es *esv1beta1.ExternalSecret) bool {
  1214. cond := GetExternalSecretCondition(es.Status, esv1beta1.ExternalSecretReady)
  1215. return cond == nil
  1216. }
  1217. tc.checkExternalSecret = func(es *esv1beta1.ExternalSecret) {
  1218. // Condition True and False should be 0, since the Condition was not created
  1219. Eventually(func() float64 {
  1220. Expect(externalSecretCondition.WithLabelValues(ExternalSecretName, ExternalSecretNamespace, string(esv1beta1.ExternalSecretReady), string(v1.ConditionTrue)).Write(&metric)).To(Succeed())
  1221. return metric.GetGauge().GetValue()
  1222. }, timeout, interval).Should(Equal(0.0))
  1223. Eventually(func() float64 {
  1224. Expect(externalSecretCondition.WithLabelValues(ExternalSecretName, ExternalSecretNamespace, string(esv1beta1.ExternalSecretReady), string(v1.ConditionFalse)).Write(&metric)).To(Succeed())
  1225. return metric.GetGauge().GetValue()
  1226. }, timeout, interval).Should(Equal(0.0))
  1227. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1beta1.ExternalSecretReady, v1.ConditionFalse, 0.0)).To(BeTrue())
  1228. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1beta1.ExternalSecretReady, v1.ConditionTrue, 0.0)).To(BeTrue())
  1229. }
  1230. }
  1231. ignoreClusterSecretStoreWhenDisabled := func(tc *testCase) {
  1232. tc.externalSecret.Spec.SecretStoreRef.Kind = esv1beta1.ClusterSecretStoreKind
  1233. Expect(shouldSkipClusterSecretStore(
  1234. &Reconciler{
  1235. ClusterSecretStoreEnabled: false,
  1236. },
  1237. *tc.externalSecret,
  1238. )).To(BeTrue())
  1239. tc.checkCondition = func(es *esv1beta1.ExternalSecret) bool {
  1240. cond := GetExternalSecretCondition(es.Status, esv1beta1.ExternalSecretReady)
  1241. return cond == nil
  1242. }
  1243. }
  1244. // When the ownership is set to owner, and we delete a dependent child kind=secret
  1245. // it should be recreated without waiting for refresh interval
  1246. checkDeletion := func(tc *testCase) {
  1247. const secretVal = "someValue"
  1248. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  1249. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Minute * 10}
  1250. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  1251. // check values
  1252. oldUID := secret.UID
  1253. Expect(oldUID).NotTo(BeEmpty())
  1254. // delete the related config
  1255. Expect(k8sClient.Delete(context.TODO(), secret))
  1256. var newSecret v1.Secret
  1257. secretLookupKey := types.NamespacedName{
  1258. Name: ExternalSecretTargetSecretName,
  1259. Namespace: ExternalSecretNamespace,
  1260. }
  1261. Eventually(func() bool {
  1262. err := k8sClient.Get(context.Background(), secretLookupKey, &newSecret)
  1263. if err != nil {
  1264. return false
  1265. }
  1266. // new secret should be a new, recreated object with a different UID
  1267. return newSecret.UID != oldUID
  1268. }, timeout, interval).Should(BeTrue())
  1269. }
  1270. }
  1271. // Checks that secret annotation has been written based on the data
  1272. checkSecretDataHashAnnotation := func(tc *testCase) {
  1273. const secretVal = "someValue"
  1274. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  1275. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  1276. Expect(secret.Annotations[esv1beta1.AnnotationDataHash]).To(Equal("9d30b95ca81e156f9454b5ef3bfcc6ee"))
  1277. }
  1278. }
  1279. // When we amend the created kind=secret, refresh operation should be run again regardless of refresh interval
  1280. checkSecretDataHashAnnotationChange := func(tc *testCase) {
  1281. fakeData := map[string][]byte{
  1282. "targetProperty": []byte(FooValue),
  1283. }
  1284. fakeProvider.WithGetSecretMap(fakeData, nil)
  1285. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Minute * 10}
  1286. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  1287. oldHash := secret.Annotations[esv1beta1.AnnotationDataHash]
  1288. oldResourceVersion := secret.ResourceVersion
  1289. Expect(oldHash).NotTo(BeEmpty())
  1290. cleanSecret := secret.DeepCopy()
  1291. secret.Data["new"] = []byte("value")
  1292. secret.ObjectMeta.Annotations[esv1beta1.AnnotationDataHash] = "thisiswronghash"
  1293. Expect(k8sClient.Patch(context.Background(), secret, client.MergeFrom(cleanSecret))).To(Succeed())
  1294. var refreshedSecret v1.Secret
  1295. secretLookupKey := types.NamespacedName{
  1296. Name: ExternalSecretTargetSecretName,
  1297. Namespace: ExternalSecretNamespace,
  1298. }
  1299. Eventually(func() bool {
  1300. err := k8sClient.Get(context.Background(), secretLookupKey, &refreshedSecret)
  1301. if err != nil {
  1302. return false
  1303. }
  1304. // refreshed secret should have a different generation (sign that it was updated), but since
  1305. // the secret source is the same (not changed), the hash should be reverted to an old value
  1306. return refreshedSecret.ResourceVersion != oldResourceVersion && refreshedSecret.Annotations[esv1beta1.AnnotationDataHash] == oldHash
  1307. }, timeout, interval).Should(BeTrue())
  1308. }
  1309. }
  1310. useClusterSecretStore := func(tc *testCase) {
  1311. tc.secretStore = &esv1beta1.ClusterSecretStore{
  1312. ObjectMeta: metav1.ObjectMeta{
  1313. Name: ExternalSecretStore,
  1314. },
  1315. Spec: esv1beta1.SecretStoreSpec{
  1316. Provider: &esv1beta1.SecretStoreProvider{
  1317. AWS: &esv1beta1.AWSProvider{
  1318. Service: esv1beta1.AWSServiceSecretsManager,
  1319. },
  1320. },
  1321. },
  1322. }
  1323. tc.externalSecret.Spec.SecretStoreRef.Kind = esv1beta1.ClusterSecretStoreKind
  1324. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  1325. }
  1326. // Secret is created when ClusterSecretStore has no conditions
  1327. noConditionsSecretCreated := func(tc *testCase) {
  1328. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  1329. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  1330. }
  1331. }
  1332. // Secret is not created when ClusterSecretStore has a single non-matching string condition
  1333. noSecretCreatedWhenNamespaceDoesntMatchStringCondition := func(tc *testCase) {
  1334. tc.secretStore.GetSpec().Conditions = []esv1beta1.ClusterSecretStoreCondition{
  1335. {
  1336. Namespaces: []string{"some-other-ns"},
  1337. },
  1338. }
  1339. tc.checkCondition = func(es *esv1beta1.ExternalSecret) bool {
  1340. cond := GetExternalSecretCondition(es.Status, esv1beta1.ExternalSecretReady)
  1341. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1beta1.ConditionReasonSecretSyncedError {
  1342. return false
  1343. }
  1344. return true
  1345. }
  1346. }
  1347. // Secret is not created when ClusterSecretStore has a single non-matching string condition with multiple names
  1348. noSecretCreatedWhenNamespaceDoesntMatchStringConditionWithMultipleNames := func(tc *testCase) {
  1349. tc.secretStore.GetSpec().Conditions = []esv1beta1.ClusterSecretStoreCondition{
  1350. {
  1351. Namespaces: []string{"some-other-ns", "another-ns"},
  1352. },
  1353. }
  1354. tc.checkCondition = func(es *esv1beta1.ExternalSecret) bool {
  1355. cond := GetExternalSecretCondition(es.Status, esv1beta1.ExternalSecretReady)
  1356. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1beta1.ConditionReasonSecretSyncedError {
  1357. return false
  1358. }
  1359. return true
  1360. }
  1361. }
  1362. // Secret is not created when ClusterSecretStore has a multiple non-matching string condition
  1363. noSecretCreatedWhenNamespaceDoesntMatchMultipleStringCondition := func(tc *testCase) {
  1364. tc.secretStore.GetSpec().Conditions = []esv1beta1.ClusterSecretStoreCondition{
  1365. {
  1366. Namespaces: []string{"some-other-ns"},
  1367. },
  1368. {
  1369. Namespaces: []string{"another-ns"},
  1370. },
  1371. }
  1372. tc.checkCondition = func(es *esv1beta1.ExternalSecret) bool {
  1373. cond := GetExternalSecretCondition(es.Status, esv1beta1.ExternalSecretReady)
  1374. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1beta1.ConditionReasonSecretSyncedError {
  1375. return false
  1376. }
  1377. return true
  1378. }
  1379. }
  1380. // Secret is created when ClusterSecretStore has a single matching string condition
  1381. secretCreatedWhenNamespaceMatchesSingleStringCondition := func(tc *testCase) {
  1382. tc.secretStore.GetSpec().Conditions = []esv1beta1.ClusterSecretStoreCondition{
  1383. {
  1384. Namespaces: []string{ExternalSecretNamespace},
  1385. },
  1386. }
  1387. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  1388. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  1389. }
  1390. }
  1391. // Secret is created when ClusterSecretStore has a multiple string conditions, one matching
  1392. secretCreatedWhenNamespaceMatchesMultipleStringConditions := func(tc *testCase) {
  1393. tc.secretStore.GetSpec().Conditions = []esv1beta1.ClusterSecretStoreCondition{
  1394. {
  1395. Namespaces: []string{ExternalSecretNamespace, "some-other-ns"},
  1396. },
  1397. }
  1398. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  1399. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  1400. }
  1401. }
  1402. // Secret is not created when ClusterSecretStore has a single non-matching label condition
  1403. noSecretCreatedWhenNamespaceDoesntMatchLabelCondition := func(tc *testCase) {
  1404. tc.secretStore.GetSpec().Conditions = []esv1beta1.ClusterSecretStoreCondition{
  1405. {
  1406. NamespaceSelector: &metav1.LabelSelector{MatchLabels: map[string]string{"some-label-key": "some-label-value"}},
  1407. },
  1408. }
  1409. tc.checkCondition = func(es *esv1beta1.ExternalSecret) bool {
  1410. cond := GetExternalSecretCondition(es.Status, esv1beta1.ExternalSecretReady)
  1411. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1beta1.ConditionReasonSecretSyncedError {
  1412. return false
  1413. }
  1414. return true
  1415. }
  1416. }
  1417. // Secret is created when ClusterSecretStore has a single matching label condition
  1418. secretCreatedWhenNamespaceMatchOnlyLabelCondition := func(tc *testCase) {
  1419. tc.secretStore.GetSpec().Conditions = []esv1beta1.ClusterSecretStoreCondition{
  1420. {
  1421. NamespaceSelector: &metav1.LabelSelector{MatchLabels: map[string]string{NamespaceLabelKey: NamespaceLabelValue}},
  1422. },
  1423. }
  1424. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  1425. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  1426. }
  1427. }
  1428. // Secret is not created when ClusterSecretStore has a partially matching label condition
  1429. noSecretCreatedWhenNamespacePartiallyMatchLabelCondition := func(tc *testCase) {
  1430. tc.secretStore.GetSpec().Conditions = []esv1beta1.ClusterSecretStoreCondition{
  1431. {
  1432. NamespaceSelector: &metav1.LabelSelector{MatchLabels: map[string]string{NamespaceLabelKey: NamespaceLabelValue, "some-label-key": "some-label-value"}},
  1433. },
  1434. }
  1435. tc.checkCondition = func(es *esv1beta1.ExternalSecret) bool {
  1436. cond := GetExternalSecretCondition(es.Status, esv1beta1.ExternalSecretReady)
  1437. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1beta1.ConditionReasonSecretSyncedError {
  1438. return false
  1439. }
  1440. return true
  1441. }
  1442. }
  1443. // Secret is created when ClusterSecretStore has at least one matching label condition
  1444. secretCreatedWhenNamespaceMatchOneLabelCondition := func(tc *testCase) {
  1445. tc.secretStore.GetSpec().Conditions = []esv1beta1.ClusterSecretStoreCondition{
  1446. {
  1447. NamespaceSelector: &metav1.LabelSelector{MatchLabels: map[string]string{NamespaceLabelKey: NamespaceLabelValue}},
  1448. },
  1449. {
  1450. NamespaceSelector: &metav1.LabelSelector{MatchLabels: map[string]string{"some-label-key": "some-label-value"}},
  1451. },
  1452. }
  1453. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  1454. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  1455. }
  1456. }
  1457. // Secret is created when ClusterSecretStore has multiple matching conditions
  1458. secretCreatedWhenNamespaceMatchMultipleConditions := func(tc *testCase) {
  1459. tc.secretStore.GetSpec().Conditions = []esv1beta1.ClusterSecretStoreCondition{
  1460. {
  1461. NamespaceSelector: &metav1.LabelSelector{MatchLabels: map[string]string{NamespaceLabelKey: NamespaceLabelValue}},
  1462. },
  1463. {
  1464. Namespaces: []string{ExternalSecretNamespace},
  1465. },
  1466. }
  1467. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  1468. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  1469. }
  1470. }
  1471. // Secret is not created when ClusterSecretStore has multiple non-matching conditions
  1472. noSecretCreatedWhenNamespaceMatchMultipleNonMatchingConditions := func(tc *testCase) {
  1473. tc.secretStore.GetSpec().Conditions = []esv1beta1.ClusterSecretStoreCondition{
  1474. {
  1475. NamespaceSelector: &metav1.LabelSelector{MatchLabels: map[string]string{"some-label-key": "some-label-value"}},
  1476. },
  1477. {
  1478. Namespaces: []string{"some-other-ns"},
  1479. },
  1480. }
  1481. tc.checkCondition = func(es *esv1beta1.ExternalSecret) bool {
  1482. cond := GetExternalSecretCondition(es.Status, esv1beta1.ExternalSecretReady)
  1483. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1beta1.ConditionReasonSecretSyncedError {
  1484. return false
  1485. }
  1486. return true
  1487. }
  1488. }
  1489. DescribeTable("When reconciling an ExternalSecret",
  1490. func(tweaks ...testTweaks) {
  1491. tc := makeDefaultTestcase()
  1492. for _, tweak := range tweaks {
  1493. tweak(tc)
  1494. }
  1495. ctx := context.Background()
  1496. By("creating a secret store and external secret")
  1497. Expect(k8sClient.Create(ctx, tc.secretStore)).To(Succeed())
  1498. Expect(k8sClient.Create(ctx, tc.externalSecret)).Should(Succeed())
  1499. esKey := types.NamespacedName{Name: ExternalSecretName, Namespace: ExternalSecretNamespace}
  1500. createdES := &esv1beta1.ExternalSecret{}
  1501. By("checking the es condition")
  1502. Eventually(func() bool {
  1503. err := k8sClient.Get(ctx, esKey, createdES)
  1504. if err != nil {
  1505. return false
  1506. }
  1507. return tc.checkCondition(createdES)
  1508. }, timeout, interval).Should(BeTrue())
  1509. tc.checkExternalSecret(createdES)
  1510. // this must be optional so we can test faulty es configuration
  1511. if tc.checkSecret != nil {
  1512. syncedSecret := &v1.Secret{}
  1513. secretLookupKey := types.NamespacedName{
  1514. Name: ExternalSecretTargetSecretName,
  1515. Namespace: ExternalSecretNamespace,
  1516. }
  1517. if createdES.Spec.Target.Name == "" {
  1518. secretLookupKey = types.NamespacedName{
  1519. Name: ExternalSecretName,
  1520. Namespace: ExternalSecretNamespace,
  1521. }
  1522. }
  1523. Eventually(func() bool {
  1524. err := k8sClient.Get(ctx, secretLookupKey, syncedSecret)
  1525. return err == nil
  1526. }, timeout, interval).Should(BeTrue())
  1527. tc.checkSecret(createdES, syncedSecret)
  1528. }
  1529. },
  1530. Entry("should recreate deleted secret", checkDeletion),
  1531. Entry("should create proper hash annotation for the external secret", checkSecretDataHashAnnotation),
  1532. Entry("should refresh when the hash annotation doesn't correspond to secret data", checkSecretDataHashAnnotationChange),
  1533. Entry("should use external secret name if target secret name isn't defined", syncWithoutTargetName),
  1534. Entry("should set the condition eventually", syncLabelsAnnotations),
  1535. Entry("should set prometheus counters", checkPrometheusCounters),
  1536. Entry("should merge with existing secret using creationPolicy=Merge", mergeWithSecret),
  1537. Entry("should error if secret doesn't exist when using creationPolicy=Merge", mergeWithSecretErr),
  1538. Entry("should not resolve conflicts with creationPolicy=Merge", mergeWithConflict),
  1539. Entry("should not update unchanged secret using creationPolicy=Merge", mergeWithSecretNoChange),
  1540. Entry("should not delete pre-existing secret with creationPolicy=Orphan", createSecretPolicyOrphan),
  1541. Entry("should sync with template", syncWithTemplate),
  1542. Entry("should sync with template engine v2", syncWithTemplateV2),
  1543. Entry("should sync template with correct value precedence", syncWithTemplatePrecedence),
  1544. Entry("should refresh secret from template", refreshWithTemplate),
  1545. Entry("should be able to use only metadata from template", onlyMetadataFromTemplate),
  1546. Entry("should refresh secret value when provider secret changes", refreshSecretValue),
  1547. Entry("should refresh secret map when provider secret changes", refreshSecretValueMap),
  1548. Entry("should refresh secret map when provider secret changes when using a template", refreshSecretValueMapTemplate),
  1549. Entry("should not refresh secret value when provider secret changes but refreshInterval is zero", refreshintervalZero),
  1550. Entry("should fetch secret using dataFrom", syncWithDataFrom),
  1551. Entry("should rewrite secret using dataFrom", syncAndRewriteWithDataFrom),
  1552. Entry("should not automatically convert from extract if rewrite is used", invalidExtractKeysErrCondition),
  1553. Entry("should fetch secret using dataFrom.find", syncDataFromFind),
  1554. Entry("should rewrite secret using dataFrom.find", syncAndRewriteDataFromFind),
  1555. Entry("should not automatically convert from find if rewrite is used", invalidFindKeysErrCondition),
  1556. Entry("should fetch secret using dataFrom and a template", syncWithDataFromTemplate),
  1557. Entry("should set error condition when provider errors", providerErrCondition),
  1558. Entry("should set an error condition when store does not exist", storeMissingErrCondition),
  1559. Entry("should set an error condition when store provider constructor fails", storeConstructErrCondition),
  1560. Entry("should not process store with mismatching controller field", ignoreMismatchController),
  1561. Entry("should not process cluster secret store when it is disabled", ignoreClusterSecretStoreWhenDisabled),
  1562. Entry("should eventually delete target secret with deletionPolicy=Delete", deleteSecretPolicy),
  1563. Entry("should not delete target secret with deletionPolicy=Retain", deleteSecretPolicyRetain),
  1564. Entry("should not delete pre-existing secret with deletionPolicy=Merge", deleteSecretPolicyMerge),
  1565. Entry("secret is created when there are no conditions for the cluster secret store", useClusterSecretStore, noConditionsSecretCreated),
  1566. Entry("secret is not created when the condition for the cluster secret store states a different namespace single string condition", useClusterSecretStore, noSecretCreatedWhenNamespaceDoesntMatchStringCondition),
  1567. 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),
  1568. Entry("secret is not created when the condition for the cluster secret store states a different namespace multiple string conditions", useClusterSecretStore, noSecretCreatedWhenNamespaceDoesntMatchMultipleStringCondition),
  1569. Entry("secret is created when the condition for the cluster secret store has only one matching namespace by string condition", useClusterSecretStore, secretCreatedWhenNamespaceMatchesSingleStringCondition),
  1570. Entry("secret is created when the condition for the cluster secret store has one matching namespace of multiple namespaces by string condition", useClusterSecretStore, secretCreatedWhenNamespaceMatchesMultipleStringConditions),
  1571. Entry("secret is not created when the condition for the cluster secret store states a non-matching label condition", useClusterSecretStore, noSecretCreatedWhenNamespaceDoesntMatchLabelCondition),
  1572. Entry("secret is created when the condition for the cluster secret store states a single matching label condition", useClusterSecretStore, secretCreatedWhenNamespaceMatchOnlyLabelCondition),
  1573. Entry("secret is not created when the condition for the cluster secret store states a partially-matching label condition", useClusterSecretStore, noSecretCreatedWhenNamespacePartiallyMatchLabelCondition),
  1574. Entry("secret is created when one of the label conditions for the cluster secret store matches", useClusterSecretStore, secretCreatedWhenNamespaceMatchOneLabelCondition),
  1575. Entry("secret is created when the namespaces matches multiple cluster secret store conditions", useClusterSecretStore, secretCreatedWhenNamespaceMatchMultipleConditions),
  1576. Entry("secret is not created when the namespaces doesn't match any of multiple cluster secret store conditions", useClusterSecretStore, noSecretCreatedWhenNamespaceMatchMultipleNonMatchingConditions),
  1577. )
  1578. })
  1579. var _ = Describe("ExternalSecret refresh logic", func() {
  1580. Context("secret refresh", func() {
  1581. It("should refresh when resource version does not match", func() {
  1582. Expect(shouldRefresh(esv1beta1.ExternalSecret{
  1583. Status: esv1beta1.ExternalSecretStatus{
  1584. SyncedResourceVersion: "some resource version",
  1585. },
  1586. })).To(BeTrue())
  1587. })
  1588. It("should refresh when labels change", func() {
  1589. es := esv1beta1.ExternalSecret{
  1590. ObjectMeta: metav1.ObjectMeta{
  1591. Generation: 1,
  1592. Labels: map[string]string{
  1593. "foo": "bar",
  1594. },
  1595. },
  1596. Spec: esv1beta1.ExternalSecretSpec{
  1597. RefreshInterval: &metav1.Duration{Duration: time.Minute},
  1598. },
  1599. Status: esv1beta1.ExternalSecretStatus{
  1600. RefreshTime: metav1.Now(),
  1601. },
  1602. }
  1603. es.Status.SyncedResourceVersion = getResourceVersion(es)
  1604. // this should not refresh, rv matches object
  1605. Expect(shouldRefresh(es)).To(BeFalse())
  1606. // change labels without changing the syncedResourceVersion and expect refresh
  1607. es.ObjectMeta.Labels["new"] = "w00t"
  1608. Expect(shouldRefresh(es)).To(BeTrue())
  1609. })
  1610. It("should refresh when annotations change", func() {
  1611. es := esv1beta1.ExternalSecret{
  1612. ObjectMeta: metav1.ObjectMeta{
  1613. Generation: 1,
  1614. Annotations: map[string]string{
  1615. "foo": "bar",
  1616. },
  1617. },
  1618. Spec: esv1beta1.ExternalSecretSpec{
  1619. RefreshInterval: &metav1.Duration{Duration: time.Minute},
  1620. },
  1621. Status: esv1beta1.ExternalSecretStatus{
  1622. RefreshTime: metav1.Now(),
  1623. },
  1624. }
  1625. es.Status.SyncedResourceVersion = getResourceVersion(es)
  1626. // this should not refresh, rv matches object
  1627. Expect(shouldRefresh(es)).To(BeFalse())
  1628. // change annotations without changing the syncedResourceVersion and expect refresh
  1629. es.ObjectMeta.Annotations["new"] = "w00t"
  1630. Expect(shouldRefresh(es)).To(BeTrue())
  1631. })
  1632. It("should refresh when generation has changed", func() {
  1633. es := esv1beta1.ExternalSecret{
  1634. ObjectMeta: metav1.ObjectMeta{
  1635. Generation: 1,
  1636. },
  1637. Spec: esv1beta1.ExternalSecretSpec{
  1638. RefreshInterval: &metav1.Duration{Duration: 0},
  1639. },
  1640. Status: esv1beta1.ExternalSecretStatus{
  1641. RefreshTime: metav1.Now(),
  1642. },
  1643. }
  1644. es.Status.SyncedResourceVersion = getResourceVersion(es)
  1645. Expect(shouldRefresh(es)).To(BeFalse())
  1646. // update gen -> refresh
  1647. es.ObjectMeta.Generation = 2
  1648. Expect(shouldRefresh(es)).To(BeTrue())
  1649. })
  1650. It("should skip refresh when refreshInterval is 0", func() {
  1651. es := esv1beta1.ExternalSecret{
  1652. ObjectMeta: metav1.ObjectMeta{
  1653. Generation: 1,
  1654. },
  1655. Spec: esv1beta1.ExternalSecretSpec{
  1656. RefreshInterval: &metav1.Duration{Duration: 0},
  1657. },
  1658. Status: esv1beta1.ExternalSecretStatus{},
  1659. }
  1660. // resource version matches
  1661. es.Status.SyncedResourceVersion = getResourceVersion(es)
  1662. Expect(shouldRefresh(es)).To(BeFalse())
  1663. })
  1664. It("should refresh when refresh interval has passed", func() {
  1665. es := esv1beta1.ExternalSecret{
  1666. ObjectMeta: metav1.ObjectMeta{
  1667. Generation: 1,
  1668. },
  1669. Spec: esv1beta1.ExternalSecretSpec{
  1670. RefreshInterval: &metav1.Duration{Duration: time.Second},
  1671. },
  1672. Status: esv1beta1.ExternalSecretStatus{
  1673. RefreshTime: metav1.NewTime(metav1.Now().Add(-time.Second * 5)),
  1674. },
  1675. }
  1676. // resource version matches
  1677. es.Status.SyncedResourceVersion = getResourceVersion(es)
  1678. Expect(shouldRefresh(es)).To(BeTrue())
  1679. })
  1680. It("should refresh when no refresh time was set", func() {
  1681. es := esv1beta1.ExternalSecret{
  1682. ObjectMeta: metav1.ObjectMeta{
  1683. Generation: 1,
  1684. },
  1685. Spec: esv1beta1.ExternalSecretSpec{
  1686. RefreshInterval: &metav1.Duration{Duration: time.Second},
  1687. },
  1688. Status: esv1beta1.ExternalSecretStatus{},
  1689. }
  1690. // resource version matches
  1691. es.Status.SyncedResourceVersion = getResourceVersion(es)
  1692. Expect(shouldRefresh(es)).To(BeTrue())
  1693. })
  1694. })
  1695. Context("objectmeta hash", func() {
  1696. It("should produce different hashes for different k/v pairs", func() {
  1697. h1 := hashMeta(metav1.ObjectMeta{
  1698. Generation: 1,
  1699. Annotations: map[string]string{
  1700. "foo": "bar",
  1701. },
  1702. })
  1703. h2 := hashMeta(metav1.ObjectMeta{
  1704. Generation: 1,
  1705. Annotations: map[string]string{
  1706. "foo": "bing",
  1707. },
  1708. })
  1709. Expect(h1).ToNot(Equal(h2))
  1710. })
  1711. It("should produce different hashes for different generations but same label/annotations", func() {
  1712. h1 := hashMeta(metav1.ObjectMeta{
  1713. Generation: 1,
  1714. Annotations: map[string]string{
  1715. "foo": "bar",
  1716. },
  1717. Labels: map[string]string{
  1718. "foo": "bar",
  1719. },
  1720. })
  1721. h2 := hashMeta(metav1.ObjectMeta{
  1722. Generation: 2,
  1723. Annotations: map[string]string{
  1724. "foo": "bar",
  1725. },
  1726. Labels: map[string]string{
  1727. "foo": "bar",
  1728. },
  1729. })
  1730. Expect(h1).To(Equal(h2))
  1731. })
  1732. It("should produce the same hash for the same k/v pairs", func() {
  1733. h1 := hashMeta(metav1.ObjectMeta{
  1734. Generation: 1,
  1735. })
  1736. h2 := hashMeta(metav1.ObjectMeta{
  1737. Generation: 1,
  1738. })
  1739. Expect(h1).To(Equal(h2))
  1740. h1 = hashMeta(metav1.ObjectMeta{
  1741. Generation: 1,
  1742. Annotations: map[string]string{
  1743. "foo": "bar",
  1744. },
  1745. })
  1746. h2 = hashMeta(metav1.ObjectMeta{
  1747. Generation: 1,
  1748. Annotations: map[string]string{
  1749. "foo": "bar",
  1750. },
  1751. })
  1752. Expect(h1).To(Equal(h2))
  1753. })
  1754. })
  1755. })
  1756. var _ = Describe("Controller Reconcile logic", func() {
  1757. Context("controller reconcile", func() {
  1758. It("should reconcile when resource is not synced", func() {
  1759. Expect(shouldReconcile(esv1beta1.ExternalSecret{
  1760. Status: esv1beta1.ExternalSecretStatus{
  1761. SyncedResourceVersion: "some resource version",
  1762. Conditions: []esv1beta1.ExternalSecretStatusCondition{{Reason: "NotASecretSynced"}},
  1763. },
  1764. })).To(BeTrue())
  1765. })
  1766. It("should reconcile when secret isn't immutable", func() {
  1767. Expect(shouldReconcile(esv1beta1.ExternalSecret{
  1768. Spec: esv1beta1.ExternalSecretSpec{
  1769. Target: esv1beta1.ExternalSecretTarget{
  1770. Immutable: false,
  1771. },
  1772. },
  1773. })).To(BeTrue())
  1774. })
  1775. It("should not reconcile if secret is immutable and has synced condition", func() {
  1776. Expect(shouldReconcile(esv1beta1.ExternalSecret{
  1777. Spec: esv1beta1.ExternalSecretSpec{
  1778. Target: esv1beta1.ExternalSecretTarget{
  1779. Immutable: true,
  1780. },
  1781. },
  1782. Status: esv1beta1.ExternalSecretStatus{
  1783. SyncedResourceVersion: "some resource version",
  1784. Conditions: []esv1beta1.ExternalSecretStatusCondition{{Reason: "SecretSynced"}},
  1785. },
  1786. })).To(BeFalse())
  1787. })
  1788. })
  1789. })
  1790. func externalSecretConditionShouldBe(name, ns string, ct esv1beta1.ExternalSecretConditionType, cs v1.ConditionStatus, v float64) bool {
  1791. return Eventually(func() float64 {
  1792. Expect(externalSecretCondition.WithLabelValues(name, ns, string(ct), string(cs)).Write(&metric)).To(Succeed())
  1793. return metric.GetGauge().GetValue()
  1794. }, timeout, interval).Should(Equal(v))
  1795. }
  1796. func init() {
  1797. fakeProvider = fake.New()
  1798. esv1beta1.ForceRegister(fakeProvider, &esv1beta1.SecretStoreProvider{
  1799. AWS: &esv1beta1.AWSProvider{
  1800. Service: esv1beta1.AWSServiceSecretsManager,
  1801. },
  1802. })
  1803. }