externalsecret_controller_test.go 62 KB

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