externalsecret_controller_test.go 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910
  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. "time"
  17. . "github.com/onsi/ginkgo"
  18. . "github.com/onsi/ginkgo/extensions/table"
  19. . "github.com/onsi/gomega"
  20. dto "github.com/prometheus/client_model/go"
  21. v1 "k8s.io/api/core/v1"
  22. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  23. "k8s.io/apimachinery/pkg/types"
  24. "k8s.io/apimachinery/pkg/util/wait"
  25. "sigs.k8s.io/controller-runtime/pkg/client"
  26. esv1alpha1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1alpha1"
  27. "github.com/external-secrets/external-secrets/pkg/provider"
  28. "github.com/external-secrets/external-secrets/pkg/provider/fake"
  29. "github.com/external-secrets/external-secrets/pkg/provider/schema"
  30. )
  31. var (
  32. fakeProvider *fake.Client
  33. metric dto.Metric
  34. timeout = time.Second * 10
  35. interval = time.Millisecond * 250
  36. )
  37. type testCase struct {
  38. secretStore *esv1alpha1.SecretStore
  39. externalSecret *esv1alpha1.ExternalSecret
  40. // checkCondition should return true if the externalSecret
  41. // has the expected condition
  42. checkCondition func(*esv1alpha1.ExternalSecret) bool
  43. // checkExternalSecret is called after the condition has been verified
  44. // use this to verify the externalSecret
  45. checkExternalSecret func(*esv1alpha1.ExternalSecret)
  46. // optional. use this to test the secret value
  47. checkSecret func(*esv1alpha1.ExternalSecret, *v1.Secret)
  48. }
  49. type testTweaks func(*testCase)
  50. var _ = Describe("ExternalSecret controller", func() {
  51. const (
  52. ExternalSecretName = "test-es"
  53. ExternalSecretStore = "test-store"
  54. ExternalSecretTargetSecretName = "test-secret"
  55. )
  56. var ExternalSecretNamespace string
  57. BeforeEach(func() {
  58. var err error
  59. ExternalSecretNamespace, err = CreateNamespace("test-ns", k8sClient)
  60. Expect(err).ToNot(HaveOccurred())
  61. metric.Reset()
  62. syncCallsTotal.Reset()
  63. syncCallsError.Reset()
  64. externalSecretCondition.Reset()
  65. })
  66. AfterEach(func() {
  67. Expect(k8sClient.Delete(context.Background(), &v1.Namespace{
  68. ObjectMeta: metav1.ObjectMeta{
  69. Name: ExternalSecretNamespace,
  70. },
  71. }, client.PropagationPolicy(metav1.DeletePropagationBackground)), client.GracePeriodSeconds(0)).To(Succeed())
  72. Expect(k8sClient.Delete(context.Background(), &esv1alpha1.SecretStore{
  73. ObjectMeta: metav1.ObjectMeta{
  74. Name: ExternalSecretStore,
  75. Namespace: ExternalSecretNamespace,
  76. },
  77. }, client.PropagationPolicy(metav1.DeletePropagationBackground)), client.GracePeriodSeconds(0)).To(Succeed())
  78. })
  79. const targetProp = "targetProperty"
  80. const remoteKey = "barz"
  81. const remoteProperty = "bang"
  82. makeDefaultTestcase := func() *testCase {
  83. return &testCase{
  84. // default condition: es should be ready
  85. checkCondition: func(es *esv1alpha1.ExternalSecret) bool {
  86. cond := GetExternalSecretCondition(es.Status, esv1alpha1.ExternalSecretReady)
  87. if cond == nil || cond.Status != v1.ConditionTrue {
  88. return false
  89. }
  90. return true
  91. },
  92. checkExternalSecret: func(es *esv1alpha1.ExternalSecret) {},
  93. secretStore: &esv1alpha1.SecretStore{
  94. ObjectMeta: metav1.ObjectMeta{
  95. Name: ExternalSecretStore,
  96. Namespace: ExternalSecretNamespace,
  97. },
  98. Spec: esv1alpha1.SecretStoreSpec{
  99. Provider: &esv1alpha1.SecretStoreProvider{
  100. AWS: &esv1alpha1.AWSProvider{
  101. Service: esv1alpha1.AWSServiceSecretsManager,
  102. },
  103. },
  104. },
  105. },
  106. externalSecret: &esv1alpha1.ExternalSecret{
  107. ObjectMeta: metav1.ObjectMeta{
  108. Name: ExternalSecretName,
  109. Namespace: ExternalSecretNamespace,
  110. },
  111. Spec: esv1alpha1.ExternalSecretSpec{
  112. SecretStoreRef: esv1alpha1.SecretStoreRef{
  113. Name: ExternalSecretStore,
  114. },
  115. Target: esv1alpha1.ExternalSecretTarget{
  116. Name: ExternalSecretTargetSecretName,
  117. },
  118. Data: []esv1alpha1.ExternalSecretData{
  119. {
  120. SecretKey: targetProp,
  121. RemoteRef: esv1alpha1.ExternalSecretDataRemoteRef{
  122. Key: remoteKey,
  123. Property: remoteProperty,
  124. },
  125. },
  126. },
  127. },
  128. },
  129. }
  130. }
  131. // labels and annotations from the Kind=ExternalSecret
  132. // should be copied over to the Kind=Secret
  133. syncLabelsAnnotations := func(tc *testCase) {
  134. const secretVal = "someValue"
  135. tc.externalSecret.ObjectMeta.Labels = map[string]string{
  136. "fooobar": "bazz",
  137. }
  138. tc.externalSecret.ObjectMeta.Annotations = map[string]string{
  139. "hihihih": "hehehe",
  140. }
  141. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  142. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  143. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1alpha1.ExternalSecretReady, v1.ConditionFalse, 0.0)).To(BeTrue())
  144. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1alpha1.ExternalSecretReady, v1.ConditionTrue, 1.0)).To(BeTrue())
  145. Eventually(func() bool {
  146. Expect(syncCallsTotal.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metric)).To(Succeed())
  147. return metric.GetCounter().GetValue() == 1.0
  148. }, timeout, interval).Should(BeTrue())
  149. // check value
  150. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  151. // check labels & annotations
  152. Expect(secret.ObjectMeta.Labels).To(BeEquivalentTo(es.ObjectMeta.Labels))
  153. Expect(secret.ObjectMeta.Annotations).To(BeEquivalentTo(es.ObjectMeta.Annotations))
  154. // ownerRef must not not be set!
  155. Expect(hasOwnerRef(secret.ObjectMeta, "ExternalSecret", ExternalSecretName)).To(BeTrue())
  156. }
  157. }
  158. // merge with existing secret using creationPolicy=Merge
  159. // it should NOT have a ownerReference
  160. // metadata.managedFields with the correct owner should be added to the secret
  161. mergeWithSecret := func(tc *testCase) {
  162. const secretVal = "someValue"
  163. const existingKey = "pre-existing-key"
  164. existingVal := "pre-existing-value"
  165. tc.externalSecret.Spec.Target.CreationPolicy = esv1alpha1.Merge
  166. // create secret beforehand
  167. Expect(k8sClient.Create(context.Background(), &v1.Secret{
  168. ObjectMeta: metav1.ObjectMeta{
  169. Name: "test-secret",
  170. Namespace: ExternalSecretNamespace,
  171. },
  172. Data: map[string][]byte{
  173. existingKey: []byte(existingVal),
  174. },
  175. }, client.FieldOwner("fake.manager"))).To(Succeed())
  176. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  177. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  178. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1alpha1.ExternalSecretReady, v1.ConditionFalse, 0.0)).To(BeTrue())
  179. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1alpha1.ExternalSecretReady, v1.ConditionTrue, 1.0)).To(BeTrue())
  180. Eventually(func() bool {
  181. Expect(syncCallsTotal.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metric)).To(Succeed())
  182. return metric.GetCounter().GetValue() == 1.0
  183. }, timeout, interval).Should(BeTrue())
  184. // check value
  185. Expect(string(secret.Data[existingKey])).To(Equal(existingVal))
  186. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  187. // check labels & annotations
  188. Expect(secret.ObjectMeta.Labels).To(BeEquivalentTo(es.ObjectMeta.Labels))
  189. Expect(secret.ObjectMeta.Annotations).To(BeEquivalentTo(es.ObjectMeta.Annotations))
  190. Expect(hasOwnerRef(secret.ObjectMeta, "ExternalSecret", ExternalSecretName)).To(BeFalse())
  191. Expect(secret.ObjectMeta.ManagedFields).To(HaveLen(2))
  192. Expect(hasFieldOwnership(secret.ObjectMeta, "external-secrets", "{\"f:data\":{\"f:targetProperty\":{}}}")).To(BeTrue())
  193. Expect(hasFieldOwnership(secret.ObjectMeta, "fake.manager", "{\"f:data\":{\".\":{},\"f:pre-existing-key\":{}},\"f:type\":{}}")).To(BeTrue())
  194. }
  195. }
  196. // should not merge with secret if it doesn't exist
  197. mergeWithSecretErr := func(tc *testCase) {
  198. const secretVal = "someValue"
  199. tc.externalSecret.Spec.Target.CreationPolicy = esv1alpha1.Merge
  200. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  201. tc.checkCondition = func(es *esv1alpha1.ExternalSecret) bool {
  202. cond := GetExternalSecretCondition(es.Status, esv1alpha1.ExternalSecretReady)
  203. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1alpha1.ConditionReasonSecretSyncedError {
  204. return false
  205. }
  206. return true
  207. }
  208. tc.checkExternalSecret = func(es *esv1alpha1.ExternalSecret) {
  209. Eventually(func() bool {
  210. Expect(syncCallsError.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metric)).To(Succeed())
  211. return metric.GetCounter().GetValue() >= 2.0
  212. }, timeout, interval).Should(BeTrue())
  213. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1alpha1.ExternalSecretReady, v1.ConditionFalse, 1.0)).To(BeTrue())
  214. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1alpha1.ExternalSecretReady, v1.ConditionTrue, 0.0)).To(BeTrue())
  215. }
  216. }
  217. // controller should not force override but
  218. // return an error on conflict
  219. mergeWithConflict := func(tc *testCase) {
  220. const secretVal = "someValue"
  221. // this should confict
  222. const existingKey = targetProp
  223. existingVal := "pre-existing-value"
  224. tc.externalSecret.Spec.Target.CreationPolicy = esv1alpha1.Merge
  225. // create secret beforehand
  226. Expect(k8sClient.Create(context.Background(), &v1.Secret{
  227. ObjectMeta: metav1.ObjectMeta{
  228. Name: "test-secret",
  229. Namespace: ExternalSecretNamespace,
  230. },
  231. Data: map[string][]byte{
  232. existingKey: []byte(existingVal),
  233. },
  234. }, client.FieldOwner("fake.manager"))).To(Succeed())
  235. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  236. tc.checkCondition = func(es *esv1alpha1.ExternalSecret) bool {
  237. cond := GetExternalSecretCondition(es.Status, esv1alpha1.ExternalSecretReady)
  238. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1alpha1.ConditionReasonSecretSyncedError {
  239. return false
  240. }
  241. return true
  242. }
  243. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  244. // check that value stays the same
  245. Expect(string(secret.Data[existingKey])).To(Equal(existingVal))
  246. Expect(string(secret.Data[targetProp])).ToNot(Equal(secretVal))
  247. // check owner/managedFields
  248. Expect(hasOwnerRef(secret.ObjectMeta, "ExternalSecret", ExternalSecretName)).To(BeFalse())
  249. Expect(secret.ObjectMeta.ManagedFields).To(HaveLen(1))
  250. Expect(hasFieldOwnership(secret.ObjectMeta, "fake.manager", "{\"f:data\":{\".\":{},\"f:targetProperty\":{}},\"f:type\":{}}")).To(BeTrue())
  251. }
  252. }
  253. // when using a template it should be used as a blueprint
  254. // to construct a new secret: labels, annotations and type
  255. syncWithTemplate := func(tc *testCase) {
  256. const secretVal = "someValue"
  257. const expectedSecretVal = "SOMEVALUE was templated"
  258. const tplStaticKey = "tplstatickey"
  259. const tplStaticVal = "tplstaticvalue"
  260. tc.externalSecret.ObjectMeta.Labels = map[string]string{
  261. "fooobar": "bazz",
  262. }
  263. tc.externalSecret.ObjectMeta.Annotations = map[string]string{
  264. "hihihih": "hehehe",
  265. }
  266. tc.externalSecret.Spec.Target.Template = &esv1alpha1.ExternalSecretTemplate{
  267. Metadata: esv1alpha1.ExternalSecretTemplateMetadata{
  268. Labels: map[string]string{
  269. "foos": "ball",
  270. },
  271. Annotations: map[string]string{
  272. "hihi": "ga",
  273. },
  274. },
  275. Type: v1.SecretTypeOpaque,
  276. Data: map[string]string{
  277. targetProp: "{{ .targetProperty | toString | upper }} was templated",
  278. tplStaticKey: tplStaticVal,
  279. },
  280. }
  281. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  282. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  283. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1alpha1.ExternalSecretReady, v1.ConditionFalse, 0.0)).To(BeTrue())
  284. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1alpha1.ExternalSecretReady, v1.ConditionTrue, 1.0)).To(BeTrue())
  285. Eventually(func() bool {
  286. Expect(syncCallsTotal.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metric)).To(Succeed())
  287. return metric.GetCounter().GetValue() == 1.0
  288. }, timeout, interval).Should(BeTrue())
  289. // check values
  290. Expect(string(secret.Data[targetProp])).To(Equal(expectedSecretVal))
  291. Expect(string(secret.Data[tplStaticKey])).To(Equal(tplStaticVal))
  292. // labels/annotations should be taken from the template
  293. Expect(secret.ObjectMeta.Labels).To(BeEquivalentTo(es.Spec.Target.Template.Metadata.Labels))
  294. Expect(secret.ObjectMeta.Annotations).To(BeEquivalentTo(es.Spec.Target.Template.Metadata.Annotations))
  295. }
  296. }
  297. // secret should be synced with correct value precedence:
  298. // * template
  299. // * templateFrom
  300. // * data
  301. // * dataFrom
  302. syncWithTemplatePrecedence := func(tc *testCase) {
  303. const secretVal = "someValue"
  304. const expectedSecretVal = "SOMEVALUE was templated"
  305. const tplStaticKey = "tplstatickey"
  306. const tplStaticVal = "tplstaticvalue"
  307. const tplFromCMName = "template-cm"
  308. const tplFromKey = "tpl-from-key"
  309. const tplFromVal = "tpl-from-value: {{ .targetProperty | toString }} // {{ .bar | toString }}"
  310. Expect(k8sClient.Create(context.Background(), &v1.ConfigMap{
  311. ObjectMeta: metav1.ObjectMeta{
  312. Name: "template-cm",
  313. Namespace: ExternalSecretNamespace,
  314. },
  315. Data: map[string]string{
  316. tplFromKey: tplFromVal,
  317. },
  318. })).To(Succeed())
  319. tc.externalSecret.Spec.Target.Template = &esv1alpha1.ExternalSecretTemplate{
  320. Metadata: esv1alpha1.ExternalSecretTemplateMetadata{},
  321. Type: v1.SecretTypeOpaque,
  322. TemplateFrom: []esv1alpha1.TemplateFrom{
  323. {
  324. ConfigMap: &esv1alpha1.TemplateRef{
  325. Name: tplFromCMName,
  326. Items: []esv1alpha1.TemplateRefItem{
  327. {
  328. Key: tplFromKey,
  329. },
  330. },
  331. },
  332. },
  333. },
  334. Data: map[string]string{
  335. // this should be the data value, not dataFrom
  336. targetProp: "{{ .targetProperty | toString | upper }} was templated",
  337. // this should use the value from the map
  338. "bar": "value from map: {{ .bar | toString }}",
  339. // just a static value
  340. tplStaticKey: tplStaticVal,
  341. },
  342. }
  343. tc.externalSecret.Spec.DataFrom = []esv1alpha1.ExternalSecretDataRemoteRef{
  344. {
  345. Key: "datamap",
  346. },
  347. }
  348. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  349. fakeProvider.WithGetSecretMap(map[string][]byte{
  350. "targetProperty": []byte("map-foo-value"),
  351. "bar": []byte("map-bar-value"),
  352. }, nil)
  353. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  354. // check values
  355. Expect(string(secret.Data[targetProp])).To(Equal(expectedSecretVal))
  356. Expect(string(secret.Data[tplStaticKey])).To(Equal(tplStaticVal))
  357. Expect(string(secret.Data["bar"])).To(Equal("value from map: map-bar-value"))
  358. Expect(string(secret.Data[tplFromKey])).To(Equal("tpl-from-value: someValue // map-bar-value"))
  359. }
  360. }
  361. refreshWithTemplate := func(tc *testCase) {
  362. const secretVal = "someValue"
  363. const expectedSecretVal = "SOMEVALUE was templated"
  364. const tplStaticKey = "tplstatickey"
  365. const tplStaticVal = "tplstaticvalue"
  366. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Second}
  367. tc.externalSecret.Spec.Target.Template = &esv1alpha1.ExternalSecretTemplate{
  368. Metadata: esv1alpha1.ExternalSecretTemplateMetadata{
  369. Labels: map[string]string{"foo": "bar"},
  370. Annotations: map[string]string{"foo": "bar"},
  371. },
  372. Type: v1.SecretTypeOpaque,
  373. Data: map[string]string{
  374. targetProp: "{{ .targetProperty | toString | upper }} was templated",
  375. tplStaticKey: tplStaticVal,
  376. },
  377. }
  378. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  379. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  380. // check values
  381. Expect(string(secret.Data[targetProp])).To(Equal(expectedSecretVal))
  382. Expect(string(secret.Data[tplStaticKey])).To(Equal(tplStaticVal))
  383. // labels/annotations should be taken from the template
  384. Expect(secret.ObjectMeta.Labels).To(BeEquivalentTo(es.Spec.Target.Template.Metadata.Labels))
  385. Expect(secret.ObjectMeta.Annotations).To(BeEquivalentTo(es.Spec.Target.Template.Metadata.Annotations))
  386. cleanEs := tc.externalSecret.DeepCopy()
  387. // now update ExternalSecret
  388. tc.externalSecret.Spec.Target.Template.Metadata.Annotations["fuzz"] = "buzz"
  389. tc.externalSecret.Spec.Target.Template.Metadata.Labels["fuzz"] = "buzz"
  390. tc.externalSecret.Spec.Target.Template.Data["new"] = "value"
  391. Expect(k8sClient.Patch(context.Background(), tc.externalSecret, client.MergeFrom(cleanEs))).To(Succeed())
  392. // wait for secret
  393. sec := &v1.Secret{}
  394. secretLookupKey := types.NamespacedName{
  395. Name: ExternalSecretTargetSecretName,
  396. Namespace: ExternalSecretNamespace,
  397. }
  398. Eventually(func() bool {
  399. err := k8sClient.Get(context.Background(), secretLookupKey, sec)
  400. if err != nil {
  401. return false
  402. }
  403. // ensure new data value exist
  404. return string(sec.Data["new"]) == "value"
  405. }, time.Second*10, time.Millisecond*200).Should(BeTrue())
  406. // also check labels/annotations have been updated
  407. Expect(secret.ObjectMeta.Labels).To(BeEquivalentTo(es.Spec.Target.Template.Metadata.Labels))
  408. Expect(secret.ObjectMeta.Annotations).To(BeEquivalentTo(es.Spec.Target.Template.Metadata.Annotations))
  409. }
  410. }
  411. // when the provider secret changes the Kind=Secret value
  412. // must change, too.
  413. refreshSecretValue := func(tc *testCase) {
  414. const targetProp = "targetProperty"
  415. const secretVal = "someValue"
  416. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  417. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Second}
  418. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  419. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1alpha1.ExternalSecretReady, v1.ConditionFalse, 0.0)).To(BeTrue())
  420. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1alpha1.ExternalSecretReady, v1.ConditionTrue, 1.0)).To(BeTrue())
  421. Eventually(func() bool {
  422. Expect(syncCallsTotal.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metric)).To(Succeed())
  423. return metric.GetCounter().GetValue() == 1.0
  424. }, timeout, interval).Should(BeTrue())
  425. // check values
  426. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  427. // update provider secret
  428. newValue := "NEW VALUE"
  429. sec := &v1.Secret{}
  430. fakeProvider.WithGetSecret([]byte(newValue), nil)
  431. secretLookupKey := types.NamespacedName{
  432. Name: ExternalSecretTargetSecretName,
  433. Namespace: ExternalSecretNamespace,
  434. }
  435. Eventually(func() bool {
  436. err := k8sClient.Get(context.Background(), secretLookupKey, sec)
  437. if err != nil {
  438. return false
  439. }
  440. v := sec.Data[targetProp]
  441. return string(v) == newValue
  442. }, timeout, interval).Should(BeTrue())
  443. }
  444. }
  445. // with dataFrom all properties from the specified secret
  446. // should be put into the secret
  447. syncWithDataFrom := func(tc *testCase) {
  448. tc.externalSecret.Spec.Data = nil
  449. tc.externalSecret.Spec.DataFrom = []esv1alpha1.ExternalSecretDataRemoteRef{
  450. {
  451. Key: remoteKey,
  452. },
  453. }
  454. fakeProvider.WithGetSecretMap(map[string][]byte{
  455. "foo": []byte("map-foo-value"),
  456. "bar": []byte("map-bar-value"),
  457. }, nil)
  458. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  459. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1alpha1.ExternalSecretReady, v1.ConditionFalse, 0.0)).To(BeTrue())
  460. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1alpha1.ExternalSecretReady, v1.ConditionTrue, 1.0)).To(BeTrue())
  461. Eventually(func() bool {
  462. Expect(syncCallsTotal.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metric)).To(Succeed())
  463. return metric.GetCounter().GetValue() == 1.0
  464. }, timeout, interval).Should(BeTrue())
  465. // check values
  466. Expect(string(secret.Data["foo"])).To(Equal("map-foo-value"))
  467. Expect(string(secret.Data["bar"])).To(Equal("map-bar-value"))
  468. }
  469. }
  470. // when a provider errors in a GetSecret call
  471. // a error condition must be set.
  472. providerErrCondition := func(tc *testCase) {
  473. const secretVal = "foobar"
  474. fakeProvider.WithGetSecret(nil, fmt.Errorf("boom"))
  475. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Millisecond * 100}
  476. tc.checkCondition = func(es *esv1alpha1.ExternalSecret) bool {
  477. cond := GetExternalSecretCondition(es.Status, esv1alpha1.ExternalSecretReady)
  478. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1alpha1.ConditionReasonSecretSyncedError {
  479. return false
  480. }
  481. return true
  482. }
  483. tc.checkExternalSecret = func(es *esv1alpha1.ExternalSecret) {
  484. Eventually(func() bool {
  485. Expect(syncCallsError.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metric)).To(Succeed())
  486. return metric.GetCounter().GetValue() >= 2.0
  487. }, timeout, interval).Should(BeTrue())
  488. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1alpha1.ExternalSecretReady, v1.ConditionFalse, 1.0)).To(BeTrue())
  489. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1alpha1.ExternalSecretReady, v1.ConditionTrue, 0.0)).To(BeTrue())
  490. // es condition should reflect recovered provider error
  491. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  492. esKey := types.NamespacedName{Name: ExternalSecretName, Namespace: ExternalSecretNamespace}
  493. Eventually(func() bool {
  494. err := k8sClient.Get(context.Background(), esKey, es)
  495. if err != nil {
  496. return false
  497. }
  498. // condition must now be true!
  499. cond := GetExternalSecretCondition(es.Status, esv1alpha1.ExternalSecretReady)
  500. if cond == nil && cond.Status != v1.ConditionTrue {
  501. return false
  502. }
  503. return true
  504. }, timeout, interval).Should(BeTrue())
  505. }
  506. }
  507. // When a ExternalSecret references an non-existing SecretStore
  508. // a error condition must be set.
  509. storeMissingErrCondition := func(tc *testCase) {
  510. tc.externalSecret.Spec.SecretStoreRef.Name = "nonexistent"
  511. tc.checkCondition = func(es *esv1alpha1.ExternalSecret) bool {
  512. cond := GetExternalSecretCondition(es.Status, esv1alpha1.ExternalSecretReady)
  513. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1alpha1.ConditionReasonSecretSyncedError {
  514. return false
  515. }
  516. return true
  517. }
  518. tc.checkExternalSecret = func(es *esv1alpha1.ExternalSecret) {
  519. Eventually(func() bool {
  520. Expect(syncCallsError.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metric)).To(Succeed())
  521. return metric.GetCounter().GetValue() >= 2.0
  522. }, timeout, interval).Should(BeTrue())
  523. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1alpha1.ExternalSecretReady, v1.ConditionFalse, 1.0)).To(BeTrue())
  524. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1alpha1.ExternalSecretReady, v1.ConditionTrue, 0.0)).To(BeTrue())
  525. }
  526. }
  527. // when the provider constructor errors (e.g. invalid configuration)
  528. // a SecretSyncedError status condition must be set
  529. storeConstructErrCondition := func(tc *testCase) {
  530. fakeProvider.WithNew(func(context.Context, esv1alpha1.GenericStore, client.Client,
  531. string) (provider.SecretsClient, error) {
  532. return nil, fmt.Errorf("artificial constructor error")
  533. })
  534. tc.checkCondition = func(es *esv1alpha1.ExternalSecret) bool {
  535. // condition must be false
  536. cond := GetExternalSecretCondition(es.Status, esv1alpha1.ExternalSecretReady)
  537. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1alpha1.ConditionReasonSecretSyncedError {
  538. return false
  539. }
  540. return true
  541. }
  542. tc.checkExternalSecret = func(es *esv1alpha1.ExternalSecret) {
  543. Eventually(func() bool {
  544. Expect(syncCallsError.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metric)).To(Succeed())
  545. return metric.GetCounter().GetValue() >= 2.0
  546. }, timeout, interval).Should(BeTrue())
  547. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1alpha1.ExternalSecretReady, v1.ConditionFalse, 1.0)).To(BeTrue())
  548. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1alpha1.ExternalSecretReady, v1.ConditionTrue, 0.0)).To(BeTrue())
  549. }
  550. }
  551. // when a SecretStore has a controller field set which we don't care about
  552. // the externalSecret must not be touched
  553. ignoreMismatchController := func(tc *testCase) {
  554. tc.secretStore.Spec.Controller = "nop"
  555. tc.checkCondition = func(es *esv1alpha1.ExternalSecret) bool {
  556. cond := GetExternalSecretCondition(es.Status, esv1alpha1.ExternalSecretReady)
  557. return cond == nil
  558. }
  559. tc.checkExternalSecret = func(es *esv1alpha1.ExternalSecret) {
  560. // Condition True and False should be 0, since the Condition was not created
  561. Eventually(func() float64 {
  562. Expect(externalSecretCondition.WithLabelValues(ExternalSecretName, ExternalSecretNamespace, string(esv1alpha1.ExternalSecretReady), string(v1.ConditionTrue)).Write(&metric)).To(Succeed())
  563. return metric.GetGauge().GetValue()
  564. }, timeout, interval).Should(Equal(0.0))
  565. Eventually(func() float64 {
  566. Expect(externalSecretCondition.WithLabelValues(ExternalSecretName, ExternalSecretNamespace, string(esv1alpha1.ExternalSecretReady), string(v1.ConditionFalse)).Write(&metric)).To(Succeed())
  567. return metric.GetGauge().GetValue()
  568. }, timeout, interval).Should(Equal(0.0))
  569. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1alpha1.ExternalSecretReady, v1.ConditionFalse, 0.0)).To(BeTrue())
  570. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1alpha1.ExternalSecretReady, v1.ConditionTrue, 0.0)).To(BeTrue())
  571. }
  572. }
  573. DescribeTable("When reconciling an ExternalSecret",
  574. func(tweaks ...testTweaks) {
  575. tc := makeDefaultTestcase()
  576. for _, tweak := range tweaks {
  577. tweak(tc)
  578. }
  579. ctx := context.Background()
  580. By("creating a secret store and external secret")
  581. Expect(k8sClient.Create(ctx, tc.secretStore)).To(Succeed())
  582. Expect(k8sClient.Create(ctx, tc.externalSecret)).Should(Succeed())
  583. esKey := types.NamespacedName{Name: ExternalSecretName, Namespace: ExternalSecretNamespace}
  584. createdES := &esv1alpha1.ExternalSecret{}
  585. By("checking the es condition")
  586. Eventually(func() bool {
  587. err := k8sClient.Get(ctx, esKey, createdES)
  588. if err != nil {
  589. return false
  590. }
  591. return tc.checkCondition(createdES)
  592. }, timeout, interval).Should(BeTrue())
  593. tc.checkExternalSecret(createdES)
  594. // this must be optional so we can test faulty es configuration
  595. if tc.checkSecret != nil {
  596. syncedSecret := &v1.Secret{}
  597. secretLookupKey := types.NamespacedName{
  598. Name: ExternalSecretTargetSecretName,
  599. Namespace: ExternalSecretNamespace,
  600. }
  601. Eventually(func() bool {
  602. err := k8sClient.Get(ctx, secretLookupKey, syncedSecret)
  603. return err == nil
  604. }, timeout, interval).Should(BeTrue())
  605. tc.checkSecret(createdES, syncedSecret)
  606. }
  607. },
  608. Entry("should set the condition eventually", syncLabelsAnnotations),
  609. Entry("should merge with existing secret using creationPolicy=Merge", mergeWithSecret),
  610. Entry("should error if sceret doesn't exist when using creationPolicy=Merge", mergeWithSecretErr),
  611. Entry("should not resolve conflicts with creationPolicy=Merge", mergeWithConflict),
  612. Entry("should sync with template", syncWithTemplate),
  613. Entry("should sync template with correct value precedence", syncWithTemplatePrecedence),
  614. Entry("should refresh secret from template", refreshWithTemplate),
  615. Entry("should refresh secret value when provider secret changes", refreshSecretValue),
  616. Entry("should fetch secret using dataFrom", syncWithDataFrom),
  617. Entry("should set error condition when provider errors", providerErrCondition),
  618. Entry("should set an error condition when store does not exist", storeMissingErrCondition),
  619. Entry("should set an error condition when store provider constructor fails", storeConstructErrCondition),
  620. Entry("should not process store with mismatching controller field", ignoreMismatchController),
  621. )
  622. })
  623. var _ = Describe("ExternalSecret refresh logic", func() {
  624. Context("secret refresh", func() {
  625. It("should refresh when resource version does not match", func() {
  626. Expect(shouldRefresh(esv1alpha1.ExternalSecret{
  627. Status: esv1alpha1.ExternalSecretStatus{
  628. SyncedResourceVersion: "some resource version",
  629. },
  630. })).To(BeTrue())
  631. })
  632. It("should refresh when labels change", func() {
  633. es := esv1alpha1.ExternalSecret{
  634. ObjectMeta: metav1.ObjectMeta{
  635. Generation: 1,
  636. Labels: map[string]string{
  637. "foo": "bar",
  638. },
  639. },
  640. Status: esv1alpha1.ExternalSecretStatus{},
  641. }
  642. es.Status.SyncedResourceVersion = getResourceVersion(es)
  643. // this should not refresh, rv matches object
  644. Expect(shouldRefresh(es)).To(BeFalse())
  645. // change labels without changing the syncedResourceVersion and expect refresh
  646. es.ObjectMeta.Labels["new"] = "w00t"
  647. Expect(shouldRefresh(es)).To(BeTrue())
  648. })
  649. It("should refresh when annotations change", func() {
  650. es := esv1alpha1.ExternalSecret{
  651. ObjectMeta: metav1.ObjectMeta{
  652. Generation: 1,
  653. Annotations: map[string]string{
  654. "foo": "bar",
  655. },
  656. },
  657. Status: esv1alpha1.ExternalSecretStatus{},
  658. }
  659. es.Status.SyncedResourceVersion = getResourceVersion(es)
  660. // this should not refresh, rv matches object
  661. Expect(shouldRefresh(es)).To(BeFalse())
  662. // change annotations without changing the syncedResourceVersion and expect refresh
  663. es.ObjectMeta.Annotations["new"] = "w00t"
  664. Expect(shouldRefresh(es)).To(BeTrue())
  665. })
  666. It("should refresh when generation has changed", func() {
  667. es := esv1alpha1.ExternalSecret{
  668. ObjectMeta: metav1.ObjectMeta{
  669. Generation: 1,
  670. },
  671. Status: esv1alpha1.ExternalSecretStatus{},
  672. }
  673. es.Status.SyncedResourceVersion = getResourceVersion(es)
  674. Expect(shouldRefresh(es)).To(BeFalse())
  675. // update gen -> refresh
  676. es.ObjectMeta.Generation = 2
  677. Expect(shouldRefresh(es)).To(BeTrue())
  678. })
  679. It("should skip refresh when refreshInterval is nil", func() {
  680. es := esv1alpha1.ExternalSecret{
  681. ObjectMeta: metav1.ObjectMeta{
  682. Generation: 1,
  683. },
  684. Spec: esv1alpha1.ExternalSecretSpec{
  685. RefreshInterval: nil,
  686. },
  687. Status: esv1alpha1.ExternalSecretStatus{},
  688. }
  689. // resource version matches
  690. es.Status.SyncedResourceVersion = getResourceVersion(es)
  691. Expect(shouldRefresh(es)).To(BeFalse())
  692. })
  693. It("should refresh when refresh interval has passed", func() {
  694. es := esv1alpha1.ExternalSecret{
  695. ObjectMeta: metav1.ObjectMeta{
  696. Generation: 1,
  697. },
  698. Spec: esv1alpha1.ExternalSecretSpec{
  699. RefreshInterval: &metav1.Duration{Duration: time.Second},
  700. },
  701. Status: esv1alpha1.ExternalSecretStatus{
  702. RefreshTime: metav1.NewTime(metav1.Now().Add(-time.Second * 5)),
  703. },
  704. }
  705. // resource version matches
  706. es.Status.SyncedResourceVersion = getResourceVersion(es)
  707. Expect(shouldRefresh(es)).To(BeTrue())
  708. })
  709. It("should refresh when no refresh time was set", func() {
  710. es := esv1alpha1.ExternalSecret{
  711. ObjectMeta: metav1.ObjectMeta{
  712. Generation: 1,
  713. },
  714. Spec: esv1alpha1.ExternalSecretSpec{
  715. RefreshInterval: &metav1.Duration{Duration: time.Second},
  716. },
  717. Status: esv1alpha1.ExternalSecretStatus{},
  718. }
  719. // resource version matches
  720. es.Status.SyncedResourceVersion = getResourceVersion(es)
  721. Expect(shouldRefresh(es)).To(BeTrue())
  722. })
  723. })
  724. Context("objectmeta hash", func() {
  725. It("should produce different hashes for different k/v pairs", func() {
  726. h1 := hashMeta(metav1.ObjectMeta{
  727. Generation: 1,
  728. Annotations: map[string]string{
  729. "foo": "bar",
  730. },
  731. })
  732. h2 := hashMeta(metav1.ObjectMeta{
  733. Generation: 1,
  734. Annotations: map[string]string{
  735. "foo": "bing",
  736. },
  737. })
  738. Expect(h1).ToNot(Equal(h2))
  739. })
  740. It("should produce different hashes for different generations but same label/annotations", func() {
  741. h1 := hashMeta(metav1.ObjectMeta{
  742. Generation: 1,
  743. Annotations: map[string]string{
  744. "foo": "bar",
  745. },
  746. Labels: map[string]string{
  747. "foo": "bar",
  748. },
  749. })
  750. h2 := hashMeta(metav1.ObjectMeta{
  751. Generation: 2,
  752. Annotations: map[string]string{
  753. "foo": "bar",
  754. },
  755. Labels: map[string]string{
  756. "foo": "bar",
  757. },
  758. })
  759. Expect(h1).To(Equal(h2))
  760. })
  761. It("should produce the same hash for the same k/v pairs", func() {
  762. h1 := hashMeta(metav1.ObjectMeta{
  763. Generation: 1,
  764. })
  765. h2 := hashMeta(metav1.ObjectMeta{
  766. Generation: 1,
  767. })
  768. Expect(h1).To(Equal(h2))
  769. h1 = hashMeta(metav1.ObjectMeta{
  770. Generation: 1,
  771. Annotations: map[string]string{
  772. "foo": "bar",
  773. },
  774. })
  775. h2 = hashMeta(metav1.ObjectMeta{
  776. Generation: 1,
  777. Annotations: map[string]string{
  778. "foo": "bar",
  779. },
  780. })
  781. Expect(h1).To(Equal(h2))
  782. })
  783. })
  784. })
  785. // CreateNamespace creates a new namespace in the cluster.
  786. func CreateNamespace(baseName string, c client.Client) (string, error) {
  787. genName := fmt.Sprintf("ctrl-test-%v", baseName)
  788. ns := &v1.Namespace{
  789. ObjectMeta: metav1.ObjectMeta{
  790. GenerateName: genName,
  791. },
  792. }
  793. var err error
  794. err = wait.Poll(time.Second, 10*time.Second, func() (bool, error) {
  795. err = c.Create(context.Background(), ns)
  796. if err != nil {
  797. return false, nil
  798. }
  799. return true, nil
  800. })
  801. if err != nil {
  802. return "", err
  803. }
  804. return ns.Name, nil
  805. }
  806. func hasOwnerRef(meta metav1.ObjectMeta, kind, name string) bool {
  807. for _, ref := range meta.OwnerReferences {
  808. if ref.Kind == kind && ref.Name == name {
  809. return true
  810. }
  811. }
  812. return false
  813. }
  814. func hasFieldOwnership(meta metav1.ObjectMeta, mgr, rawFields string) bool {
  815. for _, ref := range meta.ManagedFields {
  816. if ref.Manager == mgr && string(ref.FieldsV1.Raw) == rawFields {
  817. return true
  818. }
  819. }
  820. return false
  821. }
  822. func externalSecretConditionShouldBe(name, ns string, ct esv1alpha1.ExternalSecretConditionType, cs v1.ConditionStatus, v float64) bool {
  823. return Eventually(func() float64 {
  824. Expect(externalSecretCondition.WithLabelValues(name, ns, string(ct), string(cs)).Write(&metric)).To(Succeed())
  825. return metric.GetGauge().GetValue()
  826. }, timeout, interval).Should(Equal(v))
  827. }
  828. func init() {
  829. fakeProvider = fake.New()
  830. schema.ForceRegister(fakeProvider, &esv1alpha1.SecretStoreProvider{
  831. AWS: &esv1alpha1.AWSProvider{
  832. Service: esv1alpha1.AWSServiceSecretsManager,
  833. },
  834. })
  835. }