externalsecret_controller_test.go 44 KB

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