externalsecret_controller_test.go 44 KB

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