externalsecret_controller_test.go 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223
  1. /*
  2. Licensed under the Apache License, Version 2.0 (the "License");
  3. you may not use this file except in compliance with the License.
  4. You may obtain a copy of the License at
  5. http://www.apache.org/licenses/LICENSE-2.0
  6. Unless required by applicable law or agreed to in writing, software
  7. distributed under the License is distributed on an "AS IS" BASIS,
  8. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. See the License for the specific language governing permissions and
  10. limitations under the License.
  11. */
  12. package externalsecret
  13. import (
  14. "context"
  15. "fmt"
  16. "os"
  17. "strconv"
  18. "time"
  19. . "github.com/onsi/ginkgo/v2"
  20. . "github.com/onsi/gomega"
  21. dto "github.com/prometheus/client_model/go"
  22. v1 "k8s.io/api/core/v1"
  23. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  24. "k8s.io/apimachinery/pkg/types"
  25. "k8s.io/apimachinery/pkg/util/wait"
  26. "sigs.k8s.io/controller-runtime/pkg/client"
  27. esv1alpha1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1alpha1"
  28. "github.com/external-secrets/external-secrets/pkg/provider"
  29. "github.com/external-secrets/external-secrets/pkg/provider/fake"
  30. "github.com/external-secrets/external-secrets/pkg/provider/schema"
  31. )
  32. var (
  33. fakeProvider *fake.Client
  34. metric dto.Metric
  35. timeout = time.Second * 10
  36. interval = time.Millisecond * 250
  37. )
  38. type testCase struct {
  39. secretStore *esv1alpha1.SecretStore
  40. externalSecret *esv1alpha1.ExternalSecret
  41. // checkCondition should return true if the externalSecret
  42. // has the expected condition
  43. checkCondition func(*esv1alpha1.ExternalSecret) bool
  44. // checkExternalSecret is called after the condition has been verified
  45. // use this to verify the externalSecret
  46. checkExternalSecret func(*esv1alpha1.ExternalSecret)
  47. // optional. use this to test the secret value
  48. checkSecret func(*esv1alpha1.ExternalSecret, *v1.Secret)
  49. }
  50. type testTweaks func(*testCase)
  51. var _ = Describe("Kind=secret existence logic", func() {
  52. type testCase struct {
  53. Name string
  54. Input v1.Secret
  55. ExpectedOutput bool
  56. }
  57. tests := []testCase{
  58. {
  59. Name: "Should not be valid in case of missing uid",
  60. Input: v1.Secret{},
  61. ExpectedOutput: false,
  62. },
  63. {
  64. Name: "A nil annotation should not be valid",
  65. Input: v1.Secret{
  66. ObjectMeta: metav1.ObjectMeta{
  67. UID: "xxx",
  68. Annotations: map[string]string{},
  69. },
  70. },
  71. ExpectedOutput: false,
  72. },
  73. {
  74. Name: "A nil annotation should not be valid",
  75. Input: v1.Secret{
  76. ObjectMeta: metav1.ObjectMeta{
  77. UID: "xxx",
  78. Annotations: map[string]string{},
  79. },
  80. },
  81. ExpectedOutput: false,
  82. },
  83. {
  84. Name: "An invalid annotation hash should not be valid",
  85. Input: v1.Secret{
  86. ObjectMeta: metav1.ObjectMeta{
  87. UID: "xxx",
  88. Annotations: map[string]string{
  89. esv1alpha1.AnnotationDataHash: "xxxxxx",
  90. },
  91. },
  92. },
  93. ExpectedOutput: false,
  94. },
  95. {
  96. Name: "A valid config map should return true",
  97. Input: v1.Secret{
  98. ObjectMeta: metav1.ObjectMeta{
  99. UID: "xxx",
  100. Annotations: map[string]string{
  101. esv1alpha1.AnnotationDataHash: "caa0155759a6a9b3b6ada5a6883ee2bb",
  102. },
  103. },
  104. Data: map[string][]byte{
  105. "foo": []byte("value1"),
  106. "bar": []byte("value2"),
  107. },
  108. },
  109. ExpectedOutput: true,
  110. },
  111. }
  112. for _, tt := range tests {
  113. It(tt.Name, func() {
  114. Expect(isSecretValid(tt.Input)).To(BeEquivalentTo(tt.ExpectedOutput))
  115. })
  116. }
  117. })
  118. var _ = Describe("ExternalSecret controller", func() {
  119. const (
  120. ExternalSecretName = "test-es"
  121. ExternalSecretStore = "test-store"
  122. ExternalSecretTargetSecretName = "test-secret"
  123. FakeManager = "fake.manager"
  124. expectedSecretVal = "SOMEVALUE was templated"
  125. targetPropObj = "{{ .targetProperty | toString | upper }} was templated"
  126. FooValue = "map-foo-value"
  127. BarValue = "map-bar-value"
  128. )
  129. var ExternalSecretNamespace string
  130. // if we are in debug and need to increase the timeout for testing, we can do so by using an env var
  131. if customTimeout := os.Getenv("TEST_CUSTOM_TIMEOUT_SEC"); customTimeout != "" {
  132. if t, err := strconv.Atoi(customTimeout); err == nil {
  133. timeout = time.Second * time.Duration(t)
  134. }
  135. }
  136. BeforeEach(func() {
  137. var err error
  138. ExternalSecretNamespace, err = CreateNamespace("test-ns", k8sClient)
  139. Expect(err).ToNot(HaveOccurred())
  140. metric.Reset()
  141. syncCallsTotal.Reset()
  142. syncCallsError.Reset()
  143. externalSecretCondition.Reset()
  144. })
  145. AfterEach(func() {
  146. Expect(k8sClient.Delete(context.Background(), &v1.Namespace{
  147. ObjectMeta: metav1.ObjectMeta{
  148. Name: ExternalSecretNamespace,
  149. },
  150. }, client.PropagationPolicy(metav1.DeletePropagationBackground)), client.GracePeriodSeconds(0)).To(Succeed())
  151. Expect(k8sClient.Delete(context.Background(), &esv1alpha1.SecretStore{
  152. ObjectMeta: metav1.ObjectMeta{
  153. Name: ExternalSecretStore,
  154. Namespace: ExternalSecretNamespace,
  155. },
  156. }, client.PropagationPolicy(metav1.DeletePropagationBackground)), client.GracePeriodSeconds(0)).To(Succeed())
  157. })
  158. const targetProp = "targetProperty"
  159. const remoteKey = "barz"
  160. const remoteProperty = "bang"
  161. makeDefaultTestcase := func() *testCase {
  162. return &testCase{
  163. // default condition: es should be ready
  164. checkCondition: func(es *esv1alpha1.ExternalSecret) bool {
  165. cond := GetExternalSecretCondition(es.Status, esv1alpha1.ExternalSecretReady)
  166. if cond == nil || cond.Status != v1.ConditionTrue {
  167. return false
  168. }
  169. return true
  170. },
  171. checkExternalSecret: func(es *esv1alpha1.ExternalSecret) {},
  172. secretStore: &esv1alpha1.SecretStore{
  173. ObjectMeta: metav1.ObjectMeta{
  174. Name: ExternalSecretStore,
  175. Namespace: ExternalSecretNamespace,
  176. },
  177. Spec: esv1alpha1.SecretStoreSpec{
  178. Provider: &esv1alpha1.SecretStoreProvider{
  179. AWS: &esv1alpha1.AWSProvider{
  180. Service: esv1alpha1.AWSServiceSecretsManager,
  181. },
  182. },
  183. },
  184. },
  185. externalSecret: &esv1alpha1.ExternalSecret{
  186. ObjectMeta: metav1.ObjectMeta{
  187. Name: ExternalSecretName,
  188. Namespace: ExternalSecretNamespace,
  189. },
  190. Spec: esv1alpha1.ExternalSecretSpec{
  191. SecretStoreRef: esv1alpha1.SecretStoreRef{
  192. Name: ExternalSecretStore,
  193. },
  194. Target: esv1alpha1.ExternalSecretTarget{
  195. Name: ExternalSecretTargetSecretName,
  196. },
  197. Data: []esv1alpha1.ExternalSecretData{
  198. {
  199. SecretKey: targetProp,
  200. RemoteRef: esv1alpha1.ExternalSecretDataRemoteRef{
  201. Key: remoteKey,
  202. Property: remoteProperty,
  203. },
  204. },
  205. },
  206. },
  207. },
  208. }
  209. }
  210. // if target Secret name is not specified it should use the ExternalSecret name.
  211. syncWithoutTargetName := func(tc *testCase) {
  212. tc.externalSecret.Spec.Target.Name = ""
  213. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  214. // check secret name
  215. Expect(secret.ObjectMeta.Name).To(Equal(ExternalSecretName))
  216. }
  217. }
  218. // labels and annotations from the Kind=ExternalSecret
  219. // should be copied over to the Kind=Secret
  220. syncLabelsAnnotations := func(tc *testCase) {
  221. const secretVal = "someValue"
  222. tc.externalSecret.ObjectMeta.Labels = map[string]string{
  223. "fooobar": "bazz",
  224. }
  225. tc.externalSecret.ObjectMeta.Annotations = map[string]string{
  226. "hihihih": "hehehe",
  227. }
  228. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  229. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  230. // check value
  231. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  232. // check labels & annotations
  233. Expect(secret.ObjectMeta.Labels).To(BeEquivalentTo(es.ObjectMeta.Labels))
  234. for k, v := range es.ObjectMeta.Annotations {
  235. Expect(secret.ObjectMeta.Annotations).To(HaveKeyWithValue(k, v))
  236. }
  237. // ownerRef must not not be set!
  238. Expect(hasOwnerRef(secret.ObjectMeta, "ExternalSecret", ExternalSecretName)).To(BeTrue())
  239. }
  240. }
  241. checkPrometheusCounters := func(tc *testCase) {
  242. const secretVal = "someValue"
  243. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  244. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  245. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1alpha1.ExternalSecretReady, v1.ConditionFalse, 0.0)).To(BeTrue())
  246. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1alpha1.ExternalSecretReady, v1.ConditionTrue, 1.0)).To(BeTrue())
  247. Eventually(func() bool {
  248. Expect(syncCallsTotal.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metric)).To(Succeed())
  249. return metric.GetCounter().GetValue() == 1.0
  250. }, timeout, interval).Should(BeTrue())
  251. }
  252. }
  253. // merge with existing secret using creationPolicy=Merge
  254. // it should NOT have a ownerReference
  255. // metadata.managedFields with the correct owner should be added to the secret
  256. mergeWithSecret := func(tc *testCase) {
  257. const secretVal = "someValue"
  258. const existingKey = "pre-existing-key"
  259. existingVal := "pre-existing-value"
  260. tc.externalSecret.Spec.Target.CreationPolicy = esv1alpha1.Merge
  261. // create secret beforehand
  262. Expect(k8sClient.Create(context.Background(), &v1.Secret{
  263. ObjectMeta: metav1.ObjectMeta{
  264. Name: ExternalSecretTargetSecretName,
  265. Namespace: ExternalSecretNamespace,
  266. },
  267. Data: map[string][]byte{
  268. existingKey: []byte(existingVal),
  269. },
  270. }, client.FieldOwner(FakeManager))).To(Succeed())
  271. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  272. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  273. // check value
  274. Expect(string(secret.Data[existingKey])).To(Equal(existingVal))
  275. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  276. // check labels & annotations
  277. Expect(secret.ObjectMeta.Labels).To(BeEquivalentTo(es.ObjectMeta.Labels))
  278. for k, v := range es.ObjectMeta.Annotations {
  279. Expect(secret.ObjectMeta.Annotations).To(HaveKeyWithValue(k, v))
  280. }
  281. Expect(hasOwnerRef(secret.ObjectMeta, "ExternalSecret", ExternalSecretName)).To(BeFalse())
  282. Expect(secret.ObjectMeta.ManagedFields).To(HaveLen(2))
  283. Expect(hasFieldOwnership(
  284. secret.ObjectMeta,
  285. "external-secrets",
  286. fmt.Sprintf("{\"f:data\":{\"f:targetProperty\":{}},\"f:immutable\":{},\"f:metadata\":{\"f:annotations\":{\"f:%s\":{}}}}", esv1alpha1.AnnotationDataHash)),
  287. ).To(BeTrue())
  288. Expect(hasFieldOwnership(secret.ObjectMeta, FakeManager, "{\"f:data\":{\".\":{},\"f:pre-existing-key\":{}},\"f:type\":{}}")).To(BeTrue())
  289. }
  290. }
  291. // should not merge with secret if it doesn't exist
  292. mergeWithSecretErr := func(tc *testCase) {
  293. const secretVal = "someValue"
  294. tc.externalSecret.Spec.Target.CreationPolicy = esv1alpha1.Merge
  295. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  296. tc.checkCondition = func(es *esv1alpha1.ExternalSecret) bool {
  297. cond := GetExternalSecretCondition(es.Status, esv1alpha1.ExternalSecretReady)
  298. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1alpha1.ConditionReasonSecretSyncedError {
  299. return false
  300. }
  301. return true
  302. }
  303. tc.checkExternalSecret = func(es *esv1alpha1.ExternalSecret) {
  304. Eventually(func() bool {
  305. Expect(syncCallsError.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metric)).To(Succeed())
  306. return metric.GetCounter().GetValue() >= 2.0
  307. }, timeout, interval).Should(BeTrue())
  308. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1alpha1.ExternalSecretReady, v1.ConditionFalse, 1.0)).To(BeTrue())
  309. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1alpha1.ExternalSecretReady, v1.ConditionTrue, 0.0)).To(BeTrue())
  310. }
  311. }
  312. // controller should force ownership
  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.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  331. // check that value stays the same
  332. Expect(string(secret.Data[existingKey])).To(Equal(secretVal))
  333. // check owner/managedFields
  334. Expect(hasOwnerRef(secret.ObjectMeta, "ExternalSecret", ExternalSecretName)).To(BeFalse())
  335. Expect(secret.ObjectMeta.ManagedFields).To(HaveLen(2))
  336. Expect(hasFieldOwnership(secret.ObjectMeta, "external-secrets", "{\"f:data\":{\"f:targetProperty\":{}},\"f:immutable\":{},\"f:metadata\":{\"f:annotations\":{\"f:reconcile.external-secrets.io/data-hash\":{}}}}")).To(BeTrue())
  337. }
  338. }
  339. // when using a template it should be used as a blueprint
  340. // to construct a new secret: labels, annotations and type
  341. syncWithTemplate := func(tc *testCase) {
  342. const secretVal = "someValue"
  343. const tplStaticKey = "tplstatickey"
  344. const tplStaticVal = "tplstaticvalue"
  345. tc.externalSecret.ObjectMeta.Labels = map[string]string{
  346. "fooobar": "bazz",
  347. }
  348. tc.externalSecret.ObjectMeta.Annotations = map[string]string{
  349. "hihihih": "hehehe",
  350. }
  351. tc.externalSecret.Spec.Target.Template = &esv1alpha1.ExternalSecretTemplate{
  352. Metadata: esv1alpha1.ExternalSecretTemplateMetadata{
  353. Labels: map[string]string{
  354. "foos": "ball",
  355. },
  356. Annotations: map[string]string{
  357. "hihi": "ga",
  358. },
  359. },
  360. Type: v1.SecretTypeOpaque,
  361. Data: map[string]string{
  362. targetProp: targetPropObj,
  363. tplStaticKey: tplStaticVal,
  364. },
  365. }
  366. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  367. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  368. // check values
  369. Expect(string(secret.Data[targetProp])).To(Equal(expectedSecretVal))
  370. Expect(string(secret.Data[tplStaticKey])).To(Equal(tplStaticVal))
  371. // labels/annotations should be taken from the template
  372. Expect(secret.ObjectMeta.Labels).To(BeEquivalentTo(es.Spec.Target.Template.Metadata.Labels))
  373. for k, v := range es.Spec.Target.Template.Metadata.Annotations {
  374. Expect(secret.ObjectMeta.Annotations).To(HaveKeyWithValue(k, v))
  375. }
  376. }
  377. }
  378. // secret should be synced with correct value precedence:
  379. // * template
  380. // * templateFrom
  381. // * data
  382. // * dataFrom
  383. syncWithTemplatePrecedence := func(tc *testCase) {
  384. const secretVal = "someValue"
  385. const tplStaticKey = "tplstatickey"
  386. const tplStaticVal = "tplstaticvalue"
  387. const tplFromCMName = "template-cm"
  388. const tplFromSecretName = "template-secret"
  389. const tplFromKey = "tpl-from-key"
  390. const tplFromSecKey = "tpl-from-sec-key"
  391. const tplFromVal = "tpl-from-value: {{ .targetProperty | toString }} // {{ .bar | toString }}"
  392. const tplFromSecVal = "tpl-from-sec-value: {{ .targetProperty | toString }} // {{ .bar | toString }}"
  393. Expect(k8sClient.Create(context.Background(), &v1.ConfigMap{
  394. ObjectMeta: metav1.ObjectMeta{
  395. Name: tplFromCMName,
  396. Namespace: ExternalSecretNamespace,
  397. },
  398. Data: map[string]string{
  399. tplFromKey: tplFromVal,
  400. },
  401. })).To(Succeed())
  402. Expect(k8sClient.Create(context.Background(), &v1.Secret{
  403. ObjectMeta: metav1.ObjectMeta{
  404. Name: tplFromSecretName,
  405. Namespace: ExternalSecretNamespace,
  406. },
  407. Data: map[string][]byte{
  408. tplFromSecKey: []byte(tplFromSecVal),
  409. },
  410. })).To(Succeed())
  411. tc.externalSecret.Spec.Target.Template = &esv1alpha1.ExternalSecretTemplate{
  412. Metadata: esv1alpha1.ExternalSecretTemplateMetadata{},
  413. Type: v1.SecretTypeOpaque,
  414. TemplateFrom: []esv1alpha1.TemplateFrom{
  415. {
  416. ConfigMap: &esv1alpha1.TemplateRef{
  417. Name: tplFromCMName,
  418. Items: []esv1alpha1.TemplateRefItem{
  419. {
  420. Key: tplFromKey,
  421. },
  422. },
  423. },
  424. },
  425. {
  426. Secret: &esv1alpha1.TemplateRef{
  427. Name: tplFromSecretName,
  428. Items: []esv1alpha1.TemplateRefItem{
  429. {
  430. Key: tplFromSecKey,
  431. },
  432. },
  433. },
  434. },
  435. },
  436. Data: map[string]string{
  437. // this should be the data value, not dataFrom
  438. targetProp: targetPropObj,
  439. // this should use the value from the map
  440. "bar": "value from map: {{ .bar | toString }}",
  441. // just a static value
  442. tplStaticKey: tplStaticVal,
  443. },
  444. }
  445. tc.externalSecret.Spec.DataFrom = []esv1alpha1.ExternalSecretDataRemoteRef{
  446. {
  447. Key: "datamap",
  448. },
  449. }
  450. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  451. fakeProvider.WithGetSecretMap(map[string][]byte{
  452. "targetProperty": []byte(FooValue),
  453. "bar": []byte(BarValue),
  454. }, nil)
  455. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  456. // check values
  457. Expect(string(secret.Data[targetProp])).To(Equal(expectedSecretVal))
  458. Expect(string(secret.Data[tplStaticKey])).To(Equal(tplStaticVal))
  459. Expect(string(secret.Data["bar"])).To(Equal("value from map: map-bar-value"))
  460. Expect(string(secret.Data[tplFromKey])).To(Equal("tpl-from-value: someValue // map-bar-value"))
  461. Expect(string(secret.Data[tplFromSecKey])).To(Equal("tpl-from-sec-value: someValue // map-bar-value"))
  462. }
  463. }
  464. refreshWithTemplate := func(tc *testCase) {
  465. const secretVal = "someValue"
  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: targetPropObj,
  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(FooValue),
  604. "bar": []byte(BarValue),
  605. }, nil)
  606. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  607. // check values
  608. Expect(string(secret.Data["foo"])).To(Equal(FooValue))
  609. Expect(string(secret.Data["bar"])).To(Equal(BarValue))
  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(FooValue),
  629. "tls.key": []byte(BarValue),
  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(FooValue))
  635. Expect(string(secret.Data["tls.key"])).To(Equal(BarValue))
  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(FooValue),
  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. if createdES.Spec.Target.Name == "" {
  836. secretLookupKey = types.NamespacedName{
  837. Name: ExternalSecretName,
  838. Namespace: ExternalSecretNamespace,
  839. }
  840. }
  841. Eventually(func() bool {
  842. err := k8sClient.Get(ctx, secretLookupKey, syncedSecret)
  843. return err == nil
  844. }, timeout, interval).Should(BeTrue())
  845. tc.checkSecret(createdES, syncedSecret)
  846. }
  847. },
  848. Entry("should recreate deleted secret", checkDeletion),
  849. Entry("should create proper hash annotation for the external secret", checkSecretDataHashAnnotation),
  850. Entry("should refresh when the hash annotation doesn't correspond to secret data", checkSecretDataHashAnnotationChange),
  851. Entry("should use external secret name if target secret name isn't defined", syncWithoutTargetName),
  852. Entry("should set the condition eventually", syncLabelsAnnotations),
  853. Entry("should set prometheus counters", checkPrometheusCounters),
  854. Entry("should merge with existing secret using creationPolicy=Merge", mergeWithSecret),
  855. Entry("should error if secret doesn't exist when using creationPolicy=Merge", mergeWithSecretErr),
  856. Entry("should not resolve conflicts with creationPolicy=Merge", mergeWithConflict),
  857. Entry("should sync with template", syncWithTemplate),
  858. Entry("should sync template with correct value precedence", syncWithTemplatePrecedence),
  859. Entry("should refresh secret from template", refreshWithTemplate),
  860. Entry("should be able to use only metadata from template", onlyMetadataFromTemplate),
  861. Entry("should refresh secret value when provider secret changes", refreshSecretValue),
  862. Entry("should not refresh secret value when provider secret changes but refreshInterval is zero", refreshintervalZero),
  863. Entry("should fetch secret using dataFrom", syncWithDataFrom),
  864. Entry("should fetch secret using dataFrom and a template", syncWithDataFromTemplate),
  865. Entry("should set error condition when provider errors", providerErrCondition),
  866. Entry("should set an error condition when store does not exist", storeMissingErrCondition),
  867. Entry("should set an error condition when store provider constructor fails", storeConstructErrCondition),
  868. Entry("should not process store with mismatching controller field", ignoreMismatchController),
  869. )
  870. })
  871. var _ = Describe("ExternalSecret refresh logic", func() {
  872. Context("secret refresh", func() {
  873. It("should refresh when resource version does not match", func() {
  874. Expect(shouldRefresh(esv1alpha1.ExternalSecret{
  875. Status: esv1alpha1.ExternalSecretStatus{
  876. SyncedResourceVersion: "some resource version",
  877. },
  878. })).To(BeTrue())
  879. })
  880. It("should refresh when labels change", func() {
  881. es := esv1alpha1.ExternalSecret{
  882. ObjectMeta: metav1.ObjectMeta{
  883. Generation: 1,
  884. Labels: map[string]string{
  885. "foo": "bar",
  886. },
  887. },
  888. Spec: esv1alpha1.ExternalSecretSpec{
  889. RefreshInterval: &metav1.Duration{Duration: time.Minute},
  890. },
  891. Status: esv1alpha1.ExternalSecretStatus{
  892. RefreshTime: metav1.Now(),
  893. },
  894. }
  895. es.Status.SyncedResourceVersion = getResourceVersion(es)
  896. // this should not refresh, rv matches object
  897. Expect(shouldRefresh(es)).To(BeFalse())
  898. // change labels without changing the syncedResourceVersion and expect refresh
  899. es.ObjectMeta.Labels["new"] = "w00t"
  900. Expect(shouldRefresh(es)).To(BeTrue())
  901. })
  902. It("should refresh when annotations change", func() {
  903. es := esv1alpha1.ExternalSecret{
  904. ObjectMeta: metav1.ObjectMeta{
  905. Generation: 1,
  906. Annotations: map[string]string{
  907. "foo": "bar",
  908. },
  909. },
  910. Spec: esv1alpha1.ExternalSecretSpec{
  911. RefreshInterval: &metav1.Duration{Duration: time.Minute},
  912. },
  913. Status: esv1alpha1.ExternalSecretStatus{
  914. RefreshTime: metav1.Now(),
  915. },
  916. }
  917. es.Status.SyncedResourceVersion = getResourceVersion(es)
  918. // this should not refresh, rv matches object
  919. Expect(shouldRefresh(es)).To(BeFalse())
  920. // change annotations without changing the syncedResourceVersion and expect refresh
  921. es.ObjectMeta.Annotations["new"] = "w00t"
  922. Expect(shouldRefresh(es)).To(BeTrue())
  923. })
  924. It("should refresh when generation has changed", func() {
  925. es := esv1alpha1.ExternalSecret{
  926. ObjectMeta: metav1.ObjectMeta{
  927. Generation: 1,
  928. },
  929. Spec: esv1alpha1.ExternalSecretSpec{
  930. RefreshInterval: &metav1.Duration{Duration: 0},
  931. },
  932. Status: esv1alpha1.ExternalSecretStatus{
  933. RefreshTime: metav1.Now(),
  934. },
  935. }
  936. es.Status.SyncedResourceVersion = getResourceVersion(es)
  937. Expect(shouldRefresh(es)).To(BeFalse())
  938. // update gen -> refresh
  939. es.ObjectMeta.Generation = 2
  940. Expect(shouldRefresh(es)).To(BeTrue())
  941. })
  942. It("should skip refresh when refreshInterval is 0", func() {
  943. es := esv1alpha1.ExternalSecret{
  944. ObjectMeta: metav1.ObjectMeta{
  945. Generation: 1,
  946. },
  947. Spec: esv1alpha1.ExternalSecretSpec{
  948. RefreshInterval: &metav1.Duration{Duration: 0},
  949. },
  950. Status: esv1alpha1.ExternalSecretStatus{},
  951. }
  952. // resource version matches
  953. es.Status.SyncedResourceVersion = getResourceVersion(es)
  954. Expect(shouldRefresh(es)).To(BeFalse())
  955. })
  956. It("should refresh when refresh interval has passed", func() {
  957. es := esv1alpha1.ExternalSecret{
  958. ObjectMeta: metav1.ObjectMeta{
  959. Generation: 1,
  960. },
  961. Spec: esv1alpha1.ExternalSecretSpec{
  962. RefreshInterval: &metav1.Duration{Duration: time.Second},
  963. },
  964. Status: esv1alpha1.ExternalSecretStatus{
  965. RefreshTime: metav1.NewTime(metav1.Now().Add(-time.Second * 5)),
  966. },
  967. }
  968. // resource version matches
  969. es.Status.SyncedResourceVersion = getResourceVersion(es)
  970. Expect(shouldRefresh(es)).To(BeTrue())
  971. })
  972. It("should refresh when no refresh time was set", func() {
  973. es := esv1alpha1.ExternalSecret{
  974. ObjectMeta: metav1.ObjectMeta{
  975. Generation: 1,
  976. },
  977. Spec: esv1alpha1.ExternalSecretSpec{
  978. RefreshInterval: &metav1.Duration{Duration: time.Second},
  979. },
  980. Status: esv1alpha1.ExternalSecretStatus{},
  981. }
  982. // resource version matches
  983. es.Status.SyncedResourceVersion = getResourceVersion(es)
  984. Expect(shouldRefresh(es)).To(BeTrue())
  985. })
  986. })
  987. Context("objectmeta hash", func() {
  988. It("should produce different hashes for different k/v pairs", func() {
  989. h1 := hashMeta(metav1.ObjectMeta{
  990. Generation: 1,
  991. Annotations: map[string]string{
  992. "foo": "bar",
  993. },
  994. })
  995. h2 := hashMeta(metav1.ObjectMeta{
  996. Generation: 1,
  997. Annotations: map[string]string{
  998. "foo": "bing",
  999. },
  1000. })
  1001. Expect(h1).ToNot(Equal(h2))
  1002. })
  1003. It("should produce different hashes for different generations but same label/annotations", func() {
  1004. h1 := hashMeta(metav1.ObjectMeta{
  1005. Generation: 1,
  1006. Annotations: map[string]string{
  1007. "foo": "bar",
  1008. },
  1009. Labels: map[string]string{
  1010. "foo": "bar",
  1011. },
  1012. })
  1013. h2 := hashMeta(metav1.ObjectMeta{
  1014. Generation: 2,
  1015. Annotations: map[string]string{
  1016. "foo": "bar",
  1017. },
  1018. Labels: map[string]string{
  1019. "foo": "bar",
  1020. },
  1021. })
  1022. Expect(h1).To(Equal(h2))
  1023. })
  1024. It("should produce the same hash for the same k/v pairs", func() {
  1025. h1 := hashMeta(metav1.ObjectMeta{
  1026. Generation: 1,
  1027. })
  1028. h2 := hashMeta(metav1.ObjectMeta{
  1029. Generation: 1,
  1030. })
  1031. Expect(h1).To(Equal(h2))
  1032. h1 = hashMeta(metav1.ObjectMeta{
  1033. Generation: 1,
  1034. Annotations: map[string]string{
  1035. "foo": "bar",
  1036. },
  1037. })
  1038. h2 = hashMeta(metav1.ObjectMeta{
  1039. Generation: 1,
  1040. Annotations: map[string]string{
  1041. "foo": "bar",
  1042. },
  1043. })
  1044. Expect(h1).To(Equal(h2))
  1045. })
  1046. })
  1047. })
  1048. var _ = Describe("Controller Reconcile logic", func() {
  1049. Context("controller reconcile", func() {
  1050. It("should reconcile when resource is not synced", func() {
  1051. Expect(shouldReconcile(esv1alpha1.ExternalSecret{
  1052. Status: esv1alpha1.ExternalSecretStatus{
  1053. SyncedResourceVersion: "some resource version",
  1054. Conditions: []esv1alpha1.ExternalSecretStatusCondition{{Reason: "NotASecretSynced"}},
  1055. },
  1056. })).To(BeTrue())
  1057. })
  1058. It("should reconcile when secret isn't immutable", func() {
  1059. Expect(shouldReconcile(esv1alpha1.ExternalSecret{
  1060. Spec: esv1alpha1.ExternalSecretSpec{
  1061. Target: esv1alpha1.ExternalSecretTarget{
  1062. Immutable: false,
  1063. },
  1064. },
  1065. })).To(BeTrue())
  1066. })
  1067. It("should not reconcile if secret is immutable and has synced condition", func() {
  1068. Expect(shouldReconcile(esv1alpha1.ExternalSecret{
  1069. Spec: esv1alpha1.ExternalSecretSpec{
  1070. Target: esv1alpha1.ExternalSecretTarget{
  1071. Immutable: true,
  1072. },
  1073. },
  1074. Status: esv1alpha1.ExternalSecretStatus{
  1075. SyncedResourceVersion: "some resource version",
  1076. Conditions: []esv1alpha1.ExternalSecretStatusCondition{{Reason: "SecretSynced"}},
  1077. },
  1078. })).To(BeFalse())
  1079. })
  1080. })
  1081. })
  1082. // CreateNamespace creates a new namespace in the cluster.
  1083. func CreateNamespace(baseName string, c client.Client) (string, error) {
  1084. genName := fmt.Sprintf("ctrl-test-%v", baseName)
  1085. ns := &v1.Namespace{
  1086. ObjectMeta: metav1.ObjectMeta{
  1087. GenerateName: genName,
  1088. },
  1089. }
  1090. var err error
  1091. err = wait.Poll(time.Second, 10*time.Second, func() (bool, error) {
  1092. err = c.Create(context.Background(), ns)
  1093. if err != nil {
  1094. return false, nil
  1095. }
  1096. return true, nil
  1097. })
  1098. if err != nil {
  1099. return "", err
  1100. }
  1101. return ns.Name, nil
  1102. }
  1103. func hasOwnerRef(meta metav1.ObjectMeta, kind, name string) bool {
  1104. for _, ref := range meta.OwnerReferences {
  1105. if ref.Kind == kind && ref.Name == name {
  1106. return true
  1107. }
  1108. }
  1109. return false
  1110. }
  1111. func hasFieldOwnership(meta metav1.ObjectMeta, mgr, rawFields string) bool {
  1112. for _, ref := range meta.ManagedFields {
  1113. if ref.Manager == mgr && string(ref.FieldsV1.Raw) == rawFields {
  1114. return true
  1115. }
  1116. }
  1117. return false
  1118. }
  1119. func externalSecretConditionShouldBe(name, ns string, ct esv1alpha1.ExternalSecretConditionType, cs v1.ConditionStatus, v float64) bool {
  1120. return Eventually(func() float64 {
  1121. Expect(externalSecretCondition.WithLabelValues(name, ns, string(ct), string(cs)).Write(&metric)).To(Succeed())
  1122. return metric.GetGauge().GetValue()
  1123. }, timeout, interval).Should(Equal(v))
  1124. }
  1125. func init() {
  1126. fakeProvider = fake.New()
  1127. schema.ForceRegister(fakeProvider, &esv1alpha1.SecretStoreProvider{
  1128. AWS: &esv1alpha1.AWSProvider{
  1129. Service: esv1alpha1.AWSServiceSecretsManager,
  1130. },
  1131. })
  1132. }