externalsecret_controller_test.go 42 KB

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