externalsecret_controller_test.go 44 KB

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