externalsecret_controller_test.go 55 KB

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