externalsecret_controller_test.go 55 KB

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