externalsecret_controller_test.go 42 KB

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