externalsecret_controller_test.go 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709
  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. "bytes"
  15. "context"
  16. "fmt"
  17. "os"
  18. "strconv"
  19. "time"
  20. . "github.com/onsi/ginkgo/v2"
  21. . "github.com/onsi/gomega"
  22. dto "github.com/prometheus/client_model/go"
  23. v1 "k8s.io/api/core/v1"
  24. apierrors "k8s.io/apimachinery/pkg/api/errors"
  25. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  26. "k8s.io/apimachinery/pkg/types"
  27. "sigs.k8s.io/controller-runtime/pkg/client"
  28. esv1beta1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1beta1"
  29. ctest "github.com/external-secrets/external-secrets/pkg/controllers/commontest"
  30. "github.com/external-secrets/external-secrets/pkg/provider/testing/fake"
  31. )
  32. var (
  33. fakeProvider *fake.Client
  34. metric dto.Metric
  35. timeout = time.Second * 10
  36. interval = time.Millisecond * 250
  37. )
  38. type testCase struct {
  39. secretStore *esv1beta1.SecretStore
  40. externalSecret *esv1beta1.ExternalSecret
  41. // checkCondition should return true if the externalSecret
  42. // has the expected condition
  43. checkCondition func(*esv1beta1.ExternalSecret) bool
  44. // checkExternalSecret is called after the condition has been verified
  45. // use this to verify the externalSecret
  46. checkExternalSecret func(*esv1beta1.ExternalSecret)
  47. // optional. use this to test the secret value
  48. checkSecret func(*esv1beta1.ExternalSecret, *v1.Secret)
  49. }
  50. type testTweaks func(*testCase)
  51. var _ = Describe("Kind=secret existence logic", func() {
  52. type testCase struct {
  53. Name string
  54. Input v1.Secret
  55. ExpectedOutput bool
  56. }
  57. tests := []testCase{
  58. {
  59. Name: "Should not be valid in case of missing uid",
  60. Input: v1.Secret{},
  61. ExpectedOutput: false,
  62. },
  63. {
  64. Name: "A nil annotation should not be valid",
  65. Input: v1.Secret{
  66. ObjectMeta: metav1.ObjectMeta{
  67. UID: "xxx",
  68. Annotations: map[string]string{},
  69. },
  70. },
  71. ExpectedOutput: false,
  72. },
  73. {
  74. Name: "A nil annotation should not be valid",
  75. Input: v1.Secret{
  76. ObjectMeta: metav1.ObjectMeta{
  77. UID: "xxx",
  78. Annotations: map[string]string{},
  79. },
  80. },
  81. ExpectedOutput: false,
  82. },
  83. {
  84. Name: "An invalid annotation hash should not be valid",
  85. Input: v1.Secret{
  86. ObjectMeta: metav1.ObjectMeta{
  87. UID: "xxx",
  88. Annotations: map[string]string{
  89. esv1beta1.AnnotationDataHash: "xxxxxx",
  90. },
  91. },
  92. },
  93. ExpectedOutput: false,
  94. },
  95. {
  96. Name: "A valid config map should return true",
  97. Input: v1.Secret{
  98. ObjectMeta: metav1.ObjectMeta{
  99. UID: "xxx",
  100. Annotations: map[string]string{
  101. esv1beta1.AnnotationDataHash: "caa0155759a6a9b3b6ada5a6883ee2bb",
  102. },
  103. },
  104. Data: map[string][]byte{
  105. "foo": []byte("value1"),
  106. "bar": []byte("value2"),
  107. },
  108. },
  109. ExpectedOutput: true,
  110. },
  111. }
  112. for _, tt := range tests {
  113. It(tt.Name, func() {
  114. Expect(isSecretValid(tt.Input)).To(BeEquivalentTo(tt.ExpectedOutput))
  115. })
  116. }
  117. })
  118. var _ = Describe("ExternalSecret controller", func() {
  119. const (
  120. ExternalSecretName = "test-es"
  121. ExternalSecretFQDN = "externalsecrets.external-secrets.io/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 = ctest.CreateNamespace("test-ns", k8sClient)
  140. Expect(err).ToNot(HaveOccurred())
  141. metric.Reset()
  142. syncCallsTotal.Reset()
  143. syncCallsError.Reset()
  144. externalSecretCondition.Reset()
  145. fakeProvider.Reset()
  146. })
  147. AfterEach(func() {
  148. Expect(k8sClient.Delete(context.Background(), &v1.Namespace{
  149. ObjectMeta: metav1.ObjectMeta{
  150. Name: ExternalSecretNamespace,
  151. },
  152. })).To(Succeed())
  153. Expect(k8sClient.Delete(context.Background(), &esv1beta1.SecretStore{
  154. ObjectMeta: metav1.ObjectMeta{
  155. Name: ExternalSecretStore,
  156. Namespace: ExternalSecretNamespace,
  157. },
  158. })).To(Succeed())
  159. })
  160. const targetProp = "targetProperty"
  161. const remoteKey = "barz"
  162. const remoteProperty = "bang"
  163. makeDefaultTestcase := func() *testCase {
  164. return &testCase{
  165. // default condition: es should be ready
  166. checkCondition: func(es *esv1beta1.ExternalSecret) bool {
  167. cond := GetExternalSecretCondition(es.Status, esv1beta1.ExternalSecretReady)
  168. if cond == nil || cond.Status != v1.ConditionTrue {
  169. return false
  170. }
  171. return true
  172. },
  173. checkExternalSecret: func(es *esv1beta1.ExternalSecret) {
  174. // noop by default
  175. },
  176. secretStore: &esv1beta1.SecretStore{
  177. ObjectMeta: metav1.ObjectMeta{
  178. Name: ExternalSecretStore,
  179. Namespace: ExternalSecretNamespace,
  180. },
  181. Spec: esv1beta1.SecretStoreSpec{
  182. Provider: &esv1beta1.SecretStoreProvider{
  183. AWS: &esv1beta1.AWSProvider{
  184. Service: esv1beta1.AWSServiceSecretsManager,
  185. },
  186. },
  187. },
  188. },
  189. externalSecret: &esv1beta1.ExternalSecret{
  190. ObjectMeta: metav1.ObjectMeta{
  191. Name: ExternalSecretName,
  192. Namespace: ExternalSecretNamespace,
  193. },
  194. Spec: esv1beta1.ExternalSecretSpec{
  195. SecretStoreRef: esv1beta1.SecretStoreRef{
  196. Name: ExternalSecretStore,
  197. },
  198. Target: esv1beta1.ExternalSecretTarget{
  199. Name: ExternalSecretTargetSecretName,
  200. },
  201. Data: []esv1beta1.ExternalSecretData{
  202. {
  203. SecretKey: targetProp,
  204. RemoteRef: esv1beta1.ExternalSecretDataRemoteRef{
  205. Key: remoteKey,
  206. Property: remoteProperty,
  207. },
  208. },
  209. },
  210. },
  211. },
  212. }
  213. }
  214. // if target Secret name is not specified it should use the ExternalSecret name.
  215. syncWithoutTargetName := func(tc *testCase) {
  216. tc.externalSecret.Spec.Target.Name = ""
  217. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  218. // check secret name
  219. Expect(secret.ObjectMeta.Name).To(Equal(ExternalSecretName))
  220. }
  221. }
  222. // labels and annotations from the Kind=ExternalSecret
  223. // should be copied over to the Kind=Secret
  224. syncLabelsAnnotations := func(tc *testCase) {
  225. const secretVal = "someValue"
  226. tc.externalSecret.ObjectMeta.Labels = map[string]string{
  227. "fooobar": "bazz",
  228. }
  229. tc.externalSecret.ObjectMeta.Annotations = map[string]string{
  230. "hihihih": "hehehe",
  231. }
  232. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  233. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  234. // check value
  235. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  236. // check labels & annotations
  237. Expect(secret.ObjectMeta.Labels).To(BeEquivalentTo(es.ObjectMeta.Labels))
  238. for k, v := range es.ObjectMeta.Annotations {
  239. Expect(secret.ObjectMeta.Annotations).To(HaveKeyWithValue(k, v))
  240. }
  241. // ownerRef must not not be set!
  242. Expect(ctest.HasOwnerRef(secret.ObjectMeta, "ExternalSecret", ExternalSecretName)).To(BeTrue())
  243. }
  244. }
  245. checkPrometheusCounters := func(tc *testCase) {
  246. const secretVal = "someValue"
  247. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  248. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  249. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1beta1.ExternalSecretReady, v1.ConditionFalse, 0.0)).To(BeTrue())
  250. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1beta1.ExternalSecretReady, v1.ConditionTrue, 1.0)).To(BeTrue())
  251. Eventually(func() bool {
  252. Expect(syncCallsTotal.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metric)).To(Succeed())
  253. return metric.GetCounter().GetValue() == 1.0
  254. }, timeout, interval).Should(BeTrue())
  255. }
  256. }
  257. // merge with existing secret using creationPolicy=Merge
  258. // it should NOT have a ownerReference
  259. // metadata.managedFields with the correct owner should be added to the secret
  260. mergeWithSecret := func(tc *testCase) {
  261. const secretVal = "someValue"
  262. const existingKey = "pre-existing-key"
  263. existingVal := "pre-existing-value"
  264. tc.externalSecret.Spec.Target.CreationPolicy = esv1beta1.CreatePolicyMerge
  265. // create secret beforehand
  266. Expect(k8sClient.Create(context.Background(), &v1.Secret{
  267. ObjectMeta: metav1.ObjectMeta{
  268. Name: ExternalSecretTargetSecretName,
  269. Namespace: ExternalSecretNamespace,
  270. },
  271. Data: map[string][]byte{
  272. existingKey: []byte(existingVal),
  273. },
  274. }, client.FieldOwner(FakeManager))).To(Succeed())
  275. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  276. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  277. // check value
  278. Expect(string(secret.Data[existingKey])).To(Equal(existingVal))
  279. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  280. // check labels & annotations
  281. Expect(secret.ObjectMeta.Labels).To(BeEquivalentTo(es.ObjectMeta.Labels))
  282. for k, v := range es.ObjectMeta.Annotations {
  283. Expect(secret.ObjectMeta.Annotations).To(HaveKeyWithValue(k, v))
  284. }
  285. Expect(ctest.HasOwnerRef(secret.ObjectMeta, "ExternalSecret", ExternalSecretFQDN)).To(BeFalse())
  286. Expect(secret.ObjectMeta.ManagedFields).To(HaveLen(2))
  287. Expect(ctest.HasFieldOwnership(
  288. secret.ObjectMeta,
  289. ExternalSecretFQDN,
  290. fmt.Sprintf("{\"f:data\":{\"f:targetProperty\":{}},\"f:immutable\":{},\"f:metadata\":{\"f:annotations\":{\"f:%s\":{}}}}", esv1beta1.AnnotationDataHash)),
  291. ).To(BeTrue())
  292. Expect(ctest.HasFieldOwnership(secret.ObjectMeta, FakeManager, "{\"f:data\":{\".\":{},\"f:pre-existing-key\":{}},\"f:type\":{}}")).To(BeTrue())
  293. }
  294. }
  295. // should not update if no changes
  296. mergeWithSecretNoChange := func(tc *testCase) {
  297. const existingKey = "pre-existing-key"
  298. existingVal := "someValue"
  299. tc.externalSecret.Spec.Target.CreationPolicy = esv1beta1.CreatePolicyMerge
  300. // create secret beforehand
  301. Expect(k8sClient.Create(context.Background(), &v1.Secret{
  302. ObjectMeta: metav1.ObjectMeta{
  303. Name: ExternalSecretTargetSecretName,
  304. Namespace: ExternalSecretNamespace,
  305. },
  306. Data: map[string][]byte{
  307. existingKey: []byte(existingVal),
  308. },
  309. }, client.FieldOwner(FakeManager))).To(Succeed())
  310. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  311. oldResourceVersion := secret.ResourceVersion
  312. cleanSecret := secret.DeepCopy()
  313. Expect(k8sClient.Patch(context.Background(), secret, client.MergeFrom(cleanSecret))).To(Succeed())
  314. newSecret := &v1.Secret{}
  315. Eventually(func() bool {
  316. secretLookupKey := types.NamespacedName{
  317. Name: ExternalSecretTargetSecretName,
  318. Namespace: ExternalSecretNamespace,
  319. }
  320. err := k8sClient.Get(context.Background(), secretLookupKey, newSecret)
  321. if err != nil {
  322. return false
  323. }
  324. return oldResourceVersion == newSecret.ResourceVersion
  325. }, timeout, interval).Should(Equal(true))
  326. }
  327. }
  328. // should not merge with secret if it doesn't exist
  329. mergeWithSecretErr := func(tc *testCase) {
  330. const secretVal = "someValue"
  331. tc.externalSecret.Spec.Target.CreationPolicy = esv1beta1.CreatePolicyMerge
  332. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  333. tc.checkCondition = func(es *esv1beta1.ExternalSecret) bool {
  334. cond := GetExternalSecretCondition(es.Status, esv1beta1.ExternalSecretReady)
  335. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1beta1.ConditionReasonSecretSyncedError {
  336. return false
  337. }
  338. return true
  339. }
  340. tc.checkExternalSecret = func(es *esv1beta1.ExternalSecret) {
  341. Eventually(func() bool {
  342. Expect(syncCallsError.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metric)).To(Succeed())
  343. return metric.GetCounter().GetValue() >= 2.0
  344. }, timeout, interval).Should(BeTrue())
  345. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1beta1.ExternalSecretReady, v1.ConditionFalse, 1.0)).To(BeTrue())
  346. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1beta1.ExternalSecretReady, v1.ConditionTrue, 0.0)).To(BeTrue())
  347. }
  348. }
  349. // controller should force ownership
  350. mergeWithConflict := func(tc *testCase) {
  351. const secretVal = "someValue"
  352. // this should confict
  353. const existingKey = targetProp
  354. existingVal := "pre-existing-value"
  355. tc.externalSecret.Spec.Target.CreationPolicy = esv1beta1.CreatePolicyMerge
  356. // create secret beforehand
  357. Expect(k8sClient.Create(context.Background(), &v1.Secret{
  358. ObjectMeta: metav1.ObjectMeta{
  359. Name: ExternalSecretTargetSecretName,
  360. Namespace: ExternalSecretNamespace,
  361. },
  362. Data: map[string][]byte{
  363. existingKey: []byte(existingVal),
  364. },
  365. }, client.FieldOwner(FakeManager))).To(Succeed())
  366. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  367. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  368. // check that value stays the same
  369. Expect(string(secret.Data[existingKey])).To(Equal(secretVal))
  370. // check owner/managedFields
  371. Expect(ctest.HasOwnerRef(secret.ObjectMeta, "ExternalSecret", ExternalSecretFQDN)).To(BeFalse())
  372. Expect(secret.ObjectMeta.ManagedFields).To(HaveLen(2))
  373. Expect(ctest.HasFieldOwnership(secret.ObjectMeta, ExternalSecretFQDN, "{\"f:data\":{\"f:targetProperty\":{}},\"f:immutable\":{},\"f:metadata\":{\"f:annotations\":{\"f:reconcile.external-secrets.io/data-hash\":{}}}}")).To(BeTrue())
  374. }
  375. }
  376. // when using a template it should be used as a blueprint
  377. // to construct a new secret: labels, annotations and type
  378. syncWithTemplate := func(tc *testCase) {
  379. const secretVal = "someValue"
  380. const tplStaticKey = "tplstatickey"
  381. const tplStaticVal = "tplstaticvalue"
  382. tc.externalSecret.ObjectMeta.Labels = map[string]string{
  383. "fooobar": "bazz",
  384. }
  385. tc.externalSecret.ObjectMeta.Annotations = map[string]string{
  386. "hihihih": "hehehe",
  387. }
  388. tc.externalSecret.Spec.Target.Template = &esv1beta1.ExternalSecretTemplate{
  389. Metadata: esv1beta1.ExternalSecretTemplateMetadata{
  390. Labels: map[string]string{
  391. "foos": "ball",
  392. },
  393. Annotations: map[string]string{
  394. "hihi": "ga",
  395. },
  396. },
  397. Type: v1.SecretTypeOpaque,
  398. EngineVersion: esv1beta1.TemplateEngineV1,
  399. Data: map[string]string{
  400. targetProp: targetPropObj,
  401. tplStaticKey: tplStaticVal,
  402. },
  403. }
  404. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  405. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  406. // check values
  407. Expect(string(secret.Data[targetProp])).To(Equal(expectedSecretVal))
  408. Expect(string(secret.Data[tplStaticKey])).To(Equal(tplStaticVal))
  409. // labels/annotations should be taken from the template
  410. Expect(secret.ObjectMeta.Labels).To(BeEquivalentTo(es.Spec.Target.Template.Metadata.Labels))
  411. for k, v := range es.Spec.Target.Template.Metadata.Annotations {
  412. Expect(secret.ObjectMeta.Annotations).To(HaveKeyWithValue(k, v))
  413. }
  414. }
  415. }
  416. // when using a v2 template it should use the v2 engine version
  417. syncWithTemplateV2 := func(tc *testCase) {
  418. const secretVal = "someValue"
  419. tc.externalSecret.Spec.Target.Template = &esv1beta1.ExternalSecretTemplate{
  420. Type: v1.SecretTypeOpaque,
  421. // it should default to v2 for beta11
  422. // EngineVersion: esv1beta1.TemplateEngineV2,
  423. Data: map[string]string{
  424. targetProp: "{{ .targetProperty | upper }} was templated",
  425. },
  426. }
  427. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  428. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  429. // check values
  430. Expect(string(secret.Data[targetProp])).To(Equal(expectedSecretVal))
  431. }
  432. }
  433. // secret should be synced with correct value precedence:
  434. // * template
  435. // * templateFrom
  436. // * data
  437. // * dataFrom
  438. syncWithTemplatePrecedence := func(tc *testCase) {
  439. const secretVal = "someValue"
  440. const tplStaticKey = "tplstatickey"
  441. const tplStaticVal = "tplstaticvalue"
  442. const tplFromCMName = "template-cm"
  443. const tplFromSecretName = "template-secret"
  444. const tplFromKey = "tpl-from-key"
  445. const tplFromSecKey = "tpl-from-sec-key"
  446. const tplFromVal = "tpl-from-value: {{ .targetProperty | toString }} // {{ .bar | toString }}"
  447. const tplFromSecVal = "tpl-from-sec-value: {{ .targetProperty | toString }} // {{ .bar | toString }}"
  448. Expect(k8sClient.Create(context.Background(), &v1.ConfigMap{
  449. ObjectMeta: metav1.ObjectMeta{
  450. Name: tplFromCMName,
  451. Namespace: ExternalSecretNamespace,
  452. },
  453. Data: map[string]string{
  454. tplFromKey: tplFromVal,
  455. },
  456. })).To(Succeed())
  457. Expect(k8sClient.Create(context.Background(), &v1.Secret{
  458. ObjectMeta: metav1.ObjectMeta{
  459. Name: tplFromSecretName,
  460. Namespace: ExternalSecretNamespace,
  461. },
  462. Data: map[string][]byte{
  463. tplFromSecKey: []byte(tplFromSecVal),
  464. },
  465. })).To(Succeed())
  466. tc.externalSecret.Spec.Target.Template = &esv1beta1.ExternalSecretTemplate{
  467. Metadata: esv1beta1.ExternalSecretTemplateMetadata{},
  468. Type: v1.SecretTypeOpaque,
  469. TemplateFrom: []esv1beta1.TemplateFrom{
  470. {
  471. ConfigMap: &esv1beta1.TemplateRef{
  472. Name: tplFromCMName,
  473. Items: []esv1beta1.TemplateRefItem{
  474. {
  475. Key: tplFromKey,
  476. },
  477. },
  478. },
  479. },
  480. {
  481. Secret: &esv1beta1.TemplateRef{
  482. Name: tplFromSecretName,
  483. Items: []esv1beta1.TemplateRefItem{
  484. {
  485. Key: tplFromSecKey,
  486. },
  487. },
  488. },
  489. },
  490. },
  491. Data: map[string]string{
  492. // this should be the data value, not dataFrom
  493. targetProp: targetPropObj,
  494. // this should use the value from the map
  495. "bar": "value from map: {{ .bar | toString }}",
  496. // just a static value
  497. tplStaticKey: tplStaticVal,
  498. },
  499. }
  500. tc.externalSecret.Spec.DataFrom = []esv1beta1.ExternalSecretDataFromRemoteRef{
  501. {
  502. Extract: &esv1beta1.ExternalSecretDataRemoteRef{
  503. Key: "datamap",
  504. },
  505. },
  506. }
  507. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  508. fakeProvider.WithGetSecretMap(map[string][]byte{
  509. "targetProperty": []byte(FooValue),
  510. "bar": []byte(BarValue),
  511. }, nil)
  512. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  513. // check values
  514. Expect(string(secret.Data[targetProp])).To(Equal(expectedSecretVal))
  515. Expect(string(secret.Data[tplStaticKey])).To(Equal(tplStaticVal))
  516. Expect(string(secret.Data["bar"])).To(Equal("value from map: map-bar-value"))
  517. Expect(string(secret.Data[tplFromKey])).To(Equal("tpl-from-value: someValue // map-bar-value"))
  518. Expect(string(secret.Data[tplFromSecKey])).To(Equal("tpl-from-sec-value: someValue // map-bar-value"))
  519. }
  520. }
  521. refreshWithTemplate := func(tc *testCase) {
  522. const secretVal = "someValue"
  523. const tplStaticKey = "tplstatickey"
  524. const tplStaticVal = "tplstaticvalue"
  525. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Second}
  526. tc.externalSecret.Spec.Target.Template = &esv1beta1.ExternalSecretTemplate{
  527. Metadata: esv1beta1.ExternalSecretTemplateMetadata{
  528. Labels: map[string]string{"foo": "bar"},
  529. Annotations: map[string]string{"foo": "bar"},
  530. },
  531. Type: v1.SecretTypeOpaque,
  532. Data: map[string]string{
  533. targetProp: targetPropObj,
  534. tplStaticKey: tplStaticVal,
  535. },
  536. }
  537. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  538. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  539. // check values
  540. Expect(string(secret.Data[targetProp])).To(Equal(expectedSecretVal))
  541. Expect(string(secret.Data[tplStaticKey])).To(Equal(tplStaticVal))
  542. // labels/annotations should be taken from the template
  543. Expect(secret.ObjectMeta.Labels).To(BeEquivalentTo(es.Spec.Target.Template.Metadata.Labels))
  544. // a secret will always have some extra annotations (i.e. hashmap check), so we only check for specific
  545. // source annotations
  546. for k, v := range es.Spec.Target.Template.Metadata.Annotations {
  547. Expect(secret.ObjectMeta.Annotations).To(HaveKeyWithValue(k, v))
  548. }
  549. cleanEs := tc.externalSecret.DeepCopy()
  550. // now update ExternalSecret
  551. tc.externalSecret.Spec.Target.Template.Metadata.Annotations["fuzz"] = "buzz"
  552. tc.externalSecret.Spec.Target.Template.Metadata.Labels["fuzz"] = "buzz"
  553. tc.externalSecret.Spec.Target.Template.Data["new"] = "value"
  554. Expect(k8sClient.Patch(context.Background(), tc.externalSecret, client.MergeFrom(cleanEs))).To(Succeed())
  555. // wait for secret
  556. sec := &v1.Secret{}
  557. secretLookupKey := types.NamespacedName{
  558. Name: ExternalSecretTargetSecretName,
  559. Namespace: ExternalSecretNamespace,
  560. }
  561. Eventually(func() bool {
  562. err := k8sClient.Get(context.Background(), secretLookupKey, sec)
  563. if err != nil {
  564. return false
  565. }
  566. // ensure new data value exist
  567. return string(sec.Data["new"]) == "value"
  568. }, time.Second*10, time.Millisecond*200).Should(BeTrue())
  569. // also check labels/annotations have been updated
  570. Expect(secret.ObjectMeta.Labels).To(BeEquivalentTo(es.Spec.Target.Template.Metadata.Labels))
  571. for k, v := range es.Spec.Target.Template.Metadata.Annotations {
  572. Expect(secret.ObjectMeta.Annotations).To(HaveKeyWithValue(k, v))
  573. }
  574. }
  575. }
  576. onlyMetadataFromTemplate := func(tc *testCase) {
  577. const secretVal = "someValue"
  578. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Second}
  579. tc.externalSecret.Spec.Target.Template = &esv1beta1.ExternalSecretTemplate{
  580. Metadata: esv1beta1.ExternalSecretTemplateMetadata{
  581. Labels: map[string]string{"foo": "bar"},
  582. Annotations: map[string]string{"foo": "bar"},
  583. },
  584. }
  585. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  586. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  587. // check values
  588. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  589. // labels/annotations should be taken from the template
  590. Expect(secret.ObjectMeta.Labels).To(BeEquivalentTo(es.Spec.Target.Template.Metadata.Labels))
  591. for k, v := range es.Spec.Target.Template.Metadata.Annotations {
  592. Expect(secret.ObjectMeta.Annotations).To(HaveKeyWithValue(k, v))
  593. }
  594. }
  595. }
  596. // when the provider secret changes the Kind=Secret value
  597. // must change, too.
  598. refreshSecretValue := func(tc *testCase) {
  599. const targetProp = "targetProperty"
  600. const secretVal = "someValue"
  601. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  602. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Second}
  603. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  604. // check values
  605. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  606. // update provider secret
  607. newValue := "NEW VALUE"
  608. sec := &v1.Secret{}
  609. fakeProvider.WithGetSecret([]byte(newValue), nil)
  610. secretLookupKey := types.NamespacedName{
  611. Name: ExternalSecretTargetSecretName,
  612. Namespace: ExternalSecretNamespace,
  613. }
  614. Eventually(func() bool {
  615. err := k8sClient.Get(context.Background(), secretLookupKey, sec)
  616. if err != nil {
  617. return false
  618. }
  619. v := sec.Data[targetProp]
  620. return string(v) == newValue
  621. }, timeout, interval).Should(BeTrue())
  622. }
  623. }
  624. // when a provider secret was deleted it must be deleted from
  625. // the secret aswell
  626. refreshSecretValueMap := func(tc *testCase) {
  627. fakeProvider.WithGetSecretMap(map[string][]byte{
  628. "foo": []byte("1111"),
  629. "bar": []byte("2222"),
  630. }, nil)
  631. tc.externalSecret.Spec.Data = []esv1beta1.ExternalSecretData{}
  632. tc.externalSecret.Spec.DataFrom = []esv1beta1.ExternalSecretDataFromRemoteRef{
  633. {
  634. Extract: &esv1beta1.ExternalSecretDataRemoteRef{
  635. Key: remoteKey,
  636. },
  637. },
  638. }
  639. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Second}
  640. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  641. // check values
  642. Expect(string(secret.Data["foo"])).To(Equal("1111"))
  643. Expect(string(secret.Data["bar"])).To(Equal("2222"))
  644. // update provider secret
  645. sec := &v1.Secret{}
  646. fakeProvider.WithGetSecretMap(map[string][]byte{
  647. "foo": []byte("1111"),
  648. }, nil)
  649. secretLookupKey := types.NamespacedName{
  650. Name: ExternalSecretTargetSecretName,
  651. Namespace: ExternalSecretNamespace,
  652. }
  653. Eventually(func() bool {
  654. err := k8sClient.Get(context.Background(), secretLookupKey, sec)
  655. if err != nil {
  656. return false
  657. }
  658. return string(sec.Data["foo"]) == "1111" &&
  659. sec.Data["bar"] == nil // must not be defined, it was deleted
  660. }, timeout, interval).Should(BeTrue())
  661. }
  662. }
  663. // when a provider secret was deleted it must be deleted from
  664. // the secret aswell when using a template
  665. refreshSecretValueMapTemplate := func(tc *testCase) {
  666. fakeProvider.WithGetSecretMap(map[string][]byte{
  667. "foo": []byte("1111"),
  668. "bar": []byte("2222"),
  669. }, nil)
  670. tc.externalSecret.Spec.Target.Template = &esv1beta1.ExternalSecretTemplate{}
  671. tc.externalSecret.Spec.Data = []esv1beta1.ExternalSecretData{}
  672. tc.externalSecret.Spec.DataFrom = []esv1beta1.ExternalSecretDataFromRemoteRef{
  673. {
  674. Extract: &esv1beta1.ExternalSecretDataRemoteRef{
  675. Key: remoteKey,
  676. },
  677. },
  678. }
  679. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Second}
  680. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  681. // check values
  682. Expect(string(secret.Data["foo"])).To(Equal("1111"))
  683. Expect(string(secret.Data["bar"])).To(Equal("2222"))
  684. // update provider secret
  685. sec := &v1.Secret{}
  686. fakeProvider.WithGetSecretMap(map[string][]byte{
  687. "foo": []byte("1111"),
  688. }, nil)
  689. secretLookupKey := types.NamespacedName{
  690. Name: ExternalSecretTargetSecretName,
  691. Namespace: ExternalSecretNamespace,
  692. }
  693. Eventually(func() bool {
  694. err := k8sClient.Get(context.Background(), secretLookupKey, sec)
  695. if err != nil {
  696. return false
  697. }
  698. return string(sec.Data["foo"]) == "1111" &&
  699. sec.Data["bar"] == nil // must not be defined, it was deleted
  700. }, timeout, interval).Should(BeTrue())
  701. }
  702. }
  703. refreshintervalZero := func(tc *testCase) {
  704. const targetProp = "targetProperty"
  705. const secretVal = "someValue"
  706. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  707. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: 0}
  708. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  709. // check values
  710. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  711. // update provider secret
  712. newValue := "NEW VALUE"
  713. sec := &v1.Secret{}
  714. fakeProvider.WithGetSecret([]byte(newValue), nil)
  715. secretLookupKey := types.NamespacedName{
  716. Name: ExternalSecretTargetSecretName,
  717. Namespace: ExternalSecretNamespace,
  718. }
  719. Consistently(func() bool {
  720. err := k8sClient.Get(context.Background(), secretLookupKey, sec)
  721. if err != nil {
  722. return false
  723. }
  724. v := sec.Data[targetProp]
  725. return string(v) == secretVal
  726. }, time.Second*10, time.Second).Should(BeTrue())
  727. }
  728. }
  729. deleteSecretPolicy := func(tc *testCase) {
  730. expVal := []byte("1234")
  731. // set initial value
  732. fakeProvider.WithGetAllSecrets(map[string][]byte{
  733. "foo": expVal,
  734. "bar": expVal,
  735. }, nil)
  736. tc.externalSecret.Spec.Data = nil
  737. tc.externalSecret.Spec.DataFrom = []esv1beta1.ExternalSecretDataFromRemoteRef{
  738. {
  739. Find: &esv1beta1.ExternalSecretFind{
  740. Tags: map[string]string{},
  741. },
  742. },
  743. }
  744. tc.externalSecret.Spec.Target.DeletionPolicy = esv1beta1.DeletionPolicyDelete
  745. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Second}
  746. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  747. Expect(secret.Data["foo"]).To(Equal(expVal))
  748. // update provider secret
  749. fakeProvider.WithGetAllSecrets(map[string][]byte{
  750. "foo": expVal,
  751. }, nil)
  752. sec := &v1.Secret{}
  753. secretLookupKey := types.NamespacedName{
  754. Name: ExternalSecretTargetSecretName,
  755. Namespace: ExternalSecretNamespace,
  756. }
  757. Eventually(func() bool {
  758. By("checking secret value for foo=1234 and bar=nil")
  759. err := k8sClient.Get(context.Background(), secretLookupKey, sec)
  760. if err != nil {
  761. return false
  762. }
  763. return bytes.Equal(sec.Data["foo"], expVal) && sec.Data["bar"] == nil
  764. }, time.Second*10, time.Second).Should(BeTrue())
  765. // return specific delete err to indicate deletion
  766. fakeProvider.WithGetAllSecrets(map[string][]byte{}, esv1beta1.NoSecretErr)
  767. Eventually(func() bool {
  768. By("checking that secret has been deleted")
  769. err := k8sClient.Get(context.Background(), secretLookupKey, sec)
  770. return apierrors.IsNotFound(err)
  771. }, time.Second*10, time.Second).Should(BeTrue())
  772. }
  773. }
  774. deleteSecretPolicyRetain := func(tc *testCase) {
  775. expVal := []byte("1234")
  776. // set initial value
  777. fakeProvider.WithGetAllSecrets(map[string][]byte{
  778. "foo": expVal,
  779. "bar": expVal,
  780. }, nil)
  781. tc.externalSecret.Spec.DataFrom = []esv1beta1.ExternalSecretDataFromRemoteRef{
  782. {
  783. Find: &esv1beta1.ExternalSecretFind{
  784. Tags: map[string]string{},
  785. },
  786. },
  787. }
  788. tc.externalSecret.Spec.Target.DeletionPolicy = esv1beta1.DeletionPolicyRetain
  789. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Second}
  790. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  791. Expect(secret.Data["foo"]).To(Equal(expVal))
  792. sec := &v1.Secret{}
  793. secretLookupKey := types.NamespacedName{
  794. Name: ExternalSecretTargetSecretName,
  795. Namespace: ExternalSecretNamespace,
  796. }
  797. // return specific delete err to indicate deletion
  798. // however this should not trigger a delete
  799. fakeProvider.WithGetAllSecrets(map[string][]byte{}, esv1beta1.NoSecretErr)
  800. Consistently(func() bool {
  801. By("checking that secret has not been deleted")
  802. err := k8sClient.Get(context.Background(), secretLookupKey, sec)
  803. return apierrors.IsNotFound(err) && bytes.Equal(sec.Data["foo"], expVal)
  804. }, time.Second*10, time.Second).Should(BeFalse())
  805. }
  806. }
  807. // merge with existing secret using creationPolicy=Merge
  808. // if provider secret gets deleted only the managed field should get deleted
  809. deleteSecretPolicyMerge := func(tc *testCase) {
  810. const secretVal = "someValue"
  811. const existingKey = "some-existing-key"
  812. existingVal := "some-existing-value"
  813. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Second}
  814. tc.externalSecret.Spec.Target.CreationPolicy = esv1beta1.CreatePolicyMerge
  815. tc.externalSecret.Spec.Target.DeletionPolicy = esv1beta1.DeletionPolicyMerge
  816. // create secret beforehand
  817. Expect(k8sClient.Create(context.Background(), &v1.Secret{
  818. ObjectMeta: metav1.ObjectMeta{
  819. Name: ExternalSecretTargetSecretName,
  820. Namespace: ExternalSecretNamespace,
  821. },
  822. Data: map[string][]byte{
  823. existingKey: []byte(existingVal),
  824. },
  825. }, client.FieldOwner(FakeManager))).To(Succeed())
  826. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  827. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  828. // check value
  829. Expect(string(secret.Data[existingKey])).To(Equal(existingVal))
  830. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  831. sec := &v1.Secret{}
  832. secretLookupKey := types.NamespacedName{
  833. Name: ExternalSecretTargetSecretName,
  834. Namespace: ExternalSecretNamespace,
  835. }
  836. // return specific delete err to indicate deletion
  837. // however this should not trigger a delete
  838. // instead expect that only the pre-existing value exists
  839. fakeProvider.WithGetSecret(nil, esv1beta1.NoSecretErr)
  840. Eventually(func() bool {
  841. By("checking that secret has not been deleted and pre-existing key exists")
  842. err := k8sClient.Get(context.Background(), secretLookupKey, sec)
  843. return !apierrors.IsNotFound(err) &&
  844. len(sec.Data) == 1 &&
  845. bytes.Equal(sec.Data[existingKey], []byte(existingVal))
  846. }, time.Second*30, time.Second).Should(BeTrue())
  847. }
  848. }
  849. // orphan the secret after the external secret has been deleted
  850. createSecretPolicyOrphan := func(tc *testCase) {
  851. const secretVal = "someValue"
  852. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Second}
  853. tc.externalSecret.Spec.Target.CreationPolicy = esv1beta1.CreatePolicyOrphan
  854. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  855. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  856. // check value
  857. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  858. sec := &v1.Secret{}
  859. secretLookupKey := types.NamespacedName{
  860. Name: ExternalSecretTargetSecretName,
  861. Namespace: ExternalSecretNamespace,
  862. }
  863. err := k8sClient.Delete(context.Background(), tc.externalSecret)
  864. Expect(err).ToNot(HaveOccurred())
  865. Consistently(func() bool {
  866. By("checking that secret has not been deleted")
  867. err := k8sClient.Get(context.Background(), secretLookupKey, sec)
  868. return !apierrors.IsNotFound(err)
  869. }, time.Second*15, time.Second).Should(BeTrue())
  870. }
  871. }
  872. // with rewrite all keys from a dataFrom operation
  873. // should be put with new rewriting into the secret
  874. syncAndRewriteWithDataFrom := func(tc *testCase) {
  875. tc.externalSecret.Spec.Data = nil
  876. tc.externalSecret.Spec.DataFrom = []esv1beta1.ExternalSecretDataFromRemoteRef{
  877. {
  878. Extract: &esv1beta1.ExternalSecretDataRemoteRef{
  879. Key: remoteKey,
  880. },
  881. Rewrite: []esv1beta1.ExternalSecretRewrite{{
  882. Regexp: &esv1beta1.ExternalSecretRewriteRegexp{
  883. Source: "(.*)",
  884. Target: "new-$1",
  885. },
  886. }},
  887. },
  888. {
  889. Extract: &esv1beta1.ExternalSecretDataRemoteRef{
  890. Key: remoteKey,
  891. },
  892. Rewrite: []esv1beta1.ExternalSecretRewrite{{
  893. Regexp: &esv1beta1.ExternalSecretRewriteRegexp{
  894. Source: "(.*)",
  895. Target: "old-$1",
  896. },
  897. }},
  898. },
  899. }
  900. fakeProvider.WithGetSecretMap(map[string][]byte{
  901. "foo": []byte(FooValue),
  902. "bar": []byte(BarValue),
  903. }, nil)
  904. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  905. // check values
  906. Expect(string(secret.Data["new-foo"])).To(Equal(FooValue))
  907. Expect(string(secret.Data["new-bar"])).To(Equal(BarValue))
  908. Expect(string(secret.Data["old-foo"])).To(Equal(FooValue))
  909. Expect(string(secret.Data["old-bar"])).To(Equal(BarValue))
  910. }
  911. }
  912. // with rewrite keys from dataFrom
  913. // should error if keys are not compliant
  914. invalidExtractKeysErrCondition := func(tc *testCase) {
  915. tc.externalSecret.Spec.Data = nil
  916. tc.externalSecret.Spec.DataFrom = []esv1beta1.ExternalSecretDataFromRemoteRef{
  917. {
  918. Extract: &esv1beta1.ExternalSecretDataRemoteRef{
  919. Key: remoteKey,
  920. },
  921. Rewrite: []esv1beta1.ExternalSecretRewrite{{
  922. Regexp: &esv1beta1.ExternalSecretRewriteRegexp{
  923. Source: "(.*)",
  924. Target: "$1",
  925. },
  926. }},
  927. },
  928. }
  929. fakeProvider.WithGetSecretMap(map[string][]byte{
  930. "foo/bar": []byte(FooValue),
  931. "bar/foo": []byte(BarValue),
  932. }, nil)
  933. tc.checkCondition = func(es *esv1beta1.ExternalSecret) bool {
  934. cond := GetExternalSecretCondition(es.Status, esv1beta1.ExternalSecretReady)
  935. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1beta1.ConditionReasonSecretSyncedError {
  936. return false
  937. }
  938. return true
  939. }
  940. tc.checkCondition = func(es *esv1beta1.ExternalSecret) bool {
  941. cond := GetExternalSecretCondition(es.Status, esv1beta1.ExternalSecretReady)
  942. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1beta1.ConditionReasonSecretSyncedError {
  943. return false
  944. }
  945. return true
  946. }
  947. tc.checkExternalSecret = func(es *esv1beta1.ExternalSecret) {
  948. Eventually(func() bool {
  949. Expect(syncCallsError.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metric)).To(Succeed())
  950. return metric.GetCounter().GetValue() >= 2.0
  951. }, timeout, interval).Should(BeTrue())
  952. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1beta1.ExternalSecretReady, v1.ConditionFalse, 1.0)).To(BeTrue())
  953. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1beta1.ExternalSecretReady, v1.ConditionTrue, 0.0)).To(BeTrue())
  954. }
  955. }
  956. // with rewrite keys from dataFrom
  957. // should error if keys are not compliant
  958. invalidFindKeysErrCondition := func(tc *testCase) {
  959. tc.externalSecret.Spec.Data = nil
  960. tc.externalSecret.Spec.DataFrom = []esv1beta1.ExternalSecretDataFromRemoteRef{
  961. {
  962. Find: &esv1beta1.ExternalSecretFind{
  963. Name: &esv1beta1.FindName{
  964. RegExp: ".*",
  965. },
  966. },
  967. Rewrite: []esv1beta1.ExternalSecretRewrite{{
  968. Regexp: &esv1beta1.ExternalSecretRewriteRegexp{
  969. Source: "(.*)",
  970. Target: "$1",
  971. },
  972. }},
  973. },
  974. }
  975. fakeProvider.WithGetAllSecrets(map[string][]byte{
  976. "foo/bar": []byte(FooValue),
  977. "bar/foo": []byte(BarValue),
  978. }, nil)
  979. tc.checkCondition = func(es *esv1beta1.ExternalSecret) bool {
  980. cond := GetExternalSecretCondition(es.Status, esv1beta1.ExternalSecretReady)
  981. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1beta1.ConditionReasonSecretSyncedError {
  982. return false
  983. }
  984. return true
  985. }
  986. tc.checkCondition = func(es *esv1beta1.ExternalSecret) bool {
  987. cond := GetExternalSecretCondition(es.Status, esv1beta1.ExternalSecretReady)
  988. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1beta1.ConditionReasonSecretSyncedError {
  989. return false
  990. }
  991. return true
  992. }
  993. tc.checkExternalSecret = func(es *esv1beta1.ExternalSecret) {
  994. Eventually(func() bool {
  995. Expect(syncCallsError.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metric)).To(Succeed())
  996. return metric.GetCounter().GetValue() >= 2.0
  997. }, timeout, interval).Should(BeTrue())
  998. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1beta1.ExternalSecretReady, v1.ConditionFalse, 1.0)).To(BeTrue())
  999. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1beta1.ExternalSecretReady, v1.ConditionTrue, 0.0)).To(BeTrue())
  1000. }
  1001. }
  1002. // with dataFrom all properties from the specified secret
  1003. // should be put into the secret
  1004. syncWithDataFrom := func(tc *testCase) {
  1005. tc.externalSecret.Spec.Data = nil
  1006. tc.externalSecret.Spec.DataFrom = []esv1beta1.ExternalSecretDataFromRemoteRef{
  1007. {
  1008. Extract: &esv1beta1.ExternalSecretDataRemoteRef{
  1009. Key: remoteKey,
  1010. },
  1011. },
  1012. }
  1013. fakeProvider.WithGetSecretMap(map[string][]byte{
  1014. "foo": []byte(FooValue),
  1015. "bar": []byte(BarValue),
  1016. }, nil)
  1017. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  1018. // check values
  1019. Expect(string(secret.Data["foo"])).To(Equal(FooValue))
  1020. Expect(string(secret.Data["bar"])).To(Equal(BarValue))
  1021. }
  1022. }
  1023. // with dataFrom.Find the change is on the called method GetAllSecrets
  1024. // all keys should be put into the secret
  1025. syncAndRewriteDataFromFind := func(tc *testCase) {
  1026. tc.externalSecret.Spec.Data = nil
  1027. tc.externalSecret.Spec.DataFrom = []esv1beta1.ExternalSecretDataFromRemoteRef{
  1028. {
  1029. Find: &esv1beta1.ExternalSecretFind{
  1030. Name: &esv1beta1.FindName{
  1031. RegExp: "foobar",
  1032. },
  1033. },
  1034. Rewrite: []esv1beta1.ExternalSecretRewrite{
  1035. {
  1036. Regexp: &esv1beta1.ExternalSecretRewriteRegexp{
  1037. Source: "(.*)",
  1038. Target: "new-$1",
  1039. },
  1040. },
  1041. },
  1042. },
  1043. }
  1044. fakeProvider.WithGetAllSecrets(map[string][]byte{
  1045. "foo": []byte(FooValue),
  1046. "bar": []byte(BarValue),
  1047. }, nil)
  1048. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  1049. // check values
  1050. Expect(string(secret.Data["new-foo"])).To(Equal(FooValue))
  1051. Expect(string(secret.Data["new-bar"])).To(Equal(BarValue))
  1052. }
  1053. }
  1054. // with dataFrom.Find the change is on the called method GetAllSecrets
  1055. // all keys should be put into the secret
  1056. syncDataFromFind := func(tc *testCase) {
  1057. tc.externalSecret.Spec.Data = nil
  1058. tc.externalSecret.Spec.DataFrom = []esv1beta1.ExternalSecretDataFromRemoteRef{
  1059. {
  1060. Find: &esv1beta1.ExternalSecretFind{
  1061. Name: &esv1beta1.FindName{
  1062. RegExp: "foobar",
  1063. },
  1064. },
  1065. },
  1066. }
  1067. fakeProvider.WithGetAllSecrets(map[string][]byte{
  1068. "foo": []byte(FooValue),
  1069. "bar": []byte(BarValue),
  1070. }, nil)
  1071. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  1072. // check values
  1073. Expect(string(secret.Data["foo"])).To(Equal(FooValue))
  1074. Expect(string(secret.Data["bar"])).To(Equal(BarValue))
  1075. }
  1076. }
  1077. // with dataFrom and using a template
  1078. // should be put into the secret
  1079. syncWithDataFromTemplate := func(tc *testCase) {
  1080. tc.externalSecret.Spec.Data = nil
  1081. tc.externalSecret.Spec.Target = esv1beta1.ExternalSecretTarget{
  1082. Name: ExternalSecretTargetSecretName,
  1083. Template: &esv1beta1.ExternalSecretTemplate{
  1084. Type: v1.SecretTypeTLS,
  1085. },
  1086. }
  1087. tc.externalSecret.Spec.DataFrom = []esv1beta1.ExternalSecretDataFromRemoteRef{
  1088. {
  1089. Extract: &esv1beta1.ExternalSecretDataRemoteRef{
  1090. Key: remoteKey,
  1091. },
  1092. },
  1093. }
  1094. fakeProvider.WithGetSecretMap(map[string][]byte{
  1095. "tls.crt": []byte(FooValue),
  1096. "tls.key": []byte(BarValue),
  1097. }, nil)
  1098. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  1099. Expect(secret.Type).To(Equal(v1.SecretTypeTLS))
  1100. // check values
  1101. Expect(string(secret.Data["tls.crt"])).To(Equal(FooValue))
  1102. Expect(string(secret.Data["tls.key"])).To(Equal(BarValue))
  1103. }
  1104. }
  1105. // when a provider errors in a GetSecret call
  1106. // a error condition must be set.
  1107. providerErrCondition := func(tc *testCase) {
  1108. const secretVal = "foobar"
  1109. fakeProvider.WithGetSecret(nil, fmt.Errorf("boom"))
  1110. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Millisecond * 100}
  1111. tc.checkCondition = func(es *esv1beta1.ExternalSecret) bool {
  1112. cond := GetExternalSecretCondition(es.Status, esv1beta1.ExternalSecretReady)
  1113. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1beta1.ConditionReasonSecretSyncedError {
  1114. return false
  1115. }
  1116. return true
  1117. }
  1118. tc.checkExternalSecret = func(es *esv1beta1.ExternalSecret) {
  1119. Eventually(func() bool {
  1120. Expect(syncCallsError.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metric)).To(Succeed())
  1121. return metric.GetCounter().GetValue() >= 2.0
  1122. }, timeout, interval).Should(BeTrue())
  1123. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1beta1.ExternalSecretReady, v1.ConditionFalse, 1.0)).To(BeTrue())
  1124. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1beta1.ExternalSecretReady, v1.ConditionTrue, 0.0)).To(BeTrue())
  1125. // es condition should reflect recovered provider error
  1126. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  1127. esKey := types.NamespacedName{Name: ExternalSecretName, Namespace: ExternalSecretNamespace}
  1128. Eventually(func() bool {
  1129. err := k8sClient.Get(context.Background(), esKey, es)
  1130. if err != nil {
  1131. return false
  1132. }
  1133. // condition must now be true!
  1134. cond := GetExternalSecretCondition(es.Status, esv1beta1.ExternalSecretReady)
  1135. if cond == nil && cond.Status != v1.ConditionTrue {
  1136. return false
  1137. }
  1138. return true
  1139. }, timeout, interval).Should(BeTrue())
  1140. }
  1141. }
  1142. // When a ExternalSecret references an non-existing SecretStore
  1143. // a error condition must be set.
  1144. storeMissingErrCondition := func(tc *testCase) {
  1145. tc.externalSecret.Spec.SecretStoreRef.Name = "nonexistent"
  1146. tc.checkCondition = func(es *esv1beta1.ExternalSecret) bool {
  1147. cond := GetExternalSecretCondition(es.Status, esv1beta1.ExternalSecretReady)
  1148. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1beta1.ConditionReasonSecretSyncedError {
  1149. return false
  1150. }
  1151. return true
  1152. }
  1153. tc.checkExternalSecret = func(es *esv1beta1.ExternalSecret) {
  1154. Eventually(func() bool {
  1155. Expect(syncCallsError.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metric)).To(Succeed())
  1156. return metric.GetCounter().GetValue() >= 2.0
  1157. }, timeout, interval).Should(BeTrue())
  1158. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1beta1.ExternalSecretReady, v1.ConditionFalse, 1.0)).To(BeTrue())
  1159. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1beta1.ExternalSecretReady, v1.ConditionTrue, 0.0)).To(BeTrue())
  1160. }
  1161. }
  1162. // when the provider constructor errors (e.g. invalid configuration)
  1163. // a SecretSyncedError status condition must be set
  1164. storeConstructErrCondition := func(tc *testCase) {
  1165. fakeProvider.WithNew(func(context.Context, esv1beta1.GenericStore, client.Client,
  1166. string) (esv1beta1.SecretsClient, error) {
  1167. return nil, fmt.Errorf("artificial constructor error")
  1168. })
  1169. tc.checkCondition = func(es *esv1beta1.ExternalSecret) bool {
  1170. // condition must be false
  1171. cond := GetExternalSecretCondition(es.Status, esv1beta1.ExternalSecretReady)
  1172. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1beta1.ConditionReasonSecretSyncedError {
  1173. return false
  1174. }
  1175. return true
  1176. }
  1177. tc.checkExternalSecret = func(es *esv1beta1.ExternalSecret) {
  1178. Eventually(func() bool {
  1179. Expect(syncCallsError.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metric)).To(Succeed())
  1180. return metric.GetCounter().GetValue() >= 2.0
  1181. }, timeout, interval).Should(BeTrue())
  1182. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1beta1.ExternalSecretReady, v1.ConditionFalse, 1.0)).To(BeTrue())
  1183. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1beta1.ExternalSecretReady, v1.ConditionTrue, 0.0)).To(BeTrue())
  1184. }
  1185. }
  1186. // when a SecretStore has a controller field set which we don't care about
  1187. // the externalSecret must not be touched
  1188. ignoreMismatchController := func(tc *testCase) {
  1189. tc.secretStore.Spec.Controller = "nop"
  1190. tc.checkCondition = func(es *esv1beta1.ExternalSecret) bool {
  1191. cond := GetExternalSecretCondition(es.Status, esv1beta1.ExternalSecretReady)
  1192. return cond == nil
  1193. }
  1194. tc.checkExternalSecret = func(es *esv1beta1.ExternalSecret) {
  1195. // Condition True and False should be 0, since the Condition was not created
  1196. Eventually(func() float64 {
  1197. Expect(externalSecretCondition.WithLabelValues(ExternalSecretName, ExternalSecretNamespace, string(esv1beta1.ExternalSecretReady), string(v1.ConditionTrue)).Write(&metric)).To(Succeed())
  1198. return metric.GetGauge().GetValue()
  1199. }, timeout, interval).Should(Equal(0.0))
  1200. Eventually(func() float64 {
  1201. Expect(externalSecretCondition.WithLabelValues(ExternalSecretName, ExternalSecretNamespace, string(esv1beta1.ExternalSecretReady), string(v1.ConditionFalse)).Write(&metric)).To(Succeed())
  1202. return metric.GetGauge().GetValue()
  1203. }, timeout, interval).Should(Equal(0.0))
  1204. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1beta1.ExternalSecretReady, v1.ConditionFalse, 0.0)).To(BeTrue())
  1205. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1beta1.ExternalSecretReady, v1.ConditionTrue, 0.0)).To(BeTrue())
  1206. }
  1207. }
  1208. ignoreClusterSecretStoreWhenDisabled := func(tc *testCase) {
  1209. tc.externalSecret.Spec.SecretStoreRef.Kind = esv1beta1.ClusterSecretStoreKind
  1210. Expect(shouldSkipClusterSecretStore(
  1211. &Reconciler{
  1212. ClusterSecretStoreEnabled: false,
  1213. },
  1214. *tc.externalSecret,
  1215. )).To(BeTrue())
  1216. tc.checkCondition = func(es *esv1beta1.ExternalSecret) bool {
  1217. cond := GetExternalSecretCondition(es.Status, esv1beta1.ExternalSecretReady)
  1218. return cond == nil
  1219. }
  1220. }
  1221. // When the ownership is set to owner, and we delete a dependent child kind=secret
  1222. // it should be recreated without waiting for refresh interval
  1223. checkDeletion := func(tc *testCase) {
  1224. const secretVal = "someValue"
  1225. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  1226. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Minute * 10}
  1227. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  1228. // check values
  1229. oldUID := secret.UID
  1230. Expect(oldUID).NotTo(BeEmpty())
  1231. // delete the related config
  1232. Expect(k8sClient.Delete(context.TODO(), secret))
  1233. var newSecret v1.Secret
  1234. secretLookupKey := types.NamespacedName{
  1235. Name: ExternalSecretTargetSecretName,
  1236. Namespace: ExternalSecretNamespace,
  1237. }
  1238. Eventually(func() bool {
  1239. err := k8sClient.Get(context.Background(), secretLookupKey, &newSecret)
  1240. if err != nil {
  1241. return false
  1242. }
  1243. // new secret should be a new, recreated object with a different UID
  1244. return newSecret.UID != oldUID
  1245. }, timeout, interval).Should(BeTrue())
  1246. }
  1247. }
  1248. // Checks that secret annotation has been written based on the data
  1249. checkSecretDataHashAnnotation := func(tc *testCase) {
  1250. const secretVal = "someValue"
  1251. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  1252. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  1253. Expect(secret.Annotations[esv1beta1.AnnotationDataHash]).To(Equal("9d30b95ca81e156f9454b5ef3bfcc6ee"))
  1254. }
  1255. }
  1256. // When we amend the created kind=secret, refresh operation should be run again regardless of refresh interval
  1257. checkSecretDataHashAnnotationChange := func(tc *testCase) {
  1258. fakeData := map[string][]byte{
  1259. "targetProperty": []byte(FooValue),
  1260. }
  1261. fakeProvider.WithGetSecretMap(fakeData, nil)
  1262. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Minute * 10}
  1263. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  1264. oldHash := secret.Annotations[esv1beta1.AnnotationDataHash]
  1265. oldResourceVersion := secret.ResourceVersion
  1266. Expect(oldHash).NotTo(BeEmpty())
  1267. cleanSecret := secret.DeepCopy()
  1268. secret.Data["new"] = []byte("value")
  1269. secret.ObjectMeta.Annotations[esv1beta1.AnnotationDataHash] = "thisiswronghash"
  1270. Expect(k8sClient.Patch(context.Background(), secret, client.MergeFrom(cleanSecret))).To(Succeed())
  1271. var refreshedSecret v1.Secret
  1272. secretLookupKey := types.NamespacedName{
  1273. Name: ExternalSecretTargetSecretName,
  1274. Namespace: ExternalSecretNamespace,
  1275. }
  1276. Eventually(func() bool {
  1277. err := k8sClient.Get(context.Background(), secretLookupKey, &refreshedSecret)
  1278. if err != nil {
  1279. return false
  1280. }
  1281. // refreshed secret should have a different generation (sign that it was updated), but since
  1282. // the secret source is the same (not changed), the hash should be reverted to an old value
  1283. return refreshedSecret.ResourceVersion != oldResourceVersion && refreshedSecret.Annotations[esv1beta1.AnnotationDataHash] == oldHash
  1284. }, timeout, interval).Should(BeTrue())
  1285. }
  1286. }
  1287. DescribeTable("When reconciling an ExternalSecret",
  1288. func(tweaks ...testTweaks) {
  1289. tc := makeDefaultTestcase()
  1290. for _, tweak := range tweaks {
  1291. tweak(tc)
  1292. }
  1293. ctx := context.Background()
  1294. By("creating a secret store and external secret")
  1295. Expect(k8sClient.Create(ctx, tc.secretStore)).To(Succeed())
  1296. Expect(k8sClient.Create(ctx, tc.externalSecret)).Should(Succeed())
  1297. esKey := types.NamespacedName{Name: ExternalSecretName, Namespace: ExternalSecretNamespace}
  1298. createdES := &esv1beta1.ExternalSecret{}
  1299. By("checking the es condition")
  1300. Eventually(func() bool {
  1301. err := k8sClient.Get(ctx, esKey, createdES)
  1302. if err != nil {
  1303. return false
  1304. }
  1305. return tc.checkCondition(createdES)
  1306. }, timeout, interval).Should(BeTrue())
  1307. tc.checkExternalSecret(createdES)
  1308. // this must be optional so we can test faulty es configuration
  1309. if tc.checkSecret != nil {
  1310. syncedSecret := &v1.Secret{}
  1311. secretLookupKey := types.NamespacedName{
  1312. Name: ExternalSecretTargetSecretName,
  1313. Namespace: ExternalSecretNamespace,
  1314. }
  1315. if createdES.Spec.Target.Name == "" {
  1316. secretLookupKey = types.NamespacedName{
  1317. Name: ExternalSecretName,
  1318. Namespace: ExternalSecretNamespace,
  1319. }
  1320. }
  1321. Eventually(func() bool {
  1322. err := k8sClient.Get(ctx, secretLookupKey, syncedSecret)
  1323. return err == nil
  1324. }, timeout, interval).Should(BeTrue())
  1325. tc.checkSecret(createdES, syncedSecret)
  1326. }
  1327. },
  1328. Entry("should recreate deleted secret", checkDeletion),
  1329. Entry("should create proper hash annotation for the external secret", checkSecretDataHashAnnotation),
  1330. Entry("should refresh when the hash annotation doesn't correspond to secret data", checkSecretDataHashAnnotationChange),
  1331. Entry("should use external secret name if target secret name isn't defined", syncWithoutTargetName),
  1332. Entry("should set the condition eventually", syncLabelsAnnotations),
  1333. Entry("should set prometheus counters", checkPrometheusCounters),
  1334. Entry("should merge with existing secret using creationPolicy=Merge", mergeWithSecret),
  1335. Entry("should error if secret doesn't exist when using creationPolicy=Merge", mergeWithSecretErr),
  1336. Entry("should not resolve conflicts with creationPolicy=Merge", mergeWithConflict),
  1337. Entry("should not update unchanged secret using creationPolicy=Merge", mergeWithSecretNoChange),
  1338. Entry("should not delete pre-existing secret with creationPolicy=Orphan", createSecretPolicyOrphan),
  1339. Entry("should sync with template", syncWithTemplate),
  1340. Entry("should sync with template engine v2", syncWithTemplateV2),
  1341. Entry("should sync template with correct value precedence", syncWithTemplatePrecedence),
  1342. Entry("should refresh secret from template", refreshWithTemplate),
  1343. Entry("should be able to use only metadata from template", onlyMetadataFromTemplate),
  1344. Entry("should refresh secret value when provider secret changes", refreshSecretValue),
  1345. Entry("should refresh secret map when provider secret changes", refreshSecretValueMap),
  1346. Entry("should refresh secret map when provider secret changes when using a template", refreshSecretValueMapTemplate),
  1347. Entry("should not refresh secret value when provider secret changes but refreshInterval is zero", refreshintervalZero),
  1348. Entry("should fetch secret using dataFrom", syncWithDataFrom),
  1349. Entry("should rewrite secret using dataFrom", syncAndRewriteWithDataFrom),
  1350. Entry("should not automatically convert from extract if rewrite is used", invalidExtractKeysErrCondition),
  1351. Entry("should fetch secret using dataFrom.find", syncDataFromFind),
  1352. Entry("should rewrite secret using dataFrom.find", syncAndRewriteDataFromFind),
  1353. Entry("should not automatically convert from find if rewrite is used", invalidFindKeysErrCondition),
  1354. Entry("should fetch secret using dataFrom and a template", syncWithDataFromTemplate),
  1355. Entry("should set error condition when provider errors", providerErrCondition),
  1356. Entry("should set an error condition when store does not exist", storeMissingErrCondition),
  1357. Entry("should set an error condition when store provider constructor fails", storeConstructErrCondition),
  1358. Entry("should not process store with mismatching controller field", ignoreMismatchController),
  1359. Entry("should not process cluster secret store when it is disabled", ignoreClusterSecretStoreWhenDisabled),
  1360. Entry("should eventually delete target secret with deletionPolicy=Delete", deleteSecretPolicy),
  1361. Entry("should not delete target secret with deletionPolicy=Retain", deleteSecretPolicyRetain),
  1362. Entry("should not delete pre-existing secret with deletionPolicy=Merge", deleteSecretPolicyMerge),
  1363. )
  1364. })
  1365. var _ = Describe("ExternalSecret refresh logic", func() {
  1366. Context("secret refresh", func() {
  1367. It("should refresh when resource version does not match", func() {
  1368. Expect(shouldRefresh(esv1beta1.ExternalSecret{
  1369. Status: esv1beta1.ExternalSecretStatus{
  1370. SyncedResourceVersion: "some resource version",
  1371. },
  1372. })).To(BeTrue())
  1373. })
  1374. It("should refresh when labels change", func() {
  1375. es := esv1beta1.ExternalSecret{
  1376. ObjectMeta: metav1.ObjectMeta{
  1377. Generation: 1,
  1378. Labels: map[string]string{
  1379. "foo": "bar",
  1380. },
  1381. },
  1382. Spec: esv1beta1.ExternalSecretSpec{
  1383. RefreshInterval: &metav1.Duration{Duration: time.Minute},
  1384. },
  1385. Status: esv1beta1.ExternalSecretStatus{
  1386. RefreshTime: metav1.Now(),
  1387. },
  1388. }
  1389. es.Status.SyncedResourceVersion = getResourceVersion(es)
  1390. // this should not refresh, rv matches object
  1391. Expect(shouldRefresh(es)).To(BeFalse())
  1392. // change labels without changing the syncedResourceVersion and expect refresh
  1393. es.ObjectMeta.Labels["new"] = "w00t"
  1394. Expect(shouldRefresh(es)).To(BeTrue())
  1395. })
  1396. It("should refresh when annotations change", func() {
  1397. es := esv1beta1.ExternalSecret{
  1398. ObjectMeta: metav1.ObjectMeta{
  1399. Generation: 1,
  1400. Annotations: map[string]string{
  1401. "foo": "bar",
  1402. },
  1403. },
  1404. Spec: esv1beta1.ExternalSecretSpec{
  1405. RefreshInterval: &metav1.Duration{Duration: time.Minute},
  1406. },
  1407. Status: esv1beta1.ExternalSecretStatus{
  1408. RefreshTime: metav1.Now(),
  1409. },
  1410. }
  1411. es.Status.SyncedResourceVersion = getResourceVersion(es)
  1412. // this should not refresh, rv matches object
  1413. Expect(shouldRefresh(es)).To(BeFalse())
  1414. // change annotations without changing the syncedResourceVersion and expect refresh
  1415. es.ObjectMeta.Annotations["new"] = "w00t"
  1416. Expect(shouldRefresh(es)).To(BeTrue())
  1417. })
  1418. It("should refresh when generation has changed", func() {
  1419. es := esv1beta1.ExternalSecret{
  1420. ObjectMeta: metav1.ObjectMeta{
  1421. Generation: 1,
  1422. },
  1423. Spec: esv1beta1.ExternalSecretSpec{
  1424. RefreshInterval: &metav1.Duration{Duration: 0},
  1425. },
  1426. Status: esv1beta1.ExternalSecretStatus{
  1427. RefreshTime: metav1.Now(),
  1428. },
  1429. }
  1430. es.Status.SyncedResourceVersion = getResourceVersion(es)
  1431. Expect(shouldRefresh(es)).To(BeFalse())
  1432. // update gen -> refresh
  1433. es.ObjectMeta.Generation = 2
  1434. Expect(shouldRefresh(es)).To(BeTrue())
  1435. })
  1436. It("should skip refresh when refreshInterval is 0", func() {
  1437. es := esv1beta1.ExternalSecret{
  1438. ObjectMeta: metav1.ObjectMeta{
  1439. Generation: 1,
  1440. },
  1441. Spec: esv1beta1.ExternalSecretSpec{
  1442. RefreshInterval: &metav1.Duration{Duration: 0},
  1443. },
  1444. Status: esv1beta1.ExternalSecretStatus{},
  1445. }
  1446. // resource version matches
  1447. es.Status.SyncedResourceVersion = getResourceVersion(es)
  1448. Expect(shouldRefresh(es)).To(BeFalse())
  1449. })
  1450. It("should refresh when refresh interval has passed", func() {
  1451. es := esv1beta1.ExternalSecret{
  1452. ObjectMeta: metav1.ObjectMeta{
  1453. Generation: 1,
  1454. },
  1455. Spec: esv1beta1.ExternalSecretSpec{
  1456. RefreshInterval: &metav1.Duration{Duration: time.Second},
  1457. },
  1458. Status: esv1beta1.ExternalSecretStatus{
  1459. RefreshTime: metav1.NewTime(metav1.Now().Add(-time.Second * 5)),
  1460. },
  1461. }
  1462. // resource version matches
  1463. es.Status.SyncedResourceVersion = getResourceVersion(es)
  1464. Expect(shouldRefresh(es)).To(BeTrue())
  1465. })
  1466. It("should refresh when no refresh time was set", func() {
  1467. es := esv1beta1.ExternalSecret{
  1468. ObjectMeta: metav1.ObjectMeta{
  1469. Generation: 1,
  1470. },
  1471. Spec: esv1beta1.ExternalSecretSpec{
  1472. RefreshInterval: &metav1.Duration{Duration: time.Second},
  1473. },
  1474. Status: esv1beta1.ExternalSecretStatus{},
  1475. }
  1476. // resource version matches
  1477. es.Status.SyncedResourceVersion = getResourceVersion(es)
  1478. Expect(shouldRefresh(es)).To(BeTrue())
  1479. })
  1480. })
  1481. Context("objectmeta hash", func() {
  1482. It("should produce different hashes for different k/v pairs", func() {
  1483. h1 := hashMeta(metav1.ObjectMeta{
  1484. Generation: 1,
  1485. Annotations: map[string]string{
  1486. "foo": "bar",
  1487. },
  1488. })
  1489. h2 := hashMeta(metav1.ObjectMeta{
  1490. Generation: 1,
  1491. Annotations: map[string]string{
  1492. "foo": "bing",
  1493. },
  1494. })
  1495. Expect(h1).ToNot(Equal(h2))
  1496. })
  1497. It("should produce different hashes for different generations but same label/annotations", func() {
  1498. h1 := hashMeta(metav1.ObjectMeta{
  1499. Generation: 1,
  1500. Annotations: map[string]string{
  1501. "foo": "bar",
  1502. },
  1503. Labels: map[string]string{
  1504. "foo": "bar",
  1505. },
  1506. })
  1507. h2 := hashMeta(metav1.ObjectMeta{
  1508. Generation: 2,
  1509. Annotations: map[string]string{
  1510. "foo": "bar",
  1511. },
  1512. Labels: map[string]string{
  1513. "foo": "bar",
  1514. },
  1515. })
  1516. Expect(h1).To(Equal(h2))
  1517. })
  1518. It("should produce the same hash for the same k/v pairs", func() {
  1519. h1 := hashMeta(metav1.ObjectMeta{
  1520. Generation: 1,
  1521. })
  1522. h2 := hashMeta(metav1.ObjectMeta{
  1523. Generation: 1,
  1524. })
  1525. Expect(h1).To(Equal(h2))
  1526. h1 = hashMeta(metav1.ObjectMeta{
  1527. Generation: 1,
  1528. Annotations: map[string]string{
  1529. "foo": "bar",
  1530. },
  1531. })
  1532. h2 = hashMeta(metav1.ObjectMeta{
  1533. Generation: 1,
  1534. Annotations: map[string]string{
  1535. "foo": "bar",
  1536. },
  1537. })
  1538. Expect(h1).To(Equal(h2))
  1539. })
  1540. })
  1541. })
  1542. var _ = Describe("Controller Reconcile logic", func() {
  1543. Context("controller reconcile", func() {
  1544. It("should reconcile when resource is not synced", func() {
  1545. Expect(shouldReconcile(esv1beta1.ExternalSecret{
  1546. Status: esv1beta1.ExternalSecretStatus{
  1547. SyncedResourceVersion: "some resource version",
  1548. Conditions: []esv1beta1.ExternalSecretStatusCondition{{Reason: "NotASecretSynced"}},
  1549. },
  1550. })).To(BeTrue())
  1551. })
  1552. It("should reconcile when secret isn't immutable", func() {
  1553. Expect(shouldReconcile(esv1beta1.ExternalSecret{
  1554. Spec: esv1beta1.ExternalSecretSpec{
  1555. Target: esv1beta1.ExternalSecretTarget{
  1556. Immutable: false,
  1557. },
  1558. },
  1559. })).To(BeTrue())
  1560. })
  1561. It("should not reconcile if secret is immutable and has synced condition", func() {
  1562. Expect(shouldReconcile(esv1beta1.ExternalSecret{
  1563. Spec: esv1beta1.ExternalSecretSpec{
  1564. Target: esv1beta1.ExternalSecretTarget{
  1565. Immutable: true,
  1566. },
  1567. },
  1568. Status: esv1beta1.ExternalSecretStatus{
  1569. SyncedResourceVersion: "some resource version",
  1570. Conditions: []esv1beta1.ExternalSecretStatusCondition{{Reason: "SecretSynced"}},
  1571. },
  1572. })).To(BeFalse())
  1573. })
  1574. })
  1575. })
  1576. func externalSecretConditionShouldBe(name, ns string, ct esv1beta1.ExternalSecretConditionType, cs v1.ConditionStatus, v float64) bool {
  1577. return Eventually(func() float64 {
  1578. Expect(externalSecretCondition.WithLabelValues(name, ns, string(ct), string(cs)).Write(&metric)).To(Succeed())
  1579. return metric.GetGauge().GetValue()
  1580. }, timeout, interval).Should(Equal(v))
  1581. }
  1582. func init() {
  1583. fakeProvider = fake.New()
  1584. esv1beta1.ForceRegister(fakeProvider, &esv1beta1.SecretStoreProvider{
  1585. AWS: &esv1beta1.AWSProvider{
  1586. Service: esv1beta1.AWSServiceSecretsManager,
  1587. },
  1588. })
  1589. }