externalsecret_controller_test.go 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273
  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. "context"
  15. "fmt"
  16. "os"
  17. "strconv"
  18. "time"
  19. . "github.com/onsi/ginkgo/v2"
  20. . "github.com/onsi/gomega"
  21. dto "github.com/prometheus/client_model/go"
  22. v1 "k8s.io/api/core/v1"
  23. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  24. "k8s.io/apimachinery/pkg/types"
  25. "k8s.io/apimachinery/pkg/util/wait"
  26. "sigs.k8s.io/controller-runtime/pkg/client"
  27. esv1alpha1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1alpha1"
  28. "github.com/external-secrets/external-secrets/pkg/provider"
  29. "github.com/external-secrets/external-secrets/pkg/provider/fake"
  30. "github.com/external-secrets/external-secrets/pkg/provider/schema"
  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 *esv1alpha1.SecretStore
  40. externalSecret *esv1alpha1.ExternalSecret
  41. // checkCondition should return true if the externalSecret
  42. // has the expected condition
  43. checkCondition func(*esv1alpha1.ExternalSecret) bool
  44. // checkExternalSecret is called after the condition has been verified
  45. // use this to verify the externalSecret
  46. checkExternalSecret func(*esv1alpha1.ExternalSecret)
  47. // optional. use this to test the secret value
  48. checkSecret func(*esv1alpha1.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. esv1alpha1.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. esv1alpha1.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 = CreateNamespace("test-ns", k8sClient)
  139. Expect(err).ToNot(HaveOccurred())
  140. metric.Reset()
  141. syncCallsTotal.Reset()
  142. syncCallsError.Reset()
  143. externalSecretCondition.Reset()
  144. })
  145. AfterEach(func() {
  146. Expect(k8sClient.Delete(context.Background(), &v1.Namespace{
  147. ObjectMeta: metav1.ObjectMeta{
  148. Name: ExternalSecretNamespace,
  149. },
  150. }, client.PropagationPolicy(metav1.DeletePropagationBackground)), client.GracePeriodSeconds(0)).To(Succeed())
  151. Expect(k8sClient.Delete(context.Background(), &esv1alpha1.SecretStore{
  152. ObjectMeta: metav1.ObjectMeta{
  153. Name: ExternalSecretStore,
  154. Namespace: ExternalSecretNamespace,
  155. },
  156. }, client.PropagationPolicy(metav1.DeletePropagationBackground)), client.GracePeriodSeconds(0)).To(Succeed())
  157. })
  158. const targetProp = "targetProperty"
  159. const remoteKey = "barz"
  160. const remoteProperty = "bang"
  161. makeDefaultTestcase := func() *testCase {
  162. return &testCase{
  163. // default condition: es should be ready
  164. checkCondition: func(es *esv1alpha1.ExternalSecret) bool {
  165. cond := GetExternalSecretCondition(es.Status, esv1alpha1.ExternalSecretReady)
  166. if cond == nil || cond.Status != v1.ConditionTrue {
  167. return false
  168. }
  169. return true
  170. },
  171. checkExternalSecret: func(es *esv1alpha1.ExternalSecret) {},
  172. secretStore: &esv1alpha1.SecretStore{
  173. ObjectMeta: metav1.ObjectMeta{
  174. Name: ExternalSecretStore,
  175. Namespace: ExternalSecretNamespace,
  176. },
  177. Spec: esv1alpha1.SecretStoreSpec{
  178. Provider: &esv1alpha1.SecretStoreProvider{
  179. AWS: &esv1alpha1.AWSProvider{
  180. Service: esv1alpha1.AWSServiceSecretsManager,
  181. },
  182. },
  183. },
  184. },
  185. externalSecret: &esv1alpha1.ExternalSecret{
  186. ObjectMeta: metav1.ObjectMeta{
  187. Name: ExternalSecretName,
  188. Namespace: ExternalSecretNamespace,
  189. },
  190. Spec: esv1alpha1.ExternalSecretSpec{
  191. SecretStoreRef: esv1alpha1.SecretStoreRef{
  192. Name: ExternalSecretStore,
  193. },
  194. Target: esv1alpha1.ExternalSecretTarget{
  195. Name: ExternalSecretTargetSecretName,
  196. },
  197. Data: []esv1alpha1.ExternalSecretData{
  198. {
  199. SecretKey: targetProp,
  200. RemoteRef: esv1alpha1.ExternalSecretDataRemoteRef{
  201. Extract: esv1alpha1.ExternalSecretExtract{
  202. Key: remoteKey,
  203. Property: remoteProperty,
  204. },
  205. },
  206. },
  207. },
  208. },
  209. },
  210. }
  211. }
  212. // if target Secret name is not specified it should use the ExternalSecret name.
  213. syncWithoutTargetName := func(tc *testCase) {
  214. tc.externalSecret.Spec.Target.Name = ""
  215. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  216. // check secret name
  217. Expect(secret.ObjectMeta.Name).To(Equal(ExternalSecretName))
  218. }
  219. }
  220. // labels and annotations from the Kind=ExternalSecret
  221. // should be copied over to the Kind=Secret
  222. syncLabelsAnnotations := func(tc *testCase) {
  223. const secretVal = "someValue"
  224. tc.externalSecret.ObjectMeta.Labels = map[string]string{
  225. "fooobar": "bazz",
  226. }
  227. tc.externalSecret.ObjectMeta.Annotations = map[string]string{
  228. "hihihih": "hehehe",
  229. }
  230. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  231. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  232. // check value
  233. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  234. // check labels & annotations
  235. Expect(secret.ObjectMeta.Labels).To(BeEquivalentTo(es.ObjectMeta.Labels))
  236. for k, v := range es.ObjectMeta.Annotations {
  237. Expect(secret.ObjectMeta.Annotations).To(HaveKeyWithValue(k, v))
  238. }
  239. // ownerRef must not not be set!
  240. Expect(hasOwnerRef(secret.ObjectMeta, "ExternalSecret", ExternalSecretName)).To(BeTrue())
  241. }
  242. }
  243. checkPrometheusCounters := func(tc *testCase) {
  244. const secretVal = "someValue"
  245. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  246. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  247. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1alpha1.ExternalSecretReady, v1.ConditionFalse, 0.0)).To(BeTrue())
  248. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1alpha1.ExternalSecretReady, v1.ConditionTrue, 1.0)).To(BeTrue())
  249. Eventually(func() bool {
  250. Expect(syncCallsTotal.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metric)).To(Succeed())
  251. return metric.GetCounter().GetValue() == 1.0
  252. }, timeout, interval).Should(BeTrue())
  253. }
  254. }
  255. // merge with existing secret using creationPolicy=Merge
  256. // it should NOT have a ownerReference
  257. // metadata.managedFields with the correct owner should be added to the secret
  258. mergeWithSecret := func(tc *testCase) {
  259. const secretVal = "someValue"
  260. const existingKey = "pre-existing-key"
  261. existingVal := "pre-existing-value"
  262. tc.externalSecret.Spec.Target.CreationPolicy = esv1alpha1.Merge
  263. // create secret beforehand
  264. Expect(k8sClient.Create(context.Background(), &v1.Secret{
  265. ObjectMeta: metav1.ObjectMeta{
  266. Name: ExternalSecretTargetSecretName,
  267. Namespace: ExternalSecretNamespace,
  268. },
  269. Data: map[string][]byte{
  270. existingKey: []byte(existingVal),
  271. },
  272. }, client.FieldOwner(FakeManager))).To(Succeed())
  273. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  274. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  275. // check value
  276. Expect(string(secret.Data[existingKey])).To(Equal(existingVal))
  277. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  278. // check labels & annotations
  279. Expect(secret.ObjectMeta.Labels).To(BeEquivalentTo(es.ObjectMeta.Labels))
  280. for k, v := range es.ObjectMeta.Annotations {
  281. Expect(secret.ObjectMeta.Annotations).To(HaveKeyWithValue(k, v))
  282. }
  283. Expect(hasOwnerRef(secret.ObjectMeta, "ExternalSecret", ExternalSecretName)).To(BeFalse())
  284. Expect(secret.ObjectMeta.ManagedFields).To(HaveLen(2))
  285. Expect(hasFieldOwnership(
  286. secret.ObjectMeta,
  287. "external-secrets",
  288. fmt.Sprintf("{\"f:data\":{\"f:targetProperty\":{}},\"f:immutable\":{},\"f:metadata\":{\"f:annotations\":{\"f:%s\":{}}}}", esv1alpha1.AnnotationDataHash)),
  289. ).To(BeTrue())
  290. Expect(hasFieldOwnership(secret.ObjectMeta, FakeManager, "{\"f:data\":{\".\":{},\"f:pre-existing-key\":{}},\"f:type\":{}}")).To(BeTrue())
  291. }
  292. }
  293. // should not update if no changes
  294. mergeWithSecretNoChange := func(tc *testCase) {
  295. const existingKey = "pre-existing-key"
  296. existingVal := "someValue"
  297. tc.externalSecret.Spec.Target.CreationPolicy = esv1alpha1.Merge
  298. // create secret beforehand
  299. Expect(k8sClient.Create(context.Background(), &v1.Secret{
  300. ObjectMeta: metav1.ObjectMeta{
  301. Name: ExternalSecretTargetSecretName,
  302. Namespace: ExternalSecretNamespace,
  303. },
  304. Data: map[string][]byte{
  305. existingKey: []byte(existingVal),
  306. },
  307. }, client.FieldOwner(FakeManager))).To(Succeed())
  308. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  309. oldResourceVersion := secret.ResourceVersion
  310. cleanSecret := secret.DeepCopy()
  311. Expect(k8sClient.Patch(context.Background(), secret, client.MergeFrom(cleanSecret))).To(Succeed())
  312. newSecret := &v1.Secret{}
  313. Eventually(func() bool {
  314. secretLookupKey := types.NamespacedName{
  315. Name: ExternalSecretTargetSecretName,
  316. Namespace: ExternalSecretNamespace,
  317. }
  318. err := k8sClient.Get(context.Background(), secretLookupKey, newSecret)
  319. if err != nil {
  320. return false
  321. }
  322. return oldResourceVersion == newSecret.ResourceVersion
  323. }, timeout, interval).Should(Equal(true))
  324. }
  325. }
  326. // should not merge with secret if it doesn't exist
  327. mergeWithSecretErr := func(tc *testCase) {
  328. const secretVal = "someValue"
  329. tc.externalSecret.Spec.Target.CreationPolicy = esv1alpha1.Merge
  330. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  331. tc.checkCondition = func(es *esv1alpha1.ExternalSecret) bool {
  332. cond := GetExternalSecretCondition(es.Status, esv1alpha1.ExternalSecretReady)
  333. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1alpha1.ConditionReasonSecretSyncedError {
  334. return false
  335. }
  336. return true
  337. }
  338. tc.checkExternalSecret = func(es *esv1alpha1.ExternalSecret) {
  339. Eventually(func() bool {
  340. Expect(syncCallsError.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metric)).To(Succeed())
  341. return metric.GetCounter().GetValue() >= 2.0
  342. }, timeout, interval).Should(BeTrue())
  343. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1alpha1.ExternalSecretReady, v1.ConditionFalse, 1.0)).To(BeTrue())
  344. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1alpha1.ExternalSecretReady, v1.ConditionTrue, 0.0)).To(BeTrue())
  345. }
  346. }
  347. // controller should force ownership
  348. mergeWithConflict := func(tc *testCase) {
  349. const secretVal = "someValue"
  350. // this should confict
  351. const existingKey = targetProp
  352. existingVal := "pre-existing-value"
  353. tc.externalSecret.Spec.Target.CreationPolicy = esv1alpha1.Merge
  354. // create secret beforehand
  355. Expect(k8sClient.Create(context.Background(), &v1.Secret{
  356. ObjectMeta: metav1.ObjectMeta{
  357. Name: ExternalSecretTargetSecretName,
  358. Namespace: ExternalSecretNamespace,
  359. },
  360. Data: map[string][]byte{
  361. existingKey: []byte(existingVal),
  362. },
  363. }, client.FieldOwner(FakeManager))).To(Succeed())
  364. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  365. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  366. // check that value stays the same
  367. Expect(string(secret.Data[existingKey])).To(Equal(secretVal))
  368. // check owner/managedFields
  369. Expect(hasOwnerRef(secret.ObjectMeta, "ExternalSecret", ExternalSecretName)).To(BeFalse())
  370. Expect(secret.ObjectMeta.ManagedFields).To(HaveLen(2))
  371. Expect(hasFieldOwnership(secret.ObjectMeta, "external-secrets", "{\"f:data\":{\"f:targetProperty\":{}},\"f:immutable\":{},\"f:metadata\":{\"f:annotations\":{\"f:reconcile.external-secrets.io/data-hash\":{}}}}")).To(BeTrue())
  372. }
  373. }
  374. // when using a template it should be used as a blueprint
  375. // to construct a new secret: labels, annotations and type
  376. syncWithTemplate := func(tc *testCase) {
  377. const secretVal = "someValue"
  378. const tplStaticKey = "tplstatickey"
  379. const tplStaticVal = "tplstaticvalue"
  380. tc.externalSecret.ObjectMeta.Labels = map[string]string{
  381. "fooobar": "bazz",
  382. }
  383. tc.externalSecret.ObjectMeta.Annotations = map[string]string{
  384. "hihihih": "hehehe",
  385. }
  386. tc.externalSecret.Spec.Target.Template = &esv1alpha1.ExternalSecretTemplate{
  387. Metadata: esv1alpha1.ExternalSecretTemplateMetadata{
  388. Labels: map[string]string{
  389. "foos": "ball",
  390. },
  391. Annotations: map[string]string{
  392. "hihi": "ga",
  393. },
  394. },
  395. Type: v1.SecretTypeOpaque,
  396. Data: map[string]string{
  397. targetProp: targetPropObj,
  398. tplStaticKey: tplStaticVal,
  399. },
  400. }
  401. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  402. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  403. // check values
  404. Expect(string(secret.Data[targetProp])).To(Equal(expectedSecretVal))
  405. Expect(string(secret.Data[tplStaticKey])).To(Equal(tplStaticVal))
  406. // labels/annotations should be taken from the template
  407. Expect(secret.ObjectMeta.Labels).To(BeEquivalentTo(es.Spec.Target.Template.Metadata.Labels))
  408. for k, v := range es.Spec.Target.Template.Metadata.Annotations {
  409. Expect(secret.ObjectMeta.Annotations).To(HaveKeyWithValue(k, v))
  410. }
  411. }
  412. }
  413. // secret should be synced with correct value precedence:
  414. // * template
  415. // * templateFrom
  416. // * data
  417. // * dataFrom
  418. syncWithTemplatePrecedence := func(tc *testCase) {
  419. const secretVal = "someValue"
  420. const tplStaticKey = "tplstatickey"
  421. const tplStaticVal = "tplstaticvalue"
  422. const tplFromCMName = "template-cm"
  423. const tplFromSecretName = "template-secret"
  424. const tplFromKey = "tpl-from-key"
  425. const tplFromSecKey = "tpl-from-sec-key"
  426. const tplFromVal = "tpl-from-value: {{ .targetProperty | toString }} // {{ .bar | toString }}"
  427. const tplFromSecVal = "tpl-from-sec-value: {{ .targetProperty | toString }} // {{ .bar | toString }}"
  428. Expect(k8sClient.Create(context.Background(), &v1.ConfigMap{
  429. ObjectMeta: metav1.ObjectMeta{
  430. Name: tplFromCMName,
  431. Namespace: ExternalSecretNamespace,
  432. },
  433. Data: map[string]string{
  434. tplFromKey: tplFromVal,
  435. },
  436. })).To(Succeed())
  437. Expect(k8sClient.Create(context.Background(), &v1.Secret{
  438. ObjectMeta: metav1.ObjectMeta{
  439. Name: tplFromSecretName,
  440. Namespace: ExternalSecretNamespace,
  441. },
  442. Data: map[string][]byte{
  443. tplFromSecKey: []byte(tplFromSecVal),
  444. },
  445. })).To(Succeed())
  446. tc.externalSecret.Spec.Target.Template = &esv1alpha1.ExternalSecretTemplate{
  447. Metadata: esv1alpha1.ExternalSecretTemplateMetadata{},
  448. Type: v1.SecretTypeOpaque,
  449. TemplateFrom: []esv1alpha1.TemplateFrom{
  450. {
  451. ConfigMap: &esv1alpha1.TemplateRef{
  452. Name: tplFromCMName,
  453. Items: []esv1alpha1.TemplateRefItem{
  454. {
  455. Key: tplFromKey,
  456. },
  457. },
  458. },
  459. },
  460. {
  461. Secret: &esv1alpha1.TemplateRef{
  462. Name: tplFromSecretName,
  463. Items: []esv1alpha1.TemplateRefItem{
  464. {
  465. Key: tplFromSecKey,
  466. },
  467. },
  468. },
  469. },
  470. },
  471. Data: map[string]string{
  472. // this should be the data value, not dataFrom
  473. targetProp: targetPropObj,
  474. // this should use the value from the map
  475. "bar": "value from map: {{ .bar | toString }}",
  476. // just a static value
  477. tplStaticKey: tplStaticVal,
  478. },
  479. }
  480. tc.externalSecret.Spec.DataFrom = []esv1alpha1.ExternalSecretDataRemoteRef{
  481. {
  482. Extract: esv1alpha1.ExternalSecretExtract{
  483. Key: "datamap",
  484. },
  485. },
  486. }
  487. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  488. fakeProvider.WithGetSecretMap(map[string][]byte{
  489. "targetProperty": []byte(FooValue),
  490. "bar": []byte(BarValue),
  491. }, nil)
  492. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  493. // check values
  494. Expect(string(secret.Data[targetProp])).To(Equal(expectedSecretVal))
  495. Expect(string(secret.Data[tplStaticKey])).To(Equal(tplStaticVal))
  496. Expect(string(secret.Data["bar"])).To(Equal("value from map: map-bar-value"))
  497. Expect(string(secret.Data[tplFromKey])).To(Equal("tpl-from-value: someValue // map-bar-value"))
  498. Expect(string(secret.Data[tplFromSecKey])).To(Equal("tpl-from-sec-value: someValue // map-bar-value"))
  499. }
  500. }
  501. refreshWithTemplate := func(tc *testCase) {
  502. const secretVal = "someValue"
  503. const tplStaticKey = "tplstatickey"
  504. const tplStaticVal = "tplstaticvalue"
  505. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Second}
  506. tc.externalSecret.Spec.Target.Template = &esv1alpha1.ExternalSecretTemplate{
  507. Metadata: esv1alpha1.ExternalSecretTemplateMetadata{
  508. Labels: map[string]string{"foo": "bar"},
  509. Annotations: map[string]string{"foo": "bar"},
  510. },
  511. Type: v1.SecretTypeOpaque,
  512. Data: map[string]string{
  513. targetProp: targetPropObj,
  514. tplStaticKey: tplStaticVal,
  515. },
  516. }
  517. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  518. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  519. // check values
  520. Expect(string(secret.Data[targetProp])).To(Equal(expectedSecretVal))
  521. Expect(string(secret.Data[tplStaticKey])).To(Equal(tplStaticVal))
  522. // labels/annotations should be taken from the template
  523. Expect(secret.ObjectMeta.Labels).To(BeEquivalentTo(es.Spec.Target.Template.Metadata.Labels))
  524. // a secret will always have some extra annotations (i.e. hashmap check), so we only check for specific
  525. // source annotations
  526. for k, v := range es.Spec.Target.Template.Metadata.Annotations {
  527. Expect(secret.ObjectMeta.Annotations).To(HaveKeyWithValue(k, v))
  528. }
  529. cleanEs := tc.externalSecret.DeepCopy()
  530. // now update ExternalSecret
  531. tc.externalSecret.Spec.Target.Template.Metadata.Annotations["fuzz"] = "buzz"
  532. tc.externalSecret.Spec.Target.Template.Metadata.Labels["fuzz"] = "buzz"
  533. tc.externalSecret.Spec.Target.Template.Data["new"] = "value"
  534. Expect(k8sClient.Patch(context.Background(), tc.externalSecret, client.MergeFrom(cleanEs))).To(Succeed())
  535. // wait for secret
  536. sec := &v1.Secret{}
  537. secretLookupKey := types.NamespacedName{
  538. Name: ExternalSecretTargetSecretName,
  539. Namespace: ExternalSecretNamespace,
  540. }
  541. Eventually(func() bool {
  542. err := k8sClient.Get(context.Background(), secretLookupKey, sec)
  543. if err != nil {
  544. return false
  545. }
  546. // ensure new data value exist
  547. return string(sec.Data["new"]) == "value"
  548. }, time.Second*10, time.Millisecond*200).Should(BeTrue())
  549. // also check labels/annotations have been updated
  550. Expect(secret.ObjectMeta.Labels).To(BeEquivalentTo(es.Spec.Target.Template.Metadata.Labels))
  551. for k, v := range es.Spec.Target.Template.Metadata.Annotations {
  552. Expect(secret.ObjectMeta.Annotations).To(HaveKeyWithValue(k, v))
  553. }
  554. }
  555. }
  556. onlyMetadataFromTemplate := func(tc *testCase) {
  557. const secretVal = "someValue"
  558. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Second}
  559. tc.externalSecret.Spec.Target.Template = &esv1alpha1.ExternalSecretTemplate{
  560. Metadata: esv1alpha1.ExternalSecretTemplateMetadata{
  561. Labels: map[string]string{"foo": "bar"},
  562. Annotations: map[string]string{"foo": "bar"},
  563. },
  564. }
  565. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  566. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  567. // check values
  568. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  569. // labels/annotations should be taken from the template
  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. // when the provider secret changes the Kind=Secret value
  577. // must change, too.
  578. refreshSecretValue := func(tc *testCase) {
  579. const targetProp = "targetProperty"
  580. const secretVal = "someValue"
  581. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  582. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Second}
  583. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  584. // check values
  585. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  586. // update provider secret
  587. newValue := "NEW VALUE"
  588. sec := &v1.Secret{}
  589. fakeProvider.WithGetSecret([]byte(newValue), nil)
  590. secretLookupKey := types.NamespacedName{
  591. Name: ExternalSecretTargetSecretName,
  592. Namespace: ExternalSecretNamespace,
  593. }
  594. Eventually(func() bool {
  595. err := k8sClient.Get(context.Background(), secretLookupKey, sec)
  596. if err != nil {
  597. return false
  598. }
  599. v := sec.Data[targetProp]
  600. return string(v) == newValue
  601. }, timeout, interval).Should(BeTrue())
  602. }
  603. }
  604. refreshintervalZero := func(tc *testCase) {
  605. const targetProp = "targetProperty"
  606. const secretVal = "someValue"
  607. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  608. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: 0}
  609. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  610. // check values
  611. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  612. // update provider secret
  613. newValue := "NEW VALUE"
  614. sec := &v1.Secret{}
  615. fakeProvider.WithGetSecret([]byte(newValue), nil)
  616. secretLookupKey := types.NamespacedName{
  617. Name: ExternalSecretTargetSecretName,
  618. Namespace: ExternalSecretNamespace,
  619. }
  620. Consistently(func() bool {
  621. err := k8sClient.Get(context.Background(), secretLookupKey, sec)
  622. if err != nil {
  623. return false
  624. }
  625. v := sec.Data[targetProp]
  626. return string(v) == secretVal
  627. }, time.Second*10, time.Second).Should(BeTrue())
  628. }
  629. }
  630. // with dataFrom all properties from the specified secret
  631. // should be put into the secret
  632. syncWithDataFrom := func(tc *testCase) {
  633. tc.externalSecret.Spec.Data = nil
  634. tc.externalSecret.Spec.DataFrom = []esv1alpha1.ExternalSecretDataRemoteRef{
  635. {
  636. Extract: esv1alpha1.ExternalSecretExtract{
  637. Key: remoteKey,
  638. },
  639. },
  640. }
  641. fakeProvider.WithGetSecretMap(map[string][]byte{
  642. "foo": []byte(FooValue),
  643. "bar": []byte(BarValue),
  644. }, nil)
  645. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  646. // check values
  647. Expect(string(secret.Data["foo"])).To(Equal(FooValue))
  648. Expect(string(secret.Data["bar"])).To(Equal(BarValue))
  649. }
  650. }
  651. // with dataFrom and using a template
  652. // should be put into the secret
  653. syncWithDataFromTemplate := func(tc *testCase) {
  654. tc.externalSecret.Spec.Data = nil
  655. tc.externalSecret.Spec.Target = esv1alpha1.ExternalSecretTarget{
  656. Name: ExternalSecretTargetSecretName,
  657. Template: &esv1alpha1.ExternalSecretTemplate{
  658. Type: v1.SecretTypeTLS,
  659. },
  660. }
  661. tc.externalSecret.Spec.DataFrom = []esv1alpha1.ExternalSecretDataRemoteRef{
  662. {
  663. Extract: esv1alpha1.ExternalSecretExtract{
  664. Key: remoteKey,
  665. },
  666. },
  667. }
  668. fakeProvider.WithGetSecretMap(map[string][]byte{
  669. "tls.crt": []byte(FooValue),
  670. "tls.key": []byte(BarValue),
  671. }, nil)
  672. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  673. Expect(secret.Type).To(Equal(v1.SecretTypeTLS))
  674. // check values
  675. Expect(string(secret.Data["tls.crt"])).To(Equal(FooValue))
  676. Expect(string(secret.Data["tls.key"])).To(Equal(BarValue))
  677. }
  678. }
  679. // when a provider errors in a GetSecret call
  680. // a error condition must be set.
  681. providerErrCondition := func(tc *testCase) {
  682. const secretVal = "foobar"
  683. fakeProvider.WithGetSecret(nil, fmt.Errorf("boom"))
  684. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Millisecond * 100}
  685. tc.checkCondition = func(es *esv1alpha1.ExternalSecret) bool {
  686. cond := GetExternalSecretCondition(es.Status, esv1alpha1.ExternalSecretReady)
  687. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1alpha1.ConditionReasonSecretSyncedError {
  688. return false
  689. }
  690. return true
  691. }
  692. tc.checkExternalSecret = func(es *esv1alpha1.ExternalSecret) {
  693. Eventually(func() bool {
  694. Expect(syncCallsError.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metric)).To(Succeed())
  695. return metric.GetCounter().GetValue() >= 2.0
  696. }, timeout, interval).Should(BeTrue())
  697. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1alpha1.ExternalSecretReady, v1.ConditionFalse, 1.0)).To(BeTrue())
  698. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1alpha1.ExternalSecretReady, v1.ConditionTrue, 0.0)).To(BeTrue())
  699. // es condition should reflect recovered provider error
  700. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  701. esKey := types.NamespacedName{Name: ExternalSecretName, Namespace: ExternalSecretNamespace}
  702. Eventually(func() bool {
  703. err := k8sClient.Get(context.Background(), esKey, es)
  704. if err != nil {
  705. return false
  706. }
  707. // condition must now be true!
  708. cond := GetExternalSecretCondition(es.Status, esv1alpha1.ExternalSecretReady)
  709. if cond == nil && cond.Status != v1.ConditionTrue {
  710. return false
  711. }
  712. return true
  713. }, timeout, interval).Should(BeTrue())
  714. }
  715. }
  716. // When a ExternalSecret references an non-existing SecretStore
  717. // a error condition must be set.
  718. storeMissingErrCondition := func(tc *testCase) {
  719. tc.externalSecret.Spec.SecretStoreRef.Name = "nonexistent"
  720. tc.checkCondition = func(es *esv1alpha1.ExternalSecret) bool {
  721. cond := GetExternalSecretCondition(es.Status, esv1alpha1.ExternalSecretReady)
  722. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1alpha1.ConditionReasonSecretSyncedError {
  723. return false
  724. }
  725. return true
  726. }
  727. tc.checkExternalSecret = func(es *esv1alpha1.ExternalSecret) {
  728. Eventually(func() bool {
  729. Expect(syncCallsError.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metric)).To(Succeed())
  730. return metric.GetCounter().GetValue() >= 2.0
  731. }, timeout, interval).Should(BeTrue())
  732. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1alpha1.ExternalSecretReady, v1.ConditionFalse, 1.0)).To(BeTrue())
  733. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1alpha1.ExternalSecretReady, v1.ConditionTrue, 0.0)).To(BeTrue())
  734. }
  735. }
  736. // when the provider constructor errors (e.g. invalid configuration)
  737. // a SecretSyncedError status condition must be set
  738. storeConstructErrCondition := func(tc *testCase) {
  739. fakeProvider.WithNew(func(context.Context, esv1alpha1.GenericStore, client.Client,
  740. string) (provider.SecretsClient, error) {
  741. return nil, fmt.Errorf("artificial constructor error")
  742. })
  743. tc.checkCondition = func(es *esv1alpha1.ExternalSecret) bool {
  744. // condition must be false
  745. cond := GetExternalSecretCondition(es.Status, esv1alpha1.ExternalSecretReady)
  746. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1alpha1.ConditionReasonSecretSyncedError {
  747. return false
  748. }
  749. return true
  750. }
  751. tc.checkExternalSecret = func(es *esv1alpha1.ExternalSecret) {
  752. Eventually(func() bool {
  753. Expect(syncCallsError.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metric)).To(Succeed())
  754. return metric.GetCounter().GetValue() >= 2.0
  755. }, timeout, interval).Should(BeTrue())
  756. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1alpha1.ExternalSecretReady, v1.ConditionFalse, 1.0)).To(BeTrue())
  757. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1alpha1.ExternalSecretReady, v1.ConditionTrue, 0.0)).To(BeTrue())
  758. }
  759. }
  760. // when a SecretStore has a controller field set which we don't care about
  761. // the externalSecret must not be touched
  762. ignoreMismatchController := func(tc *testCase) {
  763. tc.secretStore.Spec.Controller = "nop"
  764. tc.checkCondition = func(es *esv1alpha1.ExternalSecret) bool {
  765. cond := GetExternalSecretCondition(es.Status, esv1alpha1.ExternalSecretReady)
  766. return cond == nil
  767. }
  768. tc.checkExternalSecret = func(es *esv1alpha1.ExternalSecret) {
  769. // Condition True and False should be 0, since the Condition was not created
  770. Eventually(func() float64 {
  771. Expect(externalSecretCondition.WithLabelValues(ExternalSecretName, ExternalSecretNamespace, string(esv1alpha1.ExternalSecretReady), string(v1.ConditionTrue)).Write(&metric)).To(Succeed())
  772. return metric.GetGauge().GetValue()
  773. }, timeout, interval).Should(Equal(0.0))
  774. Eventually(func() float64 {
  775. Expect(externalSecretCondition.WithLabelValues(ExternalSecretName, ExternalSecretNamespace, string(esv1alpha1.ExternalSecretReady), string(v1.ConditionFalse)).Write(&metric)).To(Succeed())
  776. return metric.GetGauge().GetValue()
  777. }, timeout, interval).Should(Equal(0.0))
  778. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1alpha1.ExternalSecretReady, v1.ConditionFalse, 0.0)).To(BeTrue())
  779. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1alpha1.ExternalSecretReady, v1.ConditionTrue, 0.0)).To(BeTrue())
  780. }
  781. }
  782. // When the ownership is set to owner, and we delete a dependent child kind=secret
  783. // it should be recreated without waiting for refresh interval
  784. checkDeletion := func(tc *testCase) {
  785. const secretVal = "someValue"
  786. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  787. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Minute * 10}
  788. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  789. // check values
  790. oldUID := secret.UID
  791. Expect(oldUID).NotTo(BeEmpty())
  792. // delete the related config
  793. Expect(k8sClient.Delete(context.TODO(), secret))
  794. var newSecret v1.Secret
  795. secretLookupKey := types.NamespacedName{
  796. Name: ExternalSecretTargetSecretName,
  797. Namespace: ExternalSecretNamespace,
  798. }
  799. Eventually(func() bool {
  800. err := k8sClient.Get(context.Background(), secretLookupKey, &newSecret)
  801. if err != nil {
  802. return false
  803. }
  804. // new secret should be a new, recreated object with a different UID
  805. return newSecret.UID != oldUID
  806. }, timeout, interval).Should(BeTrue())
  807. }
  808. }
  809. // Checks that secret annotation has been written based on the data
  810. checkSecretDataHashAnnotation := func(tc *testCase) {
  811. const secretVal = "someValue"
  812. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  813. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  814. Expect(secret.Annotations[esv1alpha1.AnnotationDataHash]).To(Equal("9d30b95ca81e156f9454b5ef3bfcc6ee"))
  815. }
  816. }
  817. // When we amend the created kind=secret, refresh operation should be run again regardless of refresh interval
  818. checkSecretDataHashAnnotationChange := func(tc *testCase) {
  819. fakeData := map[string][]byte{
  820. "targetProperty": []byte(FooValue),
  821. }
  822. fakeProvider.WithGetSecretMap(fakeData, nil)
  823. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Minute * 10}
  824. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  825. oldHash := secret.Annotations[esv1alpha1.AnnotationDataHash]
  826. oldResourceVersion := secret.ResourceVersion
  827. Expect(oldHash).NotTo(BeEmpty())
  828. cleanSecret := secret.DeepCopy()
  829. secret.Data["new"] = []byte("value")
  830. secret.ObjectMeta.Annotations[esv1alpha1.AnnotationDataHash] = "thisiswronghash"
  831. Expect(k8sClient.Patch(context.Background(), secret, client.MergeFrom(cleanSecret))).To(Succeed())
  832. var refreshedSecret v1.Secret
  833. secretLookupKey := types.NamespacedName{
  834. Name: ExternalSecretTargetSecretName,
  835. Namespace: ExternalSecretNamespace,
  836. }
  837. Eventually(func() bool {
  838. err := k8sClient.Get(context.Background(), secretLookupKey, &refreshedSecret)
  839. if err != nil {
  840. return false
  841. }
  842. // refreshed secret should have a different generation (sign that it was updated), but since
  843. // the secret source is the same (not changed), the hash should be reverted to an old value
  844. return refreshedSecret.ResourceVersion != oldResourceVersion && refreshedSecret.Annotations[esv1alpha1.AnnotationDataHash] == oldHash
  845. }, timeout, interval).Should(BeTrue())
  846. }
  847. }
  848. DescribeTable("When reconciling an ExternalSecret",
  849. func(tweaks ...testTweaks) {
  850. tc := makeDefaultTestcase()
  851. for _, tweak := range tweaks {
  852. tweak(tc)
  853. }
  854. ctx := context.Background()
  855. By("creating a secret store and external secret")
  856. Expect(k8sClient.Create(ctx, tc.secretStore)).To(Succeed())
  857. Expect(k8sClient.Create(ctx, tc.externalSecret)).Should(Succeed())
  858. esKey := types.NamespacedName{Name: ExternalSecretName, Namespace: ExternalSecretNamespace}
  859. createdES := &esv1alpha1.ExternalSecret{}
  860. By("checking the es condition")
  861. Eventually(func() bool {
  862. err := k8sClient.Get(ctx, esKey, createdES)
  863. if err != nil {
  864. return false
  865. }
  866. return tc.checkCondition(createdES)
  867. }, timeout, interval).Should(BeTrue())
  868. tc.checkExternalSecret(createdES)
  869. // this must be optional so we can test faulty es configuration
  870. if tc.checkSecret != nil {
  871. syncedSecret := &v1.Secret{}
  872. secretLookupKey := types.NamespacedName{
  873. Name: ExternalSecretTargetSecretName,
  874. Namespace: ExternalSecretNamespace,
  875. }
  876. if createdES.Spec.Target.Name == "" {
  877. secretLookupKey = types.NamespacedName{
  878. Name: ExternalSecretName,
  879. Namespace: ExternalSecretNamespace,
  880. }
  881. }
  882. Eventually(func() bool {
  883. err := k8sClient.Get(ctx, secretLookupKey, syncedSecret)
  884. return err == nil
  885. }, timeout, interval).Should(BeTrue())
  886. tc.checkSecret(createdES, syncedSecret)
  887. }
  888. },
  889. Entry("should recreate deleted secret", checkDeletion),
  890. Entry("should create proper hash annotation for the external secret", checkSecretDataHashAnnotation),
  891. Entry("should refresh when the hash annotation doesn't correspond to secret data", checkSecretDataHashAnnotationChange),
  892. Entry("should use external secret name if target secret name isn't defined", syncWithoutTargetName),
  893. Entry("should set the condition eventually", syncLabelsAnnotations),
  894. Entry("should set prometheus counters", checkPrometheusCounters),
  895. Entry("should merge with existing secret using creationPolicy=Merge", mergeWithSecret),
  896. Entry("should error if secret doesn't exist when using creationPolicy=Merge", mergeWithSecretErr),
  897. Entry("should not resolve conflicts with creationPolicy=Merge", mergeWithConflict),
  898. Entry("should not update unchanged secret using creationPolicy=Merge", mergeWithSecretNoChange),
  899. Entry("should sync with template", syncWithTemplate),
  900. Entry("should sync template with correct value precedence", syncWithTemplatePrecedence),
  901. Entry("should refresh secret from template", refreshWithTemplate),
  902. Entry("should be able to use only metadata from template", onlyMetadataFromTemplate),
  903. Entry("should refresh secret value when provider secret changes", refreshSecretValue),
  904. Entry("should not refresh secret value when provider secret changes but refreshInterval is zero", refreshintervalZero),
  905. Entry("should fetch secret using dataFrom", syncWithDataFrom),
  906. Entry("should fetch secret using dataFrom and a template", syncWithDataFromTemplate),
  907. Entry("should set error condition when provider errors", providerErrCondition),
  908. Entry("should set an error condition when store does not exist", storeMissingErrCondition),
  909. Entry("should set an error condition when store provider constructor fails", storeConstructErrCondition),
  910. Entry("should not process store with mismatching controller field", ignoreMismatchController),
  911. )
  912. })
  913. var _ = Describe("ExternalSecret refresh logic", func() {
  914. Context("secret refresh", func() {
  915. It("should refresh when resource version does not match", func() {
  916. Expect(shouldRefresh(esv1alpha1.ExternalSecret{
  917. Status: esv1alpha1.ExternalSecretStatus{
  918. SyncedResourceVersion: "some resource version",
  919. },
  920. })).To(BeTrue())
  921. })
  922. It("should refresh when labels change", func() {
  923. es := esv1alpha1.ExternalSecret{
  924. ObjectMeta: metav1.ObjectMeta{
  925. Generation: 1,
  926. Labels: map[string]string{
  927. "foo": "bar",
  928. },
  929. },
  930. Spec: esv1alpha1.ExternalSecretSpec{
  931. RefreshInterval: &metav1.Duration{Duration: time.Minute},
  932. },
  933. Status: esv1alpha1.ExternalSecretStatus{
  934. RefreshTime: metav1.Now(),
  935. },
  936. }
  937. es.Status.SyncedResourceVersion = getResourceVersion(es)
  938. // this should not refresh, rv matches object
  939. Expect(shouldRefresh(es)).To(BeFalse())
  940. // change labels without changing the syncedResourceVersion and expect refresh
  941. es.ObjectMeta.Labels["new"] = "w00t"
  942. Expect(shouldRefresh(es)).To(BeTrue())
  943. })
  944. It("should refresh when annotations change", func() {
  945. es := esv1alpha1.ExternalSecret{
  946. ObjectMeta: metav1.ObjectMeta{
  947. Generation: 1,
  948. Annotations: map[string]string{
  949. "foo": "bar",
  950. },
  951. },
  952. Spec: esv1alpha1.ExternalSecretSpec{
  953. RefreshInterval: &metav1.Duration{Duration: time.Minute},
  954. },
  955. Status: esv1alpha1.ExternalSecretStatus{
  956. RefreshTime: metav1.Now(),
  957. },
  958. }
  959. es.Status.SyncedResourceVersion = getResourceVersion(es)
  960. // this should not refresh, rv matches object
  961. Expect(shouldRefresh(es)).To(BeFalse())
  962. // change annotations without changing the syncedResourceVersion and expect refresh
  963. es.ObjectMeta.Annotations["new"] = "w00t"
  964. Expect(shouldRefresh(es)).To(BeTrue())
  965. })
  966. It("should refresh when generation has changed", func() {
  967. es := esv1alpha1.ExternalSecret{
  968. ObjectMeta: metav1.ObjectMeta{
  969. Generation: 1,
  970. },
  971. Spec: esv1alpha1.ExternalSecretSpec{
  972. RefreshInterval: &metav1.Duration{Duration: 0},
  973. },
  974. Status: esv1alpha1.ExternalSecretStatus{
  975. RefreshTime: metav1.Now(),
  976. },
  977. }
  978. es.Status.SyncedResourceVersion = getResourceVersion(es)
  979. Expect(shouldRefresh(es)).To(BeFalse())
  980. // update gen -> refresh
  981. es.ObjectMeta.Generation = 2
  982. Expect(shouldRefresh(es)).To(BeTrue())
  983. })
  984. It("should skip refresh when refreshInterval is 0", func() {
  985. es := esv1alpha1.ExternalSecret{
  986. ObjectMeta: metav1.ObjectMeta{
  987. Generation: 1,
  988. },
  989. Spec: esv1alpha1.ExternalSecretSpec{
  990. RefreshInterval: &metav1.Duration{Duration: 0},
  991. },
  992. Status: esv1alpha1.ExternalSecretStatus{},
  993. }
  994. // resource version matches
  995. es.Status.SyncedResourceVersion = getResourceVersion(es)
  996. Expect(shouldRefresh(es)).To(BeFalse())
  997. })
  998. It("should refresh when refresh interval has passed", func() {
  999. es := esv1alpha1.ExternalSecret{
  1000. ObjectMeta: metav1.ObjectMeta{
  1001. Generation: 1,
  1002. },
  1003. Spec: esv1alpha1.ExternalSecretSpec{
  1004. RefreshInterval: &metav1.Duration{Duration: time.Second},
  1005. },
  1006. Status: esv1alpha1.ExternalSecretStatus{
  1007. RefreshTime: metav1.NewTime(metav1.Now().Add(-time.Second * 5)),
  1008. },
  1009. }
  1010. // resource version matches
  1011. es.Status.SyncedResourceVersion = getResourceVersion(es)
  1012. Expect(shouldRefresh(es)).To(BeTrue())
  1013. })
  1014. It("should refresh when no refresh time was set", func() {
  1015. es := esv1alpha1.ExternalSecret{
  1016. ObjectMeta: metav1.ObjectMeta{
  1017. Generation: 1,
  1018. },
  1019. Spec: esv1alpha1.ExternalSecretSpec{
  1020. RefreshInterval: &metav1.Duration{Duration: time.Second},
  1021. },
  1022. Status: esv1alpha1.ExternalSecretStatus{},
  1023. }
  1024. // resource version matches
  1025. es.Status.SyncedResourceVersion = getResourceVersion(es)
  1026. Expect(shouldRefresh(es)).To(BeTrue())
  1027. })
  1028. })
  1029. Context("objectmeta hash", func() {
  1030. It("should produce different hashes for different k/v pairs", func() {
  1031. h1 := hashMeta(metav1.ObjectMeta{
  1032. Generation: 1,
  1033. Annotations: map[string]string{
  1034. "foo": "bar",
  1035. },
  1036. })
  1037. h2 := hashMeta(metav1.ObjectMeta{
  1038. Generation: 1,
  1039. Annotations: map[string]string{
  1040. "foo": "bing",
  1041. },
  1042. })
  1043. Expect(h1).ToNot(Equal(h2))
  1044. })
  1045. It("should produce different hashes for different generations but same label/annotations", func() {
  1046. h1 := hashMeta(metav1.ObjectMeta{
  1047. Generation: 1,
  1048. Annotations: map[string]string{
  1049. "foo": "bar",
  1050. },
  1051. Labels: map[string]string{
  1052. "foo": "bar",
  1053. },
  1054. })
  1055. h2 := hashMeta(metav1.ObjectMeta{
  1056. Generation: 2,
  1057. Annotations: map[string]string{
  1058. "foo": "bar",
  1059. },
  1060. Labels: map[string]string{
  1061. "foo": "bar",
  1062. },
  1063. })
  1064. Expect(h1).To(Equal(h2))
  1065. })
  1066. It("should produce the same hash for the same k/v pairs", func() {
  1067. h1 := hashMeta(metav1.ObjectMeta{
  1068. Generation: 1,
  1069. })
  1070. h2 := hashMeta(metav1.ObjectMeta{
  1071. Generation: 1,
  1072. })
  1073. Expect(h1).To(Equal(h2))
  1074. h1 = hashMeta(metav1.ObjectMeta{
  1075. Generation: 1,
  1076. Annotations: map[string]string{
  1077. "foo": "bar",
  1078. },
  1079. })
  1080. h2 = hashMeta(metav1.ObjectMeta{
  1081. Generation: 1,
  1082. Annotations: map[string]string{
  1083. "foo": "bar",
  1084. },
  1085. })
  1086. Expect(h1).To(Equal(h2))
  1087. })
  1088. })
  1089. })
  1090. var _ = Describe("Controller Reconcile logic", func() {
  1091. Context("controller reconcile", func() {
  1092. It("should reconcile when resource is not synced", func() {
  1093. Expect(shouldReconcile(esv1alpha1.ExternalSecret{
  1094. Status: esv1alpha1.ExternalSecretStatus{
  1095. SyncedResourceVersion: "some resource version",
  1096. Conditions: []esv1alpha1.ExternalSecretStatusCondition{{Reason: "NotASecretSynced"}},
  1097. },
  1098. })).To(BeTrue())
  1099. })
  1100. It("should reconcile when secret isn't immutable", func() {
  1101. Expect(shouldReconcile(esv1alpha1.ExternalSecret{
  1102. Spec: esv1alpha1.ExternalSecretSpec{
  1103. Target: esv1alpha1.ExternalSecretTarget{
  1104. Immutable: false,
  1105. },
  1106. },
  1107. })).To(BeTrue())
  1108. })
  1109. It("should not reconcile if secret is immutable and has synced condition", func() {
  1110. Expect(shouldReconcile(esv1alpha1.ExternalSecret{
  1111. Spec: esv1alpha1.ExternalSecretSpec{
  1112. Target: esv1alpha1.ExternalSecretTarget{
  1113. Immutable: true,
  1114. },
  1115. },
  1116. Status: esv1alpha1.ExternalSecretStatus{
  1117. SyncedResourceVersion: "some resource version",
  1118. Conditions: []esv1alpha1.ExternalSecretStatusCondition{{Reason: "SecretSynced"}},
  1119. },
  1120. })).To(BeFalse())
  1121. })
  1122. })
  1123. })
  1124. // CreateNamespace creates a new namespace in the cluster.
  1125. func CreateNamespace(baseName string, c client.Client) (string, error) {
  1126. genName := fmt.Sprintf("ctrl-test-%v", baseName)
  1127. ns := &v1.Namespace{
  1128. ObjectMeta: metav1.ObjectMeta{
  1129. GenerateName: genName,
  1130. },
  1131. }
  1132. var err error
  1133. err = wait.Poll(time.Second, 10*time.Second, func() (bool, error) {
  1134. err = c.Create(context.Background(), ns)
  1135. if err != nil {
  1136. return false, nil
  1137. }
  1138. return true, nil
  1139. })
  1140. if err != nil {
  1141. return "", err
  1142. }
  1143. return ns.Name, nil
  1144. }
  1145. func hasOwnerRef(meta metav1.ObjectMeta, kind, name string) bool {
  1146. for _, ref := range meta.OwnerReferences {
  1147. if ref.Kind == kind && ref.Name == name {
  1148. return true
  1149. }
  1150. }
  1151. return false
  1152. }
  1153. func hasFieldOwnership(meta metav1.ObjectMeta, mgr, rawFields string) bool {
  1154. for _, ref := range meta.ManagedFields {
  1155. if ref.Manager == mgr && string(ref.FieldsV1.Raw) == rawFields {
  1156. return true
  1157. }
  1158. }
  1159. return false
  1160. }
  1161. func externalSecretConditionShouldBe(name, ns string, ct esv1alpha1.ExternalSecretConditionType, cs v1.ConditionStatus, v float64) bool {
  1162. return Eventually(func() float64 {
  1163. Expect(externalSecretCondition.WithLabelValues(name, ns, string(ct), string(cs)).Write(&metric)).To(Succeed())
  1164. return metric.GetGauge().GetValue()
  1165. }, timeout, interval).Should(Equal(v))
  1166. }
  1167. func init() {
  1168. fakeProvider = fake.New()
  1169. schema.ForceRegister(fakeProvider, &esv1alpha1.SecretStoreProvider{
  1170. AWS: &esv1alpha1.AWSProvider{
  1171. Service: esv1alpha1.AWSServiceSecretsManager,
  1172. },
  1173. })
  1174. }