externalsecret_controller_test.go 88 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408
  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. "encoding/json"
  17. "fmt"
  18. "os"
  19. "strconv"
  20. "time"
  21. . "github.com/onsi/ginkgo/v2"
  22. . "github.com/onsi/gomega"
  23. "github.com/prometheus/client_golang/prometheus"
  24. dto "github.com/prometheus/client_model/go"
  25. v1 "k8s.io/api/core/v1"
  26. apiextensions "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
  27. apierrors "k8s.io/apimachinery/pkg/api/errors"
  28. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  29. "k8s.io/apimachinery/pkg/types"
  30. "sigs.k8s.io/controller-runtime/pkg/client"
  31. esv1beta1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1beta1"
  32. genv1alpha1 "github.com/external-secrets/external-secrets/apis/generators/v1alpha1"
  33. ctest "github.com/external-secrets/external-secrets/pkg/controllers/commontest"
  34. "github.com/external-secrets/external-secrets/pkg/controllers/externalsecret/esmetrics"
  35. ctrlmetrics "github.com/external-secrets/external-secrets/pkg/controllers/metrics"
  36. "github.com/external-secrets/external-secrets/pkg/provider/testing/fake"
  37. "github.com/external-secrets/external-secrets/pkg/utils"
  38. )
  39. var (
  40. fakeProvider *fake.Client
  41. metric dto.Metric
  42. metricDuration dto.Metric
  43. timeout = time.Second * 10
  44. interval = time.Millisecond * 250
  45. )
  46. var (
  47. testSyncCallsTotal *prometheus.CounterVec
  48. testSyncCallsError *prometheus.CounterVec
  49. testExternalSecretCondition *prometheus.GaugeVec
  50. testExternalSecretReconcileDuration *prometheus.GaugeVec
  51. )
  52. type testCase struct {
  53. secretStore esv1beta1.GenericStore
  54. externalSecret *esv1beta1.ExternalSecret
  55. targetSecretName string
  56. // checkCondition should return true if the externalSecret
  57. // has the expected condition
  58. checkCondition func(*esv1beta1.ExternalSecret) bool
  59. // checkExternalSecret is called after the condition has been verified
  60. // use this to verify the externalSecret
  61. checkExternalSecret func(*esv1beta1.ExternalSecret)
  62. // optional. use this to test the secret value
  63. checkSecret func(*esv1beta1.ExternalSecret, *v1.Secret)
  64. }
  65. type testTweaks func(*testCase)
  66. var _ = Describe("Kind=secret existence logic", func() {
  67. validData := map[string][]byte{
  68. "foo": []byte("value1"),
  69. "bar": []byte("value2"),
  70. }
  71. type testCase struct {
  72. Name string
  73. Input v1.Secret
  74. ExpectedOutput bool
  75. }
  76. tests := []testCase{
  77. {
  78. Name: "Should not be valid in case of missing uid",
  79. Input: v1.Secret{},
  80. ExpectedOutput: false,
  81. },
  82. {
  83. Name: "A nil annotation should not be valid",
  84. Input: v1.Secret{
  85. ObjectMeta: metav1.ObjectMeta{
  86. UID: "xxx",
  87. Annotations: map[string]string{},
  88. },
  89. },
  90. ExpectedOutput: false,
  91. },
  92. {
  93. Name: "A nil annotation should not be valid",
  94. Input: v1.Secret{
  95. ObjectMeta: metav1.ObjectMeta{
  96. UID: "xxx",
  97. Annotations: map[string]string{},
  98. },
  99. },
  100. ExpectedOutput: false,
  101. },
  102. {
  103. Name: "An invalid annotation hash should not be valid",
  104. Input: v1.Secret{
  105. ObjectMeta: metav1.ObjectMeta{
  106. UID: "xxx",
  107. Annotations: map[string]string{
  108. esv1beta1.AnnotationDataHash: "xxxxxx",
  109. },
  110. },
  111. },
  112. ExpectedOutput: false,
  113. },
  114. {
  115. Name: "A valid config map should return true",
  116. Input: v1.Secret{
  117. ObjectMeta: metav1.ObjectMeta{
  118. UID: "xxx",
  119. Annotations: map[string]string{
  120. esv1beta1.AnnotationDataHash: utils.ObjectHash(validData),
  121. },
  122. },
  123. Data: validData,
  124. },
  125. ExpectedOutput: true,
  126. },
  127. }
  128. for _, tt := range tests {
  129. It(tt.Name, func() {
  130. Expect(isSecretValid(tt.Input)).To(BeEquivalentTo(tt.ExpectedOutput))
  131. })
  132. }
  133. })
  134. var _ = Describe("ExternalSecret controller", Serial, func() {
  135. const (
  136. ExternalSecretName = "test-es"
  137. ExternalSecretFQDN = "externalsecrets.external-secrets.io/test-es"
  138. ExternalSecretStore = "test-store"
  139. ExternalSecretTargetSecretName = "test-secret"
  140. FakeManager = "fake.manager"
  141. expectedSecretVal = "SOMEVALUE was templated"
  142. targetPropObj = "{{ .targetProperty | toString | upper }} was templated"
  143. FooValue = "map-foo-value"
  144. BarValue = "map-bar-value"
  145. NamespaceLabelKey = "css-test-label-key"
  146. NamespaceLabelValue = "css-test-label-value"
  147. )
  148. var ExternalSecretNamespace string
  149. // if we are in debug and need to increase the timeout for testing, we can do so by using an env var
  150. if customTimeout := os.Getenv("TEST_CUSTOM_TIMEOUT_SEC"); customTimeout != "" {
  151. if t, err := strconv.Atoi(customTimeout); err == nil {
  152. timeout = time.Second * time.Duration(t)
  153. }
  154. }
  155. BeforeEach(func() {
  156. var err error
  157. ExternalSecretNamespace, err = ctest.CreateNamespaceWithLabels("test-ns", k8sClient, map[string]string{NamespaceLabelKey: NamespaceLabelValue})
  158. Expect(err).ToNot(HaveOccurred())
  159. metric.Reset()
  160. testSyncCallsTotal.Reset()
  161. testSyncCallsError.Reset()
  162. testExternalSecretCondition.Reset()
  163. testExternalSecretReconcileDuration.Reset()
  164. fakeProvider.Reset()
  165. })
  166. AfterEach(
  167. func() {
  168. secretStore := &esv1beta1.SecretStore{}
  169. secretStoreLookupKey := types.NamespacedName{
  170. Name: ExternalSecretStore,
  171. Namespace: ExternalSecretNamespace,
  172. }
  173. if err := k8sClient.Get(context.Background(), secretStoreLookupKey, secretStore); err == nil {
  174. Expect(k8sClient.Delete(context.Background(), secretStore)).To(Succeed())
  175. }
  176. clusterSecretStore := &esv1beta1.ClusterSecretStore{}
  177. clusterSecretStoreLookupKey := types.NamespacedName{
  178. Name: ExternalSecretStore,
  179. }
  180. if err := k8sClient.Get(context.Background(), clusterSecretStoreLookupKey, clusterSecretStore); err == nil {
  181. Expect(k8sClient.Delete(context.Background(), clusterSecretStore)).To(Succeed())
  182. }
  183. Expect(k8sClient.Delete(context.Background(), &v1.Namespace{
  184. ObjectMeta: metav1.ObjectMeta{
  185. Name: ExternalSecretNamespace,
  186. },
  187. })).To(Succeed())
  188. },
  189. )
  190. const (
  191. secretVal = "some-value"
  192. targetProp = "targetProperty"
  193. remoteKey = "barz"
  194. remoteProperty = "bang"
  195. existingKey = "pre-existing-key"
  196. existingVal = "pre-existing-value"
  197. )
  198. makeDefaultTestcase := func() *testCase {
  199. return &testCase{
  200. // default condition: es should be ready
  201. targetSecretName: ExternalSecretTargetSecretName,
  202. checkCondition: func(es *esv1beta1.ExternalSecret) bool {
  203. cond := GetExternalSecretCondition(es.Status, esv1beta1.ExternalSecretReady)
  204. if cond == nil || cond.Status != v1.ConditionTrue {
  205. return false
  206. }
  207. return true
  208. },
  209. checkExternalSecret: func(es *esv1beta1.ExternalSecret) {
  210. // noop by default
  211. },
  212. secretStore: &esv1beta1.SecretStore{
  213. ObjectMeta: metav1.ObjectMeta{
  214. Name: ExternalSecretStore,
  215. Namespace: ExternalSecretNamespace,
  216. },
  217. Spec: esv1beta1.SecretStoreSpec{
  218. Provider: &esv1beta1.SecretStoreProvider{
  219. AWS: &esv1beta1.AWSProvider{
  220. Service: esv1beta1.AWSServiceSecretsManager,
  221. },
  222. },
  223. },
  224. },
  225. externalSecret: &esv1beta1.ExternalSecret{
  226. ObjectMeta: metav1.ObjectMeta{
  227. Name: ExternalSecretName,
  228. Namespace: ExternalSecretNamespace,
  229. },
  230. Spec: esv1beta1.ExternalSecretSpec{
  231. SecretStoreRef: esv1beta1.SecretStoreRef{
  232. Name: ExternalSecretStore,
  233. },
  234. Target: esv1beta1.ExternalSecretTarget{
  235. Name: ExternalSecretTargetSecretName,
  236. },
  237. Data: []esv1beta1.ExternalSecretData{
  238. {
  239. SecretKey: targetProp,
  240. RemoteRef: esv1beta1.ExternalSecretDataRemoteRef{
  241. Key: remoteKey,
  242. Property: remoteProperty,
  243. },
  244. },
  245. },
  246. },
  247. },
  248. }
  249. }
  250. // if target Secret name is not specified it should use the ExternalSecret name.
  251. syncWithoutTargetName := func(tc *testCase) {
  252. tc.externalSecret.Spec.Target.Name = ""
  253. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  254. // check secret name
  255. Expect(secret.ObjectMeta.Name).To(Equal(ExternalSecretName))
  256. // check binding secret on external secret
  257. Expect(es.Status.Binding.Name).To(Equal(secret.ObjectMeta.Name))
  258. }
  259. }
  260. // if target Secret name is not specified it should use the ExternalSecret name.
  261. syncBigNames := func(tc *testCase) {
  262. tc.targetSecretName = "this-is-a-very-big-secret-name-that-wouldnt-be-generated-due-to-label-limits"
  263. tc.externalSecret.Spec.Target.Name = "this-is-a-very-big-secret-name-that-wouldnt-be-generated-due-to-label-limits"
  264. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  265. // check binding secret on external secret
  266. Expect(es.Status.Binding.Name).To(Equal(tc.externalSecret.Spec.Target.Name))
  267. }
  268. }
  269. // the secret name is reflected on the external secret's status as the binding secret
  270. syncBindingSecret := func(tc *testCase) {
  271. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  272. // check binding secret on external secret
  273. Expect(es.Status.Binding.Name).To(Equal(secret.ObjectMeta.Name))
  274. }
  275. }
  276. // their is no binding secret when a secret is not synced
  277. skipBindingSecret := func(tc *testCase) {
  278. tc.externalSecret.Spec.Target.CreationPolicy = esv1beta1.CreatePolicyNone
  279. tc.checkExternalSecret = func(es *esv1beta1.ExternalSecret) {
  280. // check binding secret is not set
  281. Expect(es.Status.Binding.Name).To(BeEmpty())
  282. }
  283. }
  284. // labels and annotations from the Kind=ExternalSecret
  285. // should be copied over to the Kind=Secret
  286. syncLabelsAnnotations := func(tc *testCase) {
  287. const secretVal = "someValue"
  288. tc.externalSecret.ObjectMeta.Labels = map[string]string{
  289. "fooobar": "bazz",
  290. }
  291. tc.externalSecret.ObjectMeta.Annotations = map[string]string{
  292. "hihihih": "hehehe",
  293. }
  294. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  295. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  296. // check value
  297. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  298. // check labels & annotations
  299. for k, v := range es.ObjectMeta.Labels {
  300. Expect(secret.ObjectMeta.Labels).To(HaveKeyWithValue(k, v))
  301. }
  302. for k, v := range es.ObjectMeta.Annotations {
  303. Expect(secret.ObjectMeta.Annotations).To(HaveKeyWithValue(k, v))
  304. }
  305. // ownerRef must not not be set!
  306. Expect(ctest.HasOwnerRef(secret.ObjectMeta, "ExternalSecret", ExternalSecretName)).To(BeTrue())
  307. }
  308. }
  309. checkPrometheusCounters := func(tc *testCase) {
  310. const secretVal = "someValue"
  311. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  312. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  313. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1beta1.ExternalSecretReady, v1.ConditionFalse, 0.0)).To(BeTrue())
  314. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1beta1.ExternalSecretReady, v1.ConditionTrue, 1.0)).To(BeTrue())
  315. Eventually(func() bool {
  316. Expect(testSyncCallsTotal.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metric)).To(Succeed())
  317. Expect(testExternalSecretReconcileDuration.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metricDuration)).To(Succeed())
  318. // three reconciliations: initial sync, status update, secret update
  319. return metric.GetCounter().GetValue() >= 2.0 && metricDuration.GetGauge().GetValue() > 0.0
  320. }, timeout, interval).Should(BeTrue())
  321. }
  322. }
  323. // merge with existing secret using creationPolicy=Merge
  324. // it should NOT have a ownerReference
  325. // metadata.managedFields with the correct owner should be added to the secret
  326. mergeWithSecret := func(tc *testCase) {
  327. const secretVal = "someValue"
  328. tc.externalSecret.Spec.Target.CreationPolicy = esv1beta1.CreatePolicyMerge
  329. // create secret beforehand
  330. Expect(k8sClient.Create(context.Background(), &v1.Secret{
  331. ObjectMeta: metav1.ObjectMeta{
  332. Name: ExternalSecretTargetSecretName,
  333. Namespace: ExternalSecretNamespace,
  334. },
  335. Data: map[string][]byte{
  336. existingKey: []byte(existingVal),
  337. },
  338. }, client.FieldOwner(FakeManager))).To(Succeed())
  339. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  340. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  341. // check value
  342. Expect(string(secret.Data[existingKey])).To(Equal(existingVal))
  343. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  344. // check labels & annotations
  345. for k, v := range es.ObjectMeta.Labels {
  346. Expect(secret.ObjectMeta.Labels).To(HaveKeyWithValue(k, v))
  347. }
  348. for k, v := range es.ObjectMeta.Annotations {
  349. Expect(secret.ObjectMeta.Annotations).To(HaveKeyWithValue(k, v))
  350. }
  351. Expect(ctest.HasOwnerRef(secret.ObjectMeta, "ExternalSecret", ExternalSecretFQDN)).To(BeFalse())
  352. Expect(secret.ObjectMeta.ManagedFields).To(HaveLen(2))
  353. Expect(ctest.HasFieldOwnership(
  354. secret.ObjectMeta,
  355. ExternalSecretFQDN,
  356. fmt.Sprintf("{\"f:data\":{\"f:targetProperty\":{}},\"f:immutable\":{},\"f:metadata\":{\"f:annotations\":{\"f:%s\":{}}}}", esv1beta1.AnnotationDataHash)),
  357. ).To(BeTrue())
  358. Expect(ctest.HasFieldOwnership(secret.ObjectMeta, FakeManager, "{\"f:data\":{\".\":{},\"f:pre-existing-key\":{}},\"f:type\":{}}")).To(BeTrue())
  359. }
  360. }
  361. // should not update if no changes
  362. mergeWithSecretNoChange := func(tc *testCase) {
  363. tc.externalSecret.Spec.Target.CreationPolicy = esv1beta1.CreatePolicyMerge
  364. // create secret beforehand
  365. Expect(k8sClient.Create(context.Background(), &v1.Secret{
  366. ObjectMeta: metav1.ObjectMeta{
  367. Name: ExternalSecretTargetSecretName,
  368. Namespace: ExternalSecretNamespace,
  369. },
  370. Data: map[string][]byte{
  371. existingKey: []byte(existingVal),
  372. },
  373. }, client.FieldOwner(FakeManager))).To(Succeed())
  374. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  375. oldResourceVersion := secret.ResourceVersion
  376. cleanSecret := secret.DeepCopy()
  377. Expect(k8sClient.Patch(context.Background(), secret, client.MergeFrom(cleanSecret))).To(Succeed())
  378. newSecret := &v1.Secret{}
  379. Eventually(func() bool {
  380. secretLookupKey := types.NamespacedName{
  381. Name: ExternalSecretTargetSecretName,
  382. Namespace: ExternalSecretNamespace,
  383. }
  384. err := k8sClient.Get(context.Background(), secretLookupKey, newSecret)
  385. if err != nil {
  386. return false
  387. }
  388. return oldResourceVersion == newSecret.ResourceVersion
  389. }, timeout, interval).Should(Equal(true))
  390. }
  391. }
  392. // should not merge with secret if it doesn't exist
  393. mergeWithSecretErr := func(tc *testCase) {
  394. const secretVal = "someValue"
  395. tc.externalSecret.Spec.Target.CreationPolicy = esv1beta1.CreatePolicyMerge
  396. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  397. tc.checkCondition = func(es *esv1beta1.ExternalSecret) bool {
  398. cond := GetExternalSecretCondition(es.Status, esv1beta1.ExternalSecretReady)
  399. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1beta1.ConditionReasonSecretSyncedError {
  400. return false
  401. }
  402. return true
  403. }
  404. tc.checkExternalSecret = func(es *esv1beta1.ExternalSecret) {
  405. Eventually(func() bool {
  406. Expect(testSyncCallsError.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metric)).To(Succeed())
  407. Expect(testExternalSecretReconcileDuration.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metricDuration)).To(Succeed())
  408. return metric.GetCounter().GetValue() >= 2.0 && metricDuration.GetGauge().GetValue() > 0.0
  409. }, timeout, interval).Should(BeTrue())
  410. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1beta1.ExternalSecretReady, v1.ConditionFalse, 1.0)).To(BeTrue())
  411. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1beta1.ExternalSecretReady, v1.ConditionTrue, 0.0)).To(BeTrue())
  412. }
  413. }
  414. // controller should force ownership
  415. mergeWithConflict := func(tc *testCase) {
  416. const secretVal = "someValue"
  417. // this should confict
  418. const existingKey = targetProp
  419. tc.externalSecret.Spec.Target.CreationPolicy = esv1beta1.CreatePolicyMerge
  420. // create secret beforehand
  421. Expect(k8sClient.Create(context.Background(), &v1.Secret{
  422. ObjectMeta: metav1.ObjectMeta{
  423. Name: ExternalSecretTargetSecretName,
  424. Namespace: ExternalSecretNamespace,
  425. },
  426. Data: map[string][]byte{
  427. existingKey: []byte(existingVal),
  428. },
  429. }, client.FieldOwner(FakeManager))).To(Succeed())
  430. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  431. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  432. // check that value stays the same
  433. Expect(string(secret.Data[existingKey])).To(Equal(secretVal))
  434. // check owner/managedFields
  435. Expect(ctest.HasOwnerRef(secret.ObjectMeta, "ExternalSecret", ExternalSecretFQDN)).To(BeFalse())
  436. Expect(secret.ObjectMeta.ManagedFields).To(HaveLen(2))
  437. Expect(ctest.HasFieldOwnership(
  438. secret.ObjectMeta,
  439. ExternalSecretFQDN,
  440. fmt.Sprintf("{\"f:data\":{\"f:targetProperty\":{}},\"f:immutable\":{},\"f:metadata\":{\"f:annotations\":{\"f:%s\":{}}}}", esv1beta1.AnnotationDataHash)),
  441. ).To(BeTrue())
  442. }
  443. }
  444. syncWithGeneratorRef := func(tc *testCase) {
  445. const secretKey = "somekey"
  446. const secretVal = "someValue"
  447. Expect(k8sClient.Create(context.Background(), &genv1alpha1.Fake{
  448. ObjectMeta: metav1.ObjectMeta{
  449. Name: "mytestfake",
  450. Namespace: ExternalSecretNamespace,
  451. },
  452. Spec: genv1alpha1.FakeSpec{
  453. Data: map[string]string{
  454. secretKey: secretVal,
  455. },
  456. },
  457. })).To(Succeed())
  458. // reset secretStoreRef
  459. tc.externalSecret.Spec.SecretStoreRef = esv1beta1.SecretStoreRef{}
  460. tc.externalSecret.Spec.Data = nil
  461. tc.externalSecret.Spec.DataFrom = []esv1beta1.ExternalSecretDataFromRemoteRef{
  462. {
  463. SourceRef: &esv1beta1.SourceRef{
  464. GeneratorRef: &esv1beta1.GeneratorRef{
  465. APIVersion: genv1alpha1.Group + "/" + genv1alpha1.Version,
  466. Kind: "Fake",
  467. Name: "mytestfake",
  468. },
  469. },
  470. },
  471. }
  472. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  473. // check values
  474. Expect(string(secret.Data[secretKey])).To(Equal(secretVal))
  475. }
  476. }
  477. deleteOrphanedSecrets := func(tc *testCase) {
  478. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  479. cleanEs := es.DeepCopy()
  480. oldSecret := v1.Secret{}
  481. oldSecretName := types.NamespacedName{
  482. Name: "test-secret",
  483. Namespace: secret.Namespace,
  484. }
  485. newSecret := v1.Secret{}
  486. secretName := types.NamespacedName{
  487. Name: "new-foo",
  488. Namespace: secret.Namespace,
  489. }
  490. Eventually(func() bool {
  491. err := k8sClient.Get(context.Background(), oldSecretName, &oldSecret)
  492. return err == nil
  493. }, time.Second*10, time.Millisecond*200).Should(BeTrue())
  494. es.Spec.Target.Name = "new-foo"
  495. Expect(k8sClient.Patch(context.Background(), es, client.MergeFrom(cleanEs))).To(Succeed())
  496. Eventually(func() bool {
  497. err := k8sClient.Get(context.Background(), secretName, &newSecret)
  498. return err == nil
  499. }, time.Second*10, time.Millisecond*200).Should(BeTrue())
  500. Eventually(func() bool {
  501. err := k8sClient.Get(context.Background(), oldSecretName, &oldSecret)
  502. return apierrors.IsNotFound(err)
  503. }, time.Second*10, time.Millisecond*200).Should(BeTrue())
  504. }
  505. }
  506. ignoreMismatchControllerForGeneratorRef := func(tc *testCase) {
  507. const secretKey = "somekey"
  508. const secretVal = "someValue"
  509. fakeGenerator := &genv1alpha1.Fake{
  510. ObjectMeta: metav1.ObjectMeta{
  511. Name: "mytestfake2",
  512. Namespace: ExternalSecretNamespace,
  513. },
  514. Spec: genv1alpha1.FakeSpec{
  515. Data: map[string]string{
  516. secretKey: secretVal,
  517. },
  518. Controller: "fakeControllerClass",
  519. },
  520. }
  521. fakeGeneratorJSON, _ := json.Marshal(fakeGenerator)
  522. Expect(shouldSkipGenerator(
  523. &Reconciler{
  524. ControllerClass: "default",
  525. },
  526. &apiextensions.JSON{Raw: fakeGeneratorJSON},
  527. )).To(BeTrue())
  528. }
  529. syncWithMultipleSecretStores := func(tc *testCase) {
  530. Expect(k8sClient.Create(context.Background(), &esv1beta1.SecretStore{
  531. ObjectMeta: metav1.ObjectMeta{
  532. Name: "foo",
  533. Namespace: ExternalSecretNamespace,
  534. },
  535. Spec: esv1beta1.SecretStoreSpec{
  536. Provider: &esv1beta1.SecretStoreProvider{
  537. Fake: &esv1beta1.FakeProvider{
  538. Data: []esv1beta1.FakeProviderData{
  539. {
  540. Key: "foo",
  541. Version: "",
  542. ValueMap: map[string]string{
  543. "foo": "bar",
  544. "foo2": "bar2",
  545. },
  546. },
  547. },
  548. },
  549. },
  550. },
  551. })).To(Succeed())
  552. Expect(k8sClient.Create(context.Background(), &esv1beta1.SecretStore{
  553. ObjectMeta: metav1.ObjectMeta{
  554. Name: "baz",
  555. Namespace: ExternalSecretNamespace,
  556. },
  557. Spec: esv1beta1.SecretStoreSpec{
  558. Provider: &esv1beta1.SecretStoreProvider{
  559. Fake: &esv1beta1.FakeProvider{
  560. Data: []esv1beta1.FakeProviderData{
  561. {
  562. Key: "baz",
  563. Version: "",
  564. ValueMap: map[string]string{
  565. "baz": "bang",
  566. "baz2": "bang2",
  567. },
  568. },
  569. },
  570. },
  571. },
  572. },
  573. })).To(Succeed())
  574. tc.externalSecret.Spec.DataFrom = []esv1beta1.ExternalSecretDataFromRemoteRef{
  575. {
  576. Extract: &esv1beta1.ExternalSecretDataRemoteRef{
  577. Key: "foo",
  578. },
  579. SourceRef: &esv1beta1.SourceRef{
  580. SecretStoreRef: &esv1beta1.SecretStoreRef{
  581. Name: "foo",
  582. Kind: esv1beta1.SecretStoreKind,
  583. },
  584. },
  585. },
  586. {
  587. Extract: &esv1beta1.ExternalSecretDataRemoteRef{
  588. Key: "baz",
  589. },
  590. SourceRef: &esv1beta1.SourceRef{
  591. SecretStoreRef: &esv1beta1.SecretStoreRef{
  592. Name: "baz",
  593. Kind: esv1beta1.SecretStoreKind,
  594. },
  595. },
  596. },
  597. }
  598. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  599. // check values
  600. Expect(string(secret.Data["foo"])).To(Equal("bar"))
  601. Expect(string(secret.Data["foo2"])).To(Equal("bar2"))
  602. Expect(string(secret.Data["baz"])).To(Equal("bang"))
  603. Expect(string(secret.Data["baz2"])).To(Equal("bang2"))
  604. }
  605. }
  606. // when using a template it should be used as a blueprint
  607. // to construct a new secret: labels, annotations and type
  608. syncWithTemplate := func(tc *testCase) {
  609. const secretVal = "someValue"
  610. const tplStaticKey = "tplstatickey"
  611. const tplStaticVal = "tplstaticvalue"
  612. tc.externalSecret.ObjectMeta.Labels = map[string]string{
  613. "fooobar": "bazz",
  614. }
  615. tc.externalSecret.ObjectMeta.Annotations = map[string]string{
  616. "hihihih": "hehehe",
  617. }
  618. tc.externalSecret.Spec.Target.Template = &esv1beta1.ExternalSecretTemplate{
  619. Metadata: esv1beta1.ExternalSecretTemplateMetadata{
  620. Labels: map[string]string{
  621. "foos": "ball",
  622. },
  623. Annotations: map[string]string{
  624. "hihi": "ga",
  625. },
  626. },
  627. Type: v1.SecretTypeOpaque,
  628. EngineVersion: esv1beta1.TemplateEngineV1,
  629. Data: map[string]string{
  630. targetProp: targetPropObj,
  631. tplStaticKey: tplStaticVal,
  632. },
  633. }
  634. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  635. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  636. // check values
  637. Expect(string(secret.Data[targetProp])).To(Equal(expectedSecretVal))
  638. Expect(string(secret.Data[tplStaticKey])).To(Equal(tplStaticVal))
  639. // labels/annotations should be taken from the template
  640. for k, v := range es.Spec.Target.Template.Metadata.Labels {
  641. Expect(secret.ObjectMeta.Labels).To(HaveKeyWithValue(k, v))
  642. }
  643. for k, v := range es.Spec.Target.Template.Metadata.Annotations {
  644. Expect(secret.ObjectMeta.Annotations).To(HaveKeyWithValue(k, v))
  645. }
  646. }
  647. }
  648. // when using a v2 template it should use the v2 engine version
  649. syncWithTemplateV2 := func(tc *testCase) {
  650. const secretVal = "someValue"
  651. tc.externalSecret.Spec.Target.Template = &esv1beta1.ExternalSecretTemplate{
  652. Type: v1.SecretTypeOpaque,
  653. // it should default to v2 for beta11
  654. // EngineVersion: esv1beta1.TemplateEngineV2,
  655. Data: map[string]string{
  656. targetProp: "{{ .targetProperty | upper }} was templated",
  657. },
  658. }
  659. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  660. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  661. // check values
  662. Expect(string(secret.Data[targetProp])).To(Equal(expectedSecretVal))
  663. }
  664. }
  665. // // secret should be synced with correct value precedence:
  666. // // * fromString
  667. // // * template data
  668. // // * templateFrom
  669. // // * data
  670. // // * dataFrom
  671. syncWithTemplatePrecedence := func(tc *testCase) {
  672. const secretVal = "someValue"
  673. const tplStaticKey = "tplstatickey"
  674. const tplStaticVal = "tplstaticvalue"
  675. const tplFromCMName = "template-cm"
  676. const tplFromSecretName = "template-secret"
  677. const tplFromKey = "tpl-from-key"
  678. const tplFromSecKey = "tpl-from-sec-key"
  679. const tplFromVal = "tpl-from-value: {{ .targetProperty | toString }} // {{ .bar | toString }}"
  680. const tplFromSecVal = "tpl-from-sec-value: {{ .targetProperty | toString }} // {{ .bar | toString }}"
  681. Expect(k8sClient.Create(context.Background(), &v1.ConfigMap{
  682. ObjectMeta: metav1.ObjectMeta{
  683. Name: tplFromCMName,
  684. Namespace: ExternalSecretNamespace,
  685. },
  686. Data: map[string]string{
  687. tplFromKey: tplFromVal,
  688. },
  689. })).To(Succeed())
  690. Expect(k8sClient.Create(context.Background(), &v1.Secret{
  691. ObjectMeta: metav1.ObjectMeta{
  692. Name: tplFromSecretName,
  693. Namespace: ExternalSecretNamespace,
  694. },
  695. Data: map[string][]byte{
  696. tplFromSecKey: []byte(tplFromSecVal),
  697. },
  698. })).To(Succeed())
  699. tc.externalSecret.Spec.Target.Template = &esv1beta1.ExternalSecretTemplate{
  700. Metadata: esv1beta1.ExternalSecretTemplateMetadata{},
  701. Type: v1.SecretTypeOpaque,
  702. TemplateFrom: []esv1beta1.TemplateFrom{
  703. {
  704. ConfigMap: &esv1beta1.TemplateRef{
  705. Name: tplFromCMName,
  706. Items: []esv1beta1.TemplateRefItem{
  707. {
  708. Key: tplFromKey,
  709. },
  710. },
  711. },
  712. },
  713. {
  714. Secret: &esv1beta1.TemplateRef{
  715. Name: tplFromSecretName,
  716. Items: []esv1beta1.TemplateRefItem{
  717. {
  718. Key: tplFromSecKey,
  719. },
  720. },
  721. },
  722. },
  723. },
  724. Data: map[string]string{
  725. // this should be the data value, not dataFrom
  726. targetProp: targetPropObj,
  727. // this should use the value from the map
  728. "bar": "value from map: {{ .bar | toString }}",
  729. // just a static value
  730. tplStaticKey: tplStaticVal,
  731. },
  732. }
  733. tc.externalSecret.Spec.DataFrom = []esv1beta1.ExternalSecretDataFromRemoteRef{
  734. {
  735. Extract: &esv1beta1.ExternalSecretDataRemoteRef{
  736. Key: "datamap",
  737. },
  738. },
  739. }
  740. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  741. fakeProvider.WithGetSecretMap(map[string][]byte{
  742. "targetProperty": []byte(FooValue),
  743. "bar": []byte(BarValue),
  744. }, nil)
  745. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  746. // check values
  747. Expect(string(secret.Data[targetProp])).To(Equal(expectedSecretVal))
  748. Expect(string(secret.Data[tplStaticKey])).To(Equal(tplStaticVal))
  749. Expect(string(secret.Data["bar"])).To(Equal("value from map: map-bar-value"))
  750. Expect(string(secret.Data[tplFromKey])).To(Equal("tpl-from-value: someValue // map-bar-value"))
  751. Expect(string(secret.Data[tplFromSecKey])).To(Equal("tpl-from-sec-value: someValue // map-bar-value"))
  752. }
  753. }
  754. syncTemplateFromKeysAndValues := func(tc *testCase) {
  755. const tplFromCMName = "template-cm"
  756. const tplFromSecretName = "template-secret"
  757. const tplFromKey = "tpl-from-key"
  758. const tplFromSecKey = "tpl-from-sec-key"
  759. const tplFromVal = "{{ .targetKey }}-cm: {{ .targetValue }}"
  760. const tplFromSecVal = "{{ .targetKey }}-sec: {{ .targetValue }}"
  761. Expect(k8sClient.Create(context.Background(), &v1.ConfigMap{
  762. ObjectMeta: metav1.ObjectMeta{
  763. Name: tplFromCMName,
  764. Namespace: ExternalSecretNamespace,
  765. },
  766. Data: map[string]string{
  767. tplFromKey: tplFromVal,
  768. },
  769. })).To(Succeed())
  770. Expect(k8sClient.Create(context.Background(), &v1.Secret{
  771. ObjectMeta: metav1.ObjectMeta{
  772. Name: tplFromSecretName,
  773. Namespace: ExternalSecretNamespace,
  774. },
  775. Data: map[string][]byte{
  776. tplFromSecKey: []byte(tplFromSecVal),
  777. },
  778. })).To(Succeed())
  779. tc.externalSecret.Spec.Target.Template = &esv1beta1.ExternalSecretTemplate{
  780. Metadata: esv1beta1.ExternalSecretTemplateMetadata{},
  781. Type: v1.SecretTypeOpaque,
  782. TemplateFrom: []esv1beta1.TemplateFrom{
  783. {
  784. ConfigMap: &esv1beta1.TemplateRef{
  785. Name: tplFromCMName,
  786. Items: []esv1beta1.TemplateRefItem{
  787. {
  788. Key: tplFromKey,
  789. TemplateAs: esv1beta1.TemplateScopeKeysAndValues,
  790. },
  791. },
  792. },
  793. },
  794. {
  795. Secret: &esv1beta1.TemplateRef{
  796. Name: tplFromSecretName,
  797. Items: []esv1beta1.TemplateRefItem{
  798. {
  799. Key: tplFromSecKey,
  800. TemplateAs: esv1beta1.TemplateScopeKeysAndValues,
  801. },
  802. },
  803. },
  804. },
  805. },
  806. }
  807. tc.externalSecret.Spec.DataFrom = []esv1beta1.ExternalSecretDataFromRemoteRef{
  808. {
  809. Extract: &esv1beta1.ExternalSecretDataRemoteRef{
  810. Key: "datamap",
  811. },
  812. },
  813. }
  814. fakeProvider.WithGetSecretMap(map[string][]byte{
  815. "targetKey": []byte(FooValue),
  816. "targetValue": []byte(BarValue),
  817. }, nil)
  818. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  819. // check values
  820. Expect(string(secret.Data["map-foo-value-cm"])).To(Equal(BarValue))
  821. Expect(string(secret.Data["map-foo-value-sec"])).To(Equal(BarValue))
  822. }
  823. }
  824. syncTemplateFromLiteral := func(tc *testCase) {
  825. tplDataVal := "{{ .targetKey }}-literal: {{ .targetValue }}"
  826. tplAnnotationsVal := "{{ .targetKey }}-annotations: {{ .targetValue }}"
  827. tplLabelsVal := "{{ .targetKey }}-labels: {{ .targetValue }}"
  828. tplComplexVal := `
  829. {{- range $k, $v := ( .complex | fromJson )}}
  830. {{ $k }}: {{ $v }}
  831. {{- end }}
  832. `
  833. tc.externalSecret.Spec.Target.Template = &esv1beta1.ExternalSecretTemplate{
  834. Metadata: esv1beta1.ExternalSecretTemplateMetadata{},
  835. Type: v1.SecretTypeOpaque,
  836. TemplateFrom: []esv1beta1.TemplateFrom{
  837. {
  838. Literal: &tplDataVal,
  839. },
  840. {
  841. Literal: &tplComplexVal,
  842. },
  843. {
  844. Target: esv1beta1.TemplateTargetAnnotations,
  845. Literal: &tplAnnotationsVal,
  846. },
  847. {
  848. Target: esv1beta1.TemplateTargetLabels,
  849. Literal: &tplLabelsVal,
  850. },
  851. },
  852. }
  853. tc.externalSecret.Spec.DataFrom = []esv1beta1.ExternalSecretDataFromRemoteRef{
  854. {
  855. Extract: &esv1beta1.ExternalSecretDataRemoteRef{
  856. Key: "datamap",
  857. },
  858. },
  859. }
  860. fakeProvider.WithGetSecretMap(map[string][]byte{
  861. "targetKey": []byte(FooValue),
  862. "targetValue": []byte(BarValue),
  863. "complex": []byte("{\"nested\":\"json\",\"can\":\"be\",\"templated\":\"successfully\"}"),
  864. }, nil)
  865. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  866. // check values
  867. Expect(string(secret.Data["map-foo-value-literal"])).To(Equal(BarValue))
  868. Expect(string(secret.Data["nested"])).To(Equal("json"))
  869. Expect(string(secret.Data["can"])).To(Equal("be"))
  870. Expect(string(secret.Data["templated"])).To(Equal("successfully"))
  871. Expect(secret.ObjectMeta.Annotations["map-foo-value-annotations"]).To(Equal(BarValue))
  872. Expect(secret.ObjectMeta.Labels["map-foo-value-labels"]).To(Equal(BarValue))
  873. }
  874. }
  875. refreshWithTemplate := func(tc *testCase) {
  876. const secretVal = "someValue"
  877. const tplStaticKey = "tplstatickey"
  878. const tplStaticVal = "tplstaticvalue"
  879. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Second}
  880. tc.externalSecret.Spec.Target.Template = &esv1beta1.ExternalSecretTemplate{
  881. Metadata: esv1beta1.ExternalSecretTemplateMetadata{
  882. Labels: map[string]string{"foo": "bar"},
  883. Annotations: map[string]string{"foo": "bar"},
  884. },
  885. Type: v1.SecretTypeOpaque,
  886. Data: map[string]string{
  887. targetProp: targetPropObj,
  888. tplStaticKey: tplStaticVal,
  889. },
  890. }
  891. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  892. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  893. // check values
  894. Expect(string(secret.Data[targetProp])).To(Equal(expectedSecretVal))
  895. Expect(string(secret.Data[tplStaticKey])).To(Equal(tplStaticVal))
  896. // labels/annotations should be taken from the template
  897. for k, v := range es.Spec.Target.Template.Metadata.Labels {
  898. Expect(secret.ObjectMeta.Labels).To(HaveKeyWithValue(k, v))
  899. }
  900. // a secret will always have some extra annotations (i.e. hashmap check), so we only check for specific
  901. // source annotations
  902. for k, v := range es.Spec.Target.Template.Metadata.Annotations {
  903. Expect(secret.ObjectMeta.Annotations).To(HaveKeyWithValue(k, v))
  904. }
  905. cleanEs := tc.externalSecret.DeepCopy()
  906. // now update ExternalSecret
  907. tc.externalSecret.Spec.Target.Template.Metadata.Annotations["fuzz"] = "buzz"
  908. tc.externalSecret.Spec.Target.Template.Metadata.Labels["fuzz"] = "buzz"
  909. tc.externalSecret.Spec.Target.Template.Data["new"] = "value"
  910. Expect(k8sClient.Patch(context.Background(), tc.externalSecret, client.MergeFrom(cleanEs))).To(Succeed())
  911. // wait for secret
  912. sec := &v1.Secret{}
  913. secretLookupKey := types.NamespacedName{
  914. Name: ExternalSecretTargetSecretName,
  915. Namespace: ExternalSecretNamespace,
  916. }
  917. Eventually(func() bool {
  918. err := k8sClient.Get(context.Background(), secretLookupKey, sec)
  919. if err != nil {
  920. return false
  921. }
  922. // ensure new data value exist
  923. return string(sec.Data["new"]) == "value"
  924. }, time.Second*10, time.Millisecond*200).Should(BeTrue())
  925. // also check labels/annotations have been updated
  926. for k, v := range es.Spec.Target.Template.Metadata.Labels {
  927. Expect(secret.ObjectMeta.Labels).To(HaveKeyWithValue(k, v))
  928. }
  929. for k, v := range es.Spec.Target.Template.Metadata.Annotations {
  930. Expect(secret.ObjectMeta.Annotations).To(HaveKeyWithValue(k, v))
  931. }
  932. }
  933. }
  934. onlyMetadataFromTemplate := func(tc *testCase) {
  935. const secretVal = "someValue"
  936. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Second}
  937. tc.externalSecret.Spec.Target.Template = &esv1beta1.ExternalSecretTemplate{
  938. Metadata: esv1beta1.ExternalSecretTemplateMetadata{
  939. Labels: map[string]string{"foo": "bar"},
  940. Annotations: map[string]string{"foo": "bar"},
  941. },
  942. }
  943. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  944. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  945. // check values
  946. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  947. // labels/annotations should be taken from the template
  948. for k, v := range es.Spec.Target.Template.Metadata.Labels {
  949. Expect(secret.ObjectMeta.Labels).To(HaveKeyWithValue(k, v))
  950. }
  951. for k, v := range es.Spec.Target.Template.Metadata.Annotations {
  952. Expect(secret.ObjectMeta.Annotations).To(HaveKeyWithValue(k, v))
  953. }
  954. }
  955. }
  956. // when the provider secret changes the Kind=Secret value
  957. // must change, too.
  958. refreshSecretValue := func(tc *testCase) {
  959. const targetProp = "targetProperty"
  960. const secretVal = "someValue"
  961. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  962. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Second}
  963. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  964. // check values
  965. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  966. // update provider secret
  967. newValue := "NEW VALUE"
  968. sec := &v1.Secret{}
  969. fakeProvider.WithGetSecret([]byte(newValue), nil)
  970. secretLookupKey := types.NamespacedName{
  971. Name: ExternalSecretTargetSecretName,
  972. Namespace: ExternalSecretNamespace,
  973. }
  974. Eventually(func() bool {
  975. err := k8sClient.Get(context.Background(), secretLookupKey, sec)
  976. if err != nil {
  977. return false
  978. }
  979. v := sec.Data[targetProp]
  980. return string(v) == newValue
  981. }, timeout, interval).Should(BeTrue())
  982. }
  983. }
  984. // when a provider secret was deleted it must be deleted from
  985. // the secret aswell
  986. refreshSecretValueMap := func(tc *testCase) {
  987. fakeProvider.WithGetSecretMap(map[string][]byte{
  988. "foo": []byte("1111"),
  989. "bar": []byte("2222"),
  990. }, nil)
  991. tc.externalSecret.Spec.Data = []esv1beta1.ExternalSecretData{}
  992. tc.externalSecret.Spec.DataFrom = []esv1beta1.ExternalSecretDataFromRemoteRef{
  993. {
  994. Extract: &esv1beta1.ExternalSecretDataRemoteRef{
  995. Key: remoteKey,
  996. },
  997. },
  998. }
  999. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Second}
  1000. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  1001. // check values
  1002. Expect(string(secret.Data["foo"])).To(Equal("1111"))
  1003. Expect(string(secret.Data["bar"])).To(Equal("2222"))
  1004. // update provider secret
  1005. sec := &v1.Secret{}
  1006. fakeProvider.WithGetSecretMap(map[string][]byte{
  1007. "foo": []byte("1111"),
  1008. }, nil)
  1009. secretLookupKey := types.NamespacedName{
  1010. Name: ExternalSecretTargetSecretName,
  1011. Namespace: ExternalSecretNamespace,
  1012. }
  1013. Eventually(func() bool {
  1014. err := k8sClient.Get(context.Background(), secretLookupKey, sec)
  1015. if err != nil {
  1016. return false
  1017. }
  1018. return string(sec.Data["foo"]) == "1111" &&
  1019. sec.Data["bar"] == nil // must not be defined, it was deleted
  1020. }, timeout, interval).Should(BeTrue())
  1021. }
  1022. }
  1023. // when a provider secret was deleted it must be deleted from
  1024. // the secret aswell when using a template
  1025. refreshSecretValueMapTemplate := func(tc *testCase) {
  1026. fakeProvider.WithGetSecretMap(map[string][]byte{
  1027. "foo": []byte("1111"),
  1028. "bar": []byte("2222"),
  1029. }, nil)
  1030. tc.externalSecret.Spec.Target.Template = &esv1beta1.ExternalSecretTemplate{}
  1031. tc.externalSecret.Spec.Data = []esv1beta1.ExternalSecretData{}
  1032. tc.externalSecret.Spec.DataFrom = []esv1beta1.ExternalSecretDataFromRemoteRef{
  1033. {
  1034. Extract: &esv1beta1.ExternalSecretDataRemoteRef{
  1035. Key: remoteKey,
  1036. },
  1037. },
  1038. }
  1039. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Second}
  1040. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  1041. // check values
  1042. Expect(string(secret.Data["foo"])).To(Equal("1111"))
  1043. Expect(string(secret.Data["bar"])).To(Equal("2222"))
  1044. // update provider secret
  1045. sec := &v1.Secret{}
  1046. fakeProvider.WithGetSecretMap(map[string][]byte{
  1047. "foo": []byte("1111"),
  1048. }, nil)
  1049. secretLookupKey := types.NamespacedName{
  1050. Name: ExternalSecretTargetSecretName,
  1051. Namespace: ExternalSecretNamespace,
  1052. }
  1053. Eventually(func() bool {
  1054. err := k8sClient.Get(context.Background(), secretLookupKey, sec)
  1055. if err != nil {
  1056. return false
  1057. }
  1058. return string(sec.Data["foo"]) == "1111" &&
  1059. sec.Data["bar"] == nil // must not be defined, it was deleted
  1060. }, timeout, interval).Should(BeTrue())
  1061. }
  1062. }
  1063. refreshintervalZero := func(tc *testCase) {
  1064. const targetProp = "targetProperty"
  1065. const secretVal = "someValue"
  1066. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  1067. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: 0}
  1068. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  1069. // check values
  1070. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  1071. // update provider secret
  1072. newValue := "NEW VALUE"
  1073. sec := &v1.Secret{}
  1074. fakeProvider.WithGetSecret([]byte(newValue), nil)
  1075. secretLookupKey := types.NamespacedName{
  1076. Name: ExternalSecretTargetSecretName,
  1077. Namespace: ExternalSecretNamespace,
  1078. }
  1079. Consistently(func() bool {
  1080. err := k8sClient.Get(context.Background(), secretLookupKey, sec)
  1081. if err != nil {
  1082. return false
  1083. }
  1084. v := sec.Data[targetProp]
  1085. return string(v) == secretVal
  1086. }, time.Second*10, time.Second).Should(BeTrue())
  1087. }
  1088. }
  1089. deleteSecretPolicy := func(tc *testCase) {
  1090. expVal := []byte("1234")
  1091. // set initial value
  1092. fakeProvider.WithGetAllSecrets(map[string][]byte{
  1093. "foo": expVal,
  1094. "bar": expVal,
  1095. }, nil)
  1096. tc.externalSecret.Spec.Data = nil
  1097. tc.externalSecret.Spec.DataFrom = []esv1beta1.ExternalSecretDataFromRemoteRef{
  1098. {
  1099. Find: &esv1beta1.ExternalSecretFind{
  1100. Tags: map[string]string{},
  1101. },
  1102. },
  1103. }
  1104. tc.externalSecret.Spec.Target.DeletionPolicy = esv1beta1.DeletionPolicyDelete
  1105. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Second}
  1106. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  1107. Expect(secret.Data["foo"]).To(Equal(expVal))
  1108. // update provider secret
  1109. fakeProvider.WithGetAllSecrets(map[string][]byte{
  1110. "foo": expVal,
  1111. }, nil)
  1112. sec := &v1.Secret{}
  1113. secretLookupKey := types.NamespacedName{
  1114. Name: ExternalSecretTargetSecretName,
  1115. Namespace: ExternalSecretNamespace,
  1116. }
  1117. Eventually(func() bool {
  1118. By("checking secret value for foo=1234 and bar=nil")
  1119. err := k8sClient.Get(context.Background(), secretLookupKey, sec)
  1120. if err != nil {
  1121. return false
  1122. }
  1123. return bytes.Equal(sec.Data["foo"], expVal) && sec.Data["bar"] == nil
  1124. }, time.Second*10, time.Second).Should(BeTrue())
  1125. // return specific delete err to indicate deletion
  1126. fakeProvider.WithGetAllSecrets(map[string][]byte{}, esv1beta1.NoSecretErr)
  1127. Eventually(func() bool {
  1128. By("checking that secret has been deleted")
  1129. err := k8sClient.Get(context.Background(), secretLookupKey, sec)
  1130. return apierrors.IsNotFound(err)
  1131. }, time.Second*10, time.Second).Should(BeTrue())
  1132. }
  1133. }
  1134. deleteSecretPolicyRetain := func(tc *testCase) {
  1135. expVal := []byte("1234")
  1136. // set initial value
  1137. fakeProvider.WithGetAllSecrets(map[string][]byte{
  1138. "foo": expVal,
  1139. "bar": expVal,
  1140. }, nil)
  1141. tc.externalSecret.Spec.DataFrom = []esv1beta1.ExternalSecretDataFromRemoteRef{
  1142. {
  1143. Find: &esv1beta1.ExternalSecretFind{
  1144. Tags: map[string]string{},
  1145. },
  1146. },
  1147. }
  1148. tc.externalSecret.Spec.Target.DeletionPolicy = esv1beta1.DeletionPolicyRetain
  1149. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Second}
  1150. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  1151. Expect(secret.Data["foo"]).To(Equal(expVal))
  1152. sec := &v1.Secret{}
  1153. secretLookupKey := types.NamespacedName{
  1154. Name: ExternalSecretTargetSecretName,
  1155. Namespace: ExternalSecretNamespace,
  1156. }
  1157. // return specific delete err to indicate deletion
  1158. // however this should not trigger a delete
  1159. fakeProvider.WithGetAllSecrets(map[string][]byte{}, esv1beta1.NoSecretErr)
  1160. Consistently(func() bool {
  1161. By("checking that secret has not been deleted")
  1162. err := k8sClient.Get(context.Background(), secretLookupKey, sec)
  1163. return apierrors.IsNotFound(err) && bytes.Equal(sec.Data["foo"], expVal)
  1164. }, time.Second*10, time.Second).Should(BeFalse())
  1165. }
  1166. }
  1167. // merge with existing secret using creationPolicy=Merge
  1168. // if provider secret gets deleted only the managed field should get deleted
  1169. deleteSecretPolicyMerge := func(tc *testCase) {
  1170. const secretVal = "someValue"
  1171. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Second}
  1172. tc.externalSecret.Spec.Target.CreationPolicy = esv1beta1.CreatePolicyMerge
  1173. tc.externalSecret.Spec.Target.DeletionPolicy = esv1beta1.DeletionPolicyMerge
  1174. // create secret beforehand
  1175. Expect(k8sClient.Create(context.Background(), &v1.Secret{
  1176. ObjectMeta: metav1.ObjectMeta{
  1177. Name: ExternalSecretTargetSecretName,
  1178. Namespace: ExternalSecretNamespace,
  1179. },
  1180. Data: map[string][]byte{
  1181. existingKey: []byte(existingVal),
  1182. },
  1183. }, client.FieldOwner(FakeManager))).To(Succeed())
  1184. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  1185. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  1186. // check value
  1187. Expect(string(secret.Data[existingKey])).To(Equal(existingVal))
  1188. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  1189. sec := &v1.Secret{}
  1190. secretLookupKey := types.NamespacedName{
  1191. Name: ExternalSecretTargetSecretName,
  1192. Namespace: ExternalSecretNamespace,
  1193. }
  1194. // return specific delete err to indicate deletion
  1195. // however this should not trigger a delete
  1196. // instead expect that only the pre-existing value exists
  1197. fakeProvider.WithGetSecret(nil, esv1beta1.NoSecretErr)
  1198. Eventually(func() bool {
  1199. By("checking that secret has not been deleted and pre-existing key exists")
  1200. err := k8sClient.Get(context.Background(), secretLookupKey, sec)
  1201. return !apierrors.IsNotFound(err) &&
  1202. len(sec.Data) == 1 &&
  1203. bytes.Equal(sec.Data[existingKey], []byte(existingVal))
  1204. }, time.Second*30, time.Second).Should(BeTrue())
  1205. }
  1206. }
  1207. // orphan the secret after the external secret has been deleted
  1208. createSecretPolicyOrphan := func(tc *testCase) {
  1209. const secretVal = "someValue"
  1210. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Second}
  1211. tc.externalSecret.Spec.Target.CreationPolicy = esv1beta1.CreatePolicyOrphan
  1212. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  1213. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  1214. // check value
  1215. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  1216. sec := &v1.Secret{}
  1217. secretLookupKey := types.NamespacedName{
  1218. Name: ExternalSecretTargetSecretName,
  1219. Namespace: ExternalSecretNamespace,
  1220. }
  1221. err := k8sClient.Delete(context.Background(), tc.externalSecret)
  1222. Expect(err).ToNot(HaveOccurred())
  1223. Consistently(func() bool {
  1224. By("checking that secret has not been deleted")
  1225. err := k8sClient.Get(context.Background(), secretLookupKey, sec)
  1226. return !apierrors.IsNotFound(err)
  1227. }, time.Second*15, time.Second).Should(BeTrue())
  1228. }
  1229. }
  1230. // with rewrite all keys from a dataFrom operation
  1231. // should be put with new rewriting into the secret
  1232. syncAndRewriteWithDataFrom := func(tc *testCase) {
  1233. tc.externalSecret.Spec.Data = nil
  1234. tc.externalSecret.Spec.DataFrom = []esv1beta1.ExternalSecretDataFromRemoteRef{
  1235. {
  1236. Extract: &esv1beta1.ExternalSecretDataRemoteRef{
  1237. Key: remoteKey,
  1238. },
  1239. Rewrite: []esv1beta1.ExternalSecretRewrite{{
  1240. Regexp: &esv1beta1.ExternalSecretRewriteRegexp{
  1241. Source: "(.*)",
  1242. Target: "new-$1",
  1243. },
  1244. }},
  1245. },
  1246. {
  1247. Extract: &esv1beta1.ExternalSecretDataRemoteRef{
  1248. Key: remoteKey,
  1249. },
  1250. Rewrite: []esv1beta1.ExternalSecretRewrite{{
  1251. Regexp: &esv1beta1.ExternalSecretRewriteRegexp{
  1252. Source: "(.*)",
  1253. Target: "old-$1",
  1254. },
  1255. }},
  1256. },
  1257. }
  1258. fakeProvider.WithGetSecretMap(map[string][]byte{
  1259. "foo": []byte(FooValue),
  1260. "bar": []byte(BarValue),
  1261. }, nil)
  1262. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  1263. // check values
  1264. Expect(string(secret.Data["new-foo"])).To(Equal(FooValue))
  1265. Expect(string(secret.Data["new-bar"])).To(Equal(BarValue))
  1266. Expect(string(secret.Data["old-foo"])).To(Equal(FooValue))
  1267. Expect(string(secret.Data["old-bar"])).To(Equal(BarValue))
  1268. }
  1269. }
  1270. // with rewrite keys from dataFrom
  1271. // should error if keys are not compliant
  1272. invalidExtractKeysErrCondition := func(tc *testCase) {
  1273. tc.externalSecret.Spec.Data = nil
  1274. tc.externalSecret.Spec.DataFrom = []esv1beta1.ExternalSecretDataFromRemoteRef{
  1275. {
  1276. Extract: &esv1beta1.ExternalSecretDataRemoteRef{
  1277. Key: remoteKey,
  1278. },
  1279. Rewrite: []esv1beta1.ExternalSecretRewrite{{
  1280. Regexp: &esv1beta1.ExternalSecretRewriteRegexp{
  1281. Source: "(.*)",
  1282. Target: "$1",
  1283. },
  1284. }},
  1285. },
  1286. }
  1287. fakeProvider.WithGetSecretMap(map[string][]byte{
  1288. "foo/bar": []byte(FooValue),
  1289. "bar/foo": []byte(BarValue),
  1290. }, nil)
  1291. tc.checkCondition = func(es *esv1beta1.ExternalSecret) bool {
  1292. cond := GetExternalSecretCondition(es.Status, esv1beta1.ExternalSecretReady)
  1293. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1beta1.ConditionReasonSecretSyncedError {
  1294. return false
  1295. }
  1296. return true
  1297. }
  1298. tc.checkCondition = func(es *esv1beta1.ExternalSecret) bool {
  1299. cond := GetExternalSecretCondition(es.Status, esv1beta1.ExternalSecretReady)
  1300. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1beta1.ConditionReasonSecretSyncedError {
  1301. return false
  1302. }
  1303. return true
  1304. }
  1305. tc.checkExternalSecret = func(es *esv1beta1.ExternalSecret) {
  1306. Eventually(func() bool {
  1307. Expect(testSyncCallsError.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metric)).To(Succeed())
  1308. Expect(testExternalSecretReconcileDuration.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metricDuration)).To(Succeed())
  1309. return metric.GetCounter().GetValue() >= 2.0 && metricDuration.GetGauge().GetValue() > 0.0
  1310. }, timeout, interval).Should(BeTrue())
  1311. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1beta1.ExternalSecretReady, v1.ConditionFalse, 1.0)).To(BeTrue())
  1312. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1beta1.ExternalSecretReady, v1.ConditionTrue, 0.0)).To(BeTrue())
  1313. }
  1314. }
  1315. // with rewrite keys from dataFrom
  1316. // should error if keys are not compliant
  1317. invalidFindKeysErrCondition := func(tc *testCase) {
  1318. tc.externalSecret.Spec.Data = nil
  1319. tc.externalSecret.Spec.DataFrom = []esv1beta1.ExternalSecretDataFromRemoteRef{
  1320. {
  1321. Find: &esv1beta1.ExternalSecretFind{
  1322. Name: &esv1beta1.FindName{
  1323. RegExp: ".*",
  1324. },
  1325. },
  1326. Rewrite: []esv1beta1.ExternalSecretRewrite{{
  1327. Regexp: &esv1beta1.ExternalSecretRewriteRegexp{
  1328. Source: "(.*)",
  1329. Target: "$1",
  1330. },
  1331. }},
  1332. },
  1333. }
  1334. fakeProvider.WithGetAllSecrets(map[string][]byte{
  1335. "foo/bar": []byte(FooValue),
  1336. "bar/foo": []byte(BarValue),
  1337. }, nil)
  1338. tc.checkCondition = func(es *esv1beta1.ExternalSecret) bool {
  1339. cond := GetExternalSecretCondition(es.Status, esv1beta1.ExternalSecretReady)
  1340. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1beta1.ConditionReasonSecretSyncedError {
  1341. return false
  1342. }
  1343. return true
  1344. }
  1345. tc.checkCondition = func(es *esv1beta1.ExternalSecret) bool {
  1346. cond := GetExternalSecretCondition(es.Status, esv1beta1.ExternalSecretReady)
  1347. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1beta1.ConditionReasonSecretSyncedError {
  1348. return false
  1349. }
  1350. return true
  1351. }
  1352. tc.checkExternalSecret = func(es *esv1beta1.ExternalSecret) {
  1353. Eventually(func() bool {
  1354. Expect(testSyncCallsError.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metric)).To(Succeed())
  1355. Expect(testExternalSecretReconcileDuration.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metricDuration)).To(Succeed())
  1356. return metric.GetCounter().GetValue() >= 2.0 && metricDuration.GetGauge().GetValue() > 0.0
  1357. }, timeout, interval).Should(BeTrue())
  1358. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1beta1.ExternalSecretReady, v1.ConditionFalse, 1.0)).To(BeTrue())
  1359. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1beta1.ExternalSecretReady, v1.ConditionTrue, 0.0)).To(BeTrue())
  1360. }
  1361. }
  1362. // with dataFrom all properties from the specified secret
  1363. // should be put into the secret
  1364. syncWithDataFrom := func(tc *testCase) {
  1365. tc.externalSecret.Spec.Data = nil
  1366. tc.externalSecret.Spec.DataFrom = []esv1beta1.ExternalSecretDataFromRemoteRef{
  1367. {
  1368. Extract: &esv1beta1.ExternalSecretDataRemoteRef{
  1369. Key: remoteKey,
  1370. },
  1371. },
  1372. }
  1373. fakeProvider.WithGetSecretMap(map[string][]byte{
  1374. "foo": []byte(FooValue),
  1375. "bar": []byte(BarValue),
  1376. }, nil)
  1377. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  1378. // check values
  1379. Expect(string(secret.Data["foo"])).To(Equal(FooValue))
  1380. Expect(string(secret.Data["bar"])).To(Equal(BarValue))
  1381. }
  1382. }
  1383. // with dataFrom.Find the change is on the called method GetAllSecrets
  1384. // all keys should be put into the secret
  1385. syncAndRewriteDataFromFind := func(tc *testCase) {
  1386. tc.externalSecret.Spec.Data = nil
  1387. tc.externalSecret.Spec.DataFrom = []esv1beta1.ExternalSecretDataFromRemoteRef{
  1388. {
  1389. Find: &esv1beta1.ExternalSecretFind{
  1390. Name: &esv1beta1.FindName{
  1391. RegExp: "foobar",
  1392. },
  1393. },
  1394. Rewrite: []esv1beta1.ExternalSecretRewrite{
  1395. {
  1396. Regexp: &esv1beta1.ExternalSecretRewriteRegexp{
  1397. Source: "(.*)",
  1398. Target: "new-$1",
  1399. },
  1400. },
  1401. },
  1402. },
  1403. }
  1404. fakeProvider.WithGetAllSecrets(map[string][]byte{
  1405. "foo": []byte(FooValue),
  1406. "bar": []byte(BarValue),
  1407. }, nil)
  1408. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  1409. // check values
  1410. Expect(string(secret.Data["new-foo"])).To(Equal(FooValue))
  1411. Expect(string(secret.Data["new-bar"])).To(Equal(BarValue))
  1412. }
  1413. }
  1414. // with dataFrom.Find the change is on the called method GetAllSecrets
  1415. // all keys should be put into the secret
  1416. syncDataFromFind := func(tc *testCase) {
  1417. tc.externalSecret.Spec.Data = nil
  1418. tc.externalSecret.Spec.DataFrom = []esv1beta1.ExternalSecretDataFromRemoteRef{
  1419. {
  1420. Find: &esv1beta1.ExternalSecretFind{
  1421. Name: &esv1beta1.FindName{
  1422. RegExp: "foobar",
  1423. },
  1424. },
  1425. },
  1426. }
  1427. fakeProvider.WithGetAllSecrets(map[string][]byte{
  1428. "foo": []byte(FooValue),
  1429. "bar": []byte(BarValue),
  1430. }, nil)
  1431. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  1432. // check values
  1433. Expect(string(secret.Data["foo"])).To(Equal(FooValue))
  1434. Expect(string(secret.Data["bar"])).To(Equal(BarValue))
  1435. }
  1436. }
  1437. // with dataFrom and using a template
  1438. // should be put into the secret
  1439. syncWithDataFromTemplate := func(tc *testCase) {
  1440. tc.externalSecret.Spec.Data = nil
  1441. tc.externalSecret.Spec.Target = esv1beta1.ExternalSecretTarget{
  1442. Name: ExternalSecretTargetSecretName,
  1443. Template: &esv1beta1.ExternalSecretTemplate{
  1444. Type: v1.SecretTypeTLS,
  1445. },
  1446. }
  1447. tc.externalSecret.Spec.DataFrom = []esv1beta1.ExternalSecretDataFromRemoteRef{
  1448. {
  1449. Extract: &esv1beta1.ExternalSecretDataRemoteRef{
  1450. Key: remoteKey,
  1451. },
  1452. },
  1453. }
  1454. fakeProvider.WithGetSecretMap(map[string][]byte{
  1455. "tls.crt": []byte(FooValue),
  1456. "tls.key": []byte(BarValue),
  1457. }, nil)
  1458. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  1459. Expect(secret.Type).To(Equal(v1.SecretTypeTLS))
  1460. // check values
  1461. Expect(string(secret.Data["tls.crt"])).To(Equal(FooValue))
  1462. Expect(string(secret.Data["tls.key"])).To(Equal(BarValue))
  1463. }
  1464. }
  1465. // when a provider errors in a GetSecret call
  1466. // a error condition must be set.
  1467. providerErrCondition := func(tc *testCase) {
  1468. const secretVal = "foobar"
  1469. fakeProvider.WithGetSecret(nil, fmt.Errorf("boom"))
  1470. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Millisecond * 100}
  1471. tc.checkCondition = func(es *esv1beta1.ExternalSecret) bool {
  1472. cond := GetExternalSecretCondition(es.Status, esv1beta1.ExternalSecretReady)
  1473. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1beta1.ConditionReasonSecretSyncedError {
  1474. return false
  1475. }
  1476. return true
  1477. }
  1478. tc.checkExternalSecret = func(es *esv1beta1.ExternalSecret) {
  1479. Eventually(func() bool {
  1480. Expect(testSyncCallsError.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metric)).To(Succeed())
  1481. Expect(testExternalSecretReconcileDuration.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metricDuration)).To(Succeed())
  1482. return metric.GetCounter().GetValue() >= 2.0 && metricDuration.GetGauge().GetValue() > 0.0
  1483. }, timeout, interval).Should(BeTrue())
  1484. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1beta1.ExternalSecretReady, v1.ConditionFalse, 1.0)).To(BeTrue())
  1485. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1beta1.ExternalSecretReady, v1.ConditionTrue, 0.0)).To(BeTrue())
  1486. // es condition should reflect recovered provider error
  1487. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  1488. esKey := types.NamespacedName{Name: ExternalSecretName, Namespace: ExternalSecretNamespace}
  1489. Eventually(func() bool {
  1490. err := k8sClient.Get(context.Background(), esKey, es)
  1491. if err != nil {
  1492. return false
  1493. }
  1494. // condition must now be true!
  1495. cond := GetExternalSecretCondition(es.Status, esv1beta1.ExternalSecretReady)
  1496. if cond == nil && cond.Status != v1.ConditionTrue {
  1497. return false
  1498. }
  1499. return true
  1500. }, timeout, interval).Should(BeTrue())
  1501. }
  1502. }
  1503. // When a ExternalSecret references an non-existing SecretStore
  1504. // a error condition must be set.
  1505. storeMissingErrCondition := func(tc *testCase) {
  1506. tc.externalSecret.Spec.SecretStoreRef.Name = "nonexistent"
  1507. tc.checkCondition = func(es *esv1beta1.ExternalSecret) bool {
  1508. cond := GetExternalSecretCondition(es.Status, esv1beta1.ExternalSecretReady)
  1509. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1beta1.ConditionReasonSecretSyncedError {
  1510. return false
  1511. }
  1512. return true
  1513. }
  1514. tc.checkExternalSecret = func(es *esv1beta1.ExternalSecret) {
  1515. Eventually(func() bool {
  1516. Expect(testSyncCallsError.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metric)).To(Succeed())
  1517. Expect(testExternalSecretReconcileDuration.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metricDuration)).To(Succeed())
  1518. return metric.GetCounter().GetValue() >= 2.0 && metricDuration.GetGauge().GetValue() > 0.0
  1519. }, timeout, interval).Should(BeTrue())
  1520. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1beta1.ExternalSecretReady, v1.ConditionFalse, 1.0)).To(BeTrue())
  1521. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1beta1.ExternalSecretReady, v1.ConditionTrue, 0.0)).To(BeTrue())
  1522. }
  1523. }
  1524. // when the provider constructor errors (e.g. invalid configuration)
  1525. // a SecretSyncedError status condition must be set
  1526. storeConstructErrCondition := func(tc *testCase) {
  1527. fakeProvider.WithNew(func(context.Context, esv1beta1.GenericStore, client.Client,
  1528. string) (esv1beta1.SecretsClient, error) {
  1529. return nil, fmt.Errorf("artificial constructor error")
  1530. })
  1531. tc.checkCondition = func(es *esv1beta1.ExternalSecret) bool {
  1532. // condition must be false
  1533. cond := GetExternalSecretCondition(es.Status, esv1beta1.ExternalSecretReady)
  1534. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1beta1.ConditionReasonSecretSyncedError {
  1535. return false
  1536. }
  1537. return true
  1538. }
  1539. tc.checkExternalSecret = func(es *esv1beta1.ExternalSecret) {
  1540. Eventually(func() bool {
  1541. Expect(testSyncCallsError.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metric)).To(Succeed())
  1542. Expect(testExternalSecretReconcileDuration.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metricDuration)).To(Succeed())
  1543. return metric.GetCounter().GetValue() >= 2.0 && metricDuration.GetGauge().GetValue() > 0.0
  1544. }, timeout, interval).Should(BeTrue())
  1545. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1beta1.ExternalSecretReady, v1.ConditionFalse, 1.0)).To(BeTrue())
  1546. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1beta1.ExternalSecretReady, v1.ConditionTrue, 0.0)).To(BeTrue())
  1547. }
  1548. }
  1549. // when a SecretStore has a controller field set which we don't care about
  1550. // the externalSecret must not be touched
  1551. ignoreMismatchController := func(tc *testCase) {
  1552. tc.secretStore.GetSpec().Controller = "nop"
  1553. tc.checkCondition = func(es *esv1beta1.ExternalSecret) bool {
  1554. cond := GetExternalSecretCondition(es.Status, esv1beta1.ExternalSecretReady)
  1555. return cond == nil
  1556. }
  1557. tc.checkExternalSecret = func(es *esv1beta1.ExternalSecret) {
  1558. // Condition True and False should be 0, since the Condition was not created
  1559. Eventually(func() float64 {
  1560. Expect(testExternalSecretCondition.WithLabelValues(ExternalSecretName, ExternalSecretNamespace, string(esv1beta1.ExternalSecretReady), string(v1.ConditionTrue)).Write(&metric)).To(Succeed())
  1561. return metric.GetGauge().GetValue()
  1562. }, timeout, interval).Should(Equal(0.0))
  1563. Eventually(func() float64 {
  1564. Expect(testExternalSecretCondition.WithLabelValues(ExternalSecretName, ExternalSecretNamespace, string(esv1beta1.ExternalSecretReady), string(v1.ConditionFalse)).Write(&metric)).To(Succeed())
  1565. return metric.GetGauge().GetValue()
  1566. }, timeout, interval).Should(Equal(0.0))
  1567. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1beta1.ExternalSecretReady, v1.ConditionFalse, 0.0)).To(BeTrue())
  1568. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1beta1.ExternalSecretReady, v1.ConditionTrue, 0.0)).To(BeTrue())
  1569. }
  1570. }
  1571. ignoreClusterSecretStoreWhenDisabled := func(tc *testCase) {
  1572. tc.externalSecret.Spec.SecretStoreRef.Kind = esv1beta1.ClusterSecretStoreKind
  1573. Expect(shouldSkipClusterSecretStore(
  1574. &Reconciler{
  1575. ClusterSecretStoreEnabled: false,
  1576. },
  1577. *tc.externalSecret,
  1578. )).To(BeTrue())
  1579. tc.checkCondition = func(es *esv1beta1.ExternalSecret) bool {
  1580. cond := GetExternalSecretCondition(es.Status, esv1beta1.ExternalSecretReady)
  1581. return cond == nil
  1582. }
  1583. }
  1584. // When the ownership is set to owner, and we delete a dependent child kind=secret
  1585. // it should be recreated without waiting for refresh interval
  1586. checkDeletion := func(tc *testCase) {
  1587. const secretVal = "someValue"
  1588. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  1589. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Minute * 10}
  1590. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  1591. // check values
  1592. oldUID := secret.UID
  1593. Expect(oldUID).NotTo(BeEmpty())
  1594. // delete the related config
  1595. Expect(k8sClient.Delete(context.TODO(), secret))
  1596. var newSecret v1.Secret
  1597. secretLookupKey := types.NamespacedName{
  1598. Name: ExternalSecretTargetSecretName,
  1599. Namespace: ExternalSecretNamespace,
  1600. }
  1601. Eventually(func() bool {
  1602. err := k8sClient.Get(context.Background(), secretLookupKey, &newSecret)
  1603. if err != nil {
  1604. return false
  1605. }
  1606. // new secret should be a new, recreated object with a different UID
  1607. return newSecret.UID != oldUID
  1608. }, timeout, interval).Should(BeTrue())
  1609. }
  1610. }
  1611. // Checks that secret annotation has been written based on the data
  1612. checkSecretDataHashAnnotation := func(tc *testCase) {
  1613. const secretVal = "someValue"
  1614. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  1615. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  1616. expectedHash := utils.ObjectHash(map[string][]byte{
  1617. targetProp: []byte(secretVal),
  1618. })
  1619. Expect(secret.Annotations[esv1beta1.AnnotationDataHash]).To(Equal(expectedHash))
  1620. }
  1621. }
  1622. // Checks that secret annotation has been written based on the all the data for merge keys
  1623. checkMergeSecretDataHashAnnotation := func(tc *testCase) {
  1624. const secretVal = "someValue"
  1625. tc.externalSecret.Spec.Target.CreationPolicy = esv1beta1.CreatePolicyMerge
  1626. // create secret beforehand
  1627. Expect(k8sClient.Create(context.Background(), &v1.Secret{
  1628. ObjectMeta: metav1.ObjectMeta{
  1629. Name: ExternalSecretTargetSecretName,
  1630. Namespace: ExternalSecretNamespace,
  1631. },
  1632. Data: map[string][]byte{
  1633. existingKey: []byte(existingVal),
  1634. },
  1635. }, client.FieldOwner(FakeManager))).To(Succeed())
  1636. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  1637. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  1638. expectedHash := utils.ObjectHash(map[string][]byte{
  1639. existingKey: []byte(existingVal),
  1640. targetProp: []byte(secretVal),
  1641. })
  1642. Expect(secret.Annotations[esv1beta1.AnnotationDataHash]).To(Equal(expectedHash))
  1643. }
  1644. }
  1645. // When we amend the created kind=secret, refresh operation should be run again regardless of refresh interval
  1646. checkSecretDataHashAnnotationChange := func(tc *testCase) {
  1647. fakeData := map[string][]byte{
  1648. "targetProperty": []byte(FooValue),
  1649. }
  1650. fakeProvider.WithGetSecretMap(fakeData, nil)
  1651. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Minute * 10}
  1652. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  1653. oldHash := secret.Annotations[esv1beta1.AnnotationDataHash]
  1654. oldResourceVersion := secret.ResourceVersion
  1655. Expect(oldHash).NotTo(BeEmpty())
  1656. cleanSecret := secret.DeepCopy()
  1657. secret.Data["new"] = []byte("value")
  1658. secret.ObjectMeta.Annotations[esv1beta1.AnnotationDataHash] = "thisiswronghash"
  1659. Expect(k8sClient.Patch(context.Background(), secret, client.MergeFrom(cleanSecret))).To(Succeed())
  1660. var refreshedSecret v1.Secret
  1661. secretLookupKey := types.NamespacedName{
  1662. Name: ExternalSecretTargetSecretName,
  1663. Namespace: ExternalSecretNamespace,
  1664. }
  1665. Eventually(func() bool {
  1666. err := k8sClient.Get(context.Background(), secretLookupKey, &refreshedSecret)
  1667. if err != nil {
  1668. return false
  1669. }
  1670. // refreshed secret should have a different generation (sign that it was updated), but since
  1671. // the secret source is the same (not changed), the hash should be reverted to an old value
  1672. return refreshedSecret.ResourceVersion != oldResourceVersion && refreshedSecret.Annotations[esv1beta1.AnnotationDataHash] == oldHash
  1673. }, timeout, interval).Should(BeTrue())
  1674. }
  1675. }
  1676. // When we update the template, remaining keys should not be preserved
  1677. templateShouldRewrite := func(tc *testCase) {
  1678. const secretVal = "someValue"
  1679. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  1680. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Minute * 10}
  1681. tc.externalSecret.Spec.Target.Template = &esv1beta1.ExternalSecretTemplate{
  1682. Data: map[string]string{
  1683. "key": `{{.targetProperty}}-foo`,
  1684. },
  1685. }
  1686. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  1687. Expect(secret.Data["key"]).To(Equal([]byte("someValue-foo")))
  1688. newEs := es.DeepCopy()
  1689. newEs.Spec.Target.Template.Data = map[string]string{
  1690. "new": "foo",
  1691. }
  1692. Expect(k8sClient.Patch(context.Background(), newEs, client.MergeFrom(es))).To(Succeed())
  1693. var refreshedSecret v1.Secret
  1694. secretLookupKey := types.NamespacedName{
  1695. Name: ExternalSecretTargetSecretName,
  1696. Namespace: ExternalSecretNamespace,
  1697. }
  1698. Eventually(func() bool {
  1699. err := k8sClient.Get(context.Background(), secretLookupKey, &refreshedSecret)
  1700. if err != nil {
  1701. return false
  1702. }
  1703. _, ok := refreshedSecret.Data["key"]
  1704. return !ok && bytes.Equal(refreshedSecret.Data["new"], []byte("foo"))
  1705. }, timeout, interval).Should(BeTrue())
  1706. }
  1707. }
  1708. // When we update the template, remaining keys should not be preserved
  1709. templateShouldMerge := func(tc *testCase) {
  1710. const secretVal = "someValue"
  1711. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  1712. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Minute * 10}
  1713. tc.externalSecret.Spec.Target.Template = &esv1beta1.ExternalSecretTemplate{
  1714. MergePolicy: esv1beta1.MergePolicyMerge,
  1715. Data: map[string]string{
  1716. "key": `{{.targetProperty}}-foo`,
  1717. },
  1718. }
  1719. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  1720. Expect(secret.Data["key"]).To(Equal([]byte("someValue-foo")))
  1721. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  1722. }
  1723. }
  1724. useClusterSecretStore := func(tc *testCase) {
  1725. tc.secretStore = &esv1beta1.ClusterSecretStore{
  1726. ObjectMeta: metav1.ObjectMeta{
  1727. Name: ExternalSecretStore,
  1728. },
  1729. Spec: esv1beta1.SecretStoreSpec{
  1730. Provider: &esv1beta1.SecretStoreProvider{
  1731. AWS: &esv1beta1.AWSProvider{
  1732. Service: esv1beta1.AWSServiceSecretsManager,
  1733. },
  1734. },
  1735. },
  1736. }
  1737. tc.externalSecret.Spec.SecretStoreRef.Kind = esv1beta1.ClusterSecretStoreKind
  1738. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  1739. }
  1740. // Secret is created when ClusterSecretStore has no conditions
  1741. noConditionsSecretCreated := func(tc *testCase) {
  1742. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  1743. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  1744. }
  1745. }
  1746. // Secret is not created when ClusterSecretStore has a single non-matching string condition
  1747. noSecretCreatedWhenNamespaceDoesntMatchStringCondition := func(tc *testCase) {
  1748. tc.secretStore.GetSpec().Conditions = []esv1beta1.ClusterSecretStoreCondition{
  1749. {
  1750. Namespaces: []string{"some-other-ns"},
  1751. },
  1752. }
  1753. tc.checkCondition = func(es *esv1beta1.ExternalSecret) bool {
  1754. cond := GetExternalSecretCondition(es.Status, esv1beta1.ExternalSecretReady)
  1755. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1beta1.ConditionReasonSecretSyncedError {
  1756. return false
  1757. }
  1758. return true
  1759. }
  1760. }
  1761. // Secret is not created when ClusterSecretStore has a single non-matching string condition with multiple names
  1762. noSecretCreatedWhenNamespaceDoesntMatchStringConditionWithMultipleNames := func(tc *testCase) {
  1763. tc.secretStore.GetSpec().Conditions = []esv1beta1.ClusterSecretStoreCondition{
  1764. {
  1765. Namespaces: []string{"some-other-ns", "another-ns"},
  1766. },
  1767. }
  1768. tc.checkCondition = func(es *esv1beta1.ExternalSecret) bool {
  1769. cond := GetExternalSecretCondition(es.Status, esv1beta1.ExternalSecretReady)
  1770. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1beta1.ConditionReasonSecretSyncedError {
  1771. return false
  1772. }
  1773. return true
  1774. }
  1775. }
  1776. // Secret is not created when ClusterSecretStore has a multiple non-matching string condition
  1777. noSecretCreatedWhenNamespaceDoesntMatchMultipleStringCondition := func(tc *testCase) {
  1778. tc.secretStore.GetSpec().Conditions = []esv1beta1.ClusterSecretStoreCondition{
  1779. {
  1780. Namespaces: []string{"some-other-ns"},
  1781. },
  1782. {
  1783. Namespaces: []string{"another-ns"},
  1784. },
  1785. }
  1786. tc.checkCondition = func(es *esv1beta1.ExternalSecret) bool {
  1787. cond := GetExternalSecretCondition(es.Status, esv1beta1.ExternalSecretReady)
  1788. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1beta1.ConditionReasonSecretSyncedError {
  1789. return false
  1790. }
  1791. return true
  1792. }
  1793. }
  1794. // Secret is created when ClusterSecretStore has a single matching string condition
  1795. secretCreatedWhenNamespaceMatchesSingleStringCondition := func(tc *testCase) {
  1796. tc.secretStore.GetSpec().Conditions = []esv1beta1.ClusterSecretStoreCondition{
  1797. {
  1798. Namespaces: []string{ExternalSecretNamespace},
  1799. },
  1800. }
  1801. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  1802. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  1803. }
  1804. }
  1805. // Secret is created when ClusterSecretStore has a multiple string conditions, one matching
  1806. secretCreatedWhenNamespaceMatchesMultipleStringConditions := func(tc *testCase) {
  1807. tc.secretStore.GetSpec().Conditions = []esv1beta1.ClusterSecretStoreCondition{
  1808. {
  1809. Namespaces: []string{ExternalSecretNamespace, "some-other-ns"},
  1810. },
  1811. }
  1812. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  1813. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  1814. }
  1815. }
  1816. // Secret is not created when ClusterSecretStore has a single non-matching label condition
  1817. noSecretCreatedWhenNamespaceDoesntMatchLabelCondition := func(tc *testCase) {
  1818. tc.secretStore.GetSpec().Conditions = []esv1beta1.ClusterSecretStoreCondition{
  1819. {
  1820. NamespaceSelector: &metav1.LabelSelector{MatchLabels: map[string]string{"some-label-key": "some-label-value"}},
  1821. },
  1822. }
  1823. tc.checkCondition = func(es *esv1beta1.ExternalSecret) bool {
  1824. cond := GetExternalSecretCondition(es.Status, esv1beta1.ExternalSecretReady)
  1825. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1beta1.ConditionReasonSecretSyncedError {
  1826. return false
  1827. }
  1828. return true
  1829. }
  1830. }
  1831. // Secret is created when ClusterSecretStore has a single matching label condition
  1832. secretCreatedWhenNamespaceMatchOnlyLabelCondition := func(tc *testCase) {
  1833. tc.secretStore.GetSpec().Conditions = []esv1beta1.ClusterSecretStoreCondition{
  1834. {
  1835. NamespaceSelector: &metav1.LabelSelector{MatchLabels: map[string]string{NamespaceLabelKey: NamespaceLabelValue}},
  1836. },
  1837. }
  1838. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  1839. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  1840. }
  1841. }
  1842. // Secret is not created when ClusterSecretStore has a partially matching label condition
  1843. noSecretCreatedWhenNamespacePartiallyMatchLabelCondition := func(tc *testCase) {
  1844. tc.secretStore.GetSpec().Conditions = []esv1beta1.ClusterSecretStoreCondition{
  1845. {
  1846. NamespaceSelector: &metav1.LabelSelector{MatchLabels: map[string]string{NamespaceLabelKey: NamespaceLabelValue, "some-label-key": "some-label-value"}},
  1847. },
  1848. }
  1849. tc.checkCondition = func(es *esv1beta1.ExternalSecret) bool {
  1850. cond := GetExternalSecretCondition(es.Status, esv1beta1.ExternalSecretReady)
  1851. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1beta1.ConditionReasonSecretSyncedError {
  1852. return false
  1853. }
  1854. return true
  1855. }
  1856. }
  1857. // Secret is created when ClusterSecretStore has at least one matching label condition
  1858. secretCreatedWhenNamespaceMatchOneLabelCondition := func(tc *testCase) {
  1859. tc.secretStore.GetSpec().Conditions = []esv1beta1.ClusterSecretStoreCondition{
  1860. {
  1861. NamespaceSelector: &metav1.LabelSelector{MatchLabels: map[string]string{NamespaceLabelKey: NamespaceLabelValue}},
  1862. },
  1863. {
  1864. NamespaceSelector: &metav1.LabelSelector{MatchLabels: map[string]string{"some-label-key": "some-label-value"}},
  1865. },
  1866. }
  1867. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  1868. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  1869. }
  1870. }
  1871. // Secret is created when ClusterSecretStore has multiple matching conditions
  1872. secretCreatedWhenNamespaceMatchMultipleConditions := func(tc *testCase) {
  1873. tc.secretStore.GetSpec().Conditions = []esv1beta1.ClusterSecretStoreCondition{
  1874. {
  1875. NamespaceSelector: &metav1.LabelSelector{MatchLabels: map[string]string{NamespaceLabelKey: NamespaceLabelValue}},
  1876. },
  1877. {
  1878. Namespaces: []string{ExternalSecretNamespace},
  1879. },
  1880. }
  1881. tc.checkSecret = func(es *esv1beta1.ExternalSecret, secret *v1.Secret) {
  1882. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  1883. }
  1884. }
  1885. // Secret is not created when ClusterSecretStore has multiple non-matching conditions
  1886. noSecretCreatedWhenNamespaceMatchMultipleNonMatchingConditions := func(tc *testCase) {
  1887. tc.secretStore.GetSpec().Conditions = []esv1beta1.ClusterSecretStoreCondition{
  1888. {
  1889. NamespaceSelector: &metav1.LabelSelector{MatchLabels: map[string]string{"some-label-key": "some-label-value"}},
  1890. },
  1891. {
  1892. Namespaces: []string{"some-other-ns"},
  1893. },
  1894. }
  1895. tc.checkCondition = func(es *esv1beta1.ExternalSecret) bool {
  1896. cond := GetExternalSecretCondition(es.Status, esv1beta1.ExternalSecretReady)
  1897. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1beta1.ConditionReasonSecretSyncedError {
  1898. return false
  1899. }
  1900. return true
  1901. }
  1902. }
  1903. DescribeTable("When reconciling an ExternalSecret",
  1904. func(tweaks ...testTweaks) {
  1905. tc := makeDefaultTestcase()
  1906. for _, tweak := range tweaks {
  1907. tweak(tc)
  1908. }
  1909. ctx := context.Background()
  1910. By("creating a secret store and external secret")
  1911. Expect(k8sClient.Create(ctx, tc.secretStore)).To(Succeed())
  1912. Expect(k8sClient.Create(ctx, tc.externalSecret)).Should(Succeed())
  1913. esKey := types.NamespacedName{Name: ExternalSecretName, Namespace: ExternalSecretNamespace}
  1914. createdES := &esv1beta1.ExternalSecret{}
  1915. By("checking the es condition")
  1916. Eventually(func() bool {
  1917. err := k8sClient.Get(ctx, esKey, createdES)
  1918. if err != nil {
  1919. return false
  1920. }
  1921. return tc.checkCondition(createdES)
  1922. }, timeout, interval).Should(BeTrue())
  1923. tc.checkExternalSecret(createdES)
  1924. // this must be optional so we can test faulty es configuration
  1925. if tc.checkSecret != nil {
  1926. syncedSecret := &v1.Secret{}
  1927. secretLookupKey := types.NamespacedName{
  1928. Name: tc.targetSecretName,
  1929. Namespace: ExternalSecretNamespace,
  1930. }
  1931. if createdES.Spec.Target.Name == "" {
  1932. secretLookupKey = types.NamespacedName{
  1933. Name: ExternalSecretName,
  1934. Namespace: ExternalSecretNamespace,
  1935. }
  1936. }
  1937. Eventually(func() bool {
  1938. err := k8sClient.Get(ctx, secretLookupKey, syncedSecret)
  1939. return err == nil
  1940. }, timeout, interval).Should(BeTrue())
  1941. tc.checkSecret(createdES, syncedSecret)
  1942. }
  1943. },
  1944. Entry("should recreate deleted secret", checkDeletion),
  1945. Entry("should create proper hash annotation for the external secret", checkSecretDataHashAnnotation),
  1946. Entry("should create proper hash annotation for the external secret with creationPolicy=Merge", checkMergeSecretDataHashAnnotation),
  1947. Entry("es deletes orphaned secrets", deleteOrphanedSecrets),
  1948. Entry("should refresh when the hash annotation doesn't correspond to secret data", checkSecretDataHashAnnotationChange),
  1949. Entry("should use external secret name if target secret name isn't defined", syncWithoutTargetName),
  1950. Entry("should sync to target secrets with naming bigger than 63 characters", syncBigNames),
  1951. Entry("should expose the secret as a provisioned service binding secret", syncBindingSecret),
  1952. Entry("should not expose a provisioned service when no secret is synced", skipBindingSecret),
  1953. Entry("should set the condition eventually", syncLabelsAnnotations),
  1954. Entry("should set prometheus counters", checkPrometheusCounters),
  1955. Entry("should merge with existing secret using creationPolicy=Merge", mergeWithSecret),
  1956. Entry("should error if secret doesn't exist when using creationPolicy=Merge", mergeWithSecretErr),
  1957. Entry("should not resolve conflicts with creationPolicy=Merge", mergeWithConflict),
  1958. Entry("should not update unchanged secret using creationPolicy=Merge", mergeWithSecretNoChange),
  1959. Entry("should not delete pre-existing secret with creationPolicy=Orphan", createSecretPolicyOrphan),
  1960. Entry("should sync with generatorRef", syncWithGeneratorRef),
  1961. Entry("should not process generatorRef with mismatching controller field", ignoreMismatchControllerForGeneratorRef),
  1962. Entry("should sync with multiple secret stores via sourceRef", syncWithMultipleSecretStores),
  1963. Entry("should sync with template", syncWithTemplate),
  1964. Entry("should sync with template engine v2", syncWithTemplateV2),
  1965. Entry("should sync template with correct value precedence", syncWithTemplatePrecedence),
  1966. Entry("should sync template from keys and values", syncTemplateFromKeysAndValues),
  1967. Entry("should sync template from literal", syncTemplateFromLiteral),
  1968. Entry("should update template if ExternalSecret is updated", templateShouldRewrite),
  1969. Entry("should keep data with templates if MergePolicy=Merge", templateShouldMerge),
  1970. Entry("should refresh secret from template", refreshWithTemplate),
  1971. Entry("should be able to use only metadata from template", onlyMetadataFromTemplate),
  1972. Entry("should refresh secret value when provider secret changes", refreshSecretValue),
  1973. Entry("should refresh secret map when provider secret changes", refreshSecretValueMap),
  1974. Entry("should refresh secret map when provider secret changes when using a template", refreshSecretValueMapTemplate),
  1975. Entry("should not refresh secret value when provider secret changes but refreshInterval is zero", refreshintervalZero),
  1976. Entry("should fetch secret using dataFrom", syncWithDataFrom),
  1977. Entry("should rewrite secret using dataFrom", syncAndRewriteWithDataFrom),
  1978. Entry("should not automatically convert from extract if rewrite is used", invalidExtractKeysErrCondition),
  1979. Entry("should fetch secret using dataFrom.find", syncDataFromFind),
  1980. Entry("should rewrite secret using dataFrom.find", syncAndRewriteDataFromFind),
  1981. Entry("should not automatically convert from find if rewrite is used", invalidFindKeysErrCondition),
  1982. Entry("should fetch secret using dataFrom and a template", syncWithDataFromTemplate),
  1983. Entry("should set error condition when provider errors", providerErrCondition),
  1984. Entry("should set an error condition when store does not exist", storeMissingErrCondition),
  1985. Entry("should set an error condition when store provider constructor fails", storeConstructErrCondition),
  1986. Entry("should not process store with mismatching controller field", ignoreMismatchController),
  1987. Entry("should not process cluster secret store when it is disabled", ignoreClusterSecretStoreWhenDisabled),
  1988. Entry("should eventually delete target secret with deletionPolicy=Delete", deleteSecretPolicy),
  1989. Entry("should not delete target secret with deletionPolicy=Retain", deleteSecretPolicyRetain),
  1990. Entry("should not delete pre-existing secret with deletionPolicy=Merge", deleteSecretPolicyMerge),
  1991. Entry("secret is created when there are no conditions for the cluster secret store", useClusterSecretStore, noConditionsSecretCreated),
  1992. Entry("secret is not created when the condition for the cluster secret store states a different namespace single string condition", useClusterSecretStore, noSecretCreatedWhenNamespaceDoesntMatchStringCondition),
  1993. Entry("secret is not created when the condition for the cluster secret store states a different namespace single string condition with multiple names", useClusterSecretStore, noSecretCreatedWhenNamespaceDoesntMatchStringConditionWithMultipleNames),
  1994. Entry("secret is not created when the condition for the cluster secret store states a different namespace multiple string conditions", useClusterSecretStore, noSecretCreatedWhenNamespaceDoesntMatchMultipleStringCondition),
  1995. Entry("secret is created when the condition for the cluster secret store has only one matching namespace by string condition", useClusterSecretStore, secretCreatedWhenNamespaceMatchesSingleStringCondition),
  1996. Entry("secret is created when the condition for the cluster secret store has one matching namespace of multiple namespaces by string condition", useClusterSecretStore, secretCreatedWhenNamespaceMatchesMultipleStringConditions),
  1997. Entry("secret is not created when the condition for the cluster secret store states a non-matching label condition", useClusterSecretStore, noSecretCreatedWhenNamespaceDoesntMatchLabelCondition),
  1998. Entry("secret is created when the condition for the cluster secret store states a single matching label condition", useClusterSecretStore, secretCreatedWhenNamespaceMatchOnlyLabelCondition),
  1999. Entry("secret is not created when the condition for the cluster secret store states a partially-matching label condition", useClusterSecretStore, noSecretCreatedWhenNamespacePartiallyMatchLabelCondition),
  2000. Entry("secret is created when one of the label conditions for the cluster secret store matches", useClusterSecretStore, secretCreatedWhenNamespaceMatchOneLabelCondition),
  2001. Entry("secret is created when the namespaces matches multiple cluster secret store conditions", useClusterSecretStore, secretCreatedWhenNamespaceMatchMultipleConditions),
  2002. Entry("secret is not created when the namespaces doesn't match any of multiple cluster secret store conditions", useClusterSecretStore, noSecretCreatedWhenNamespaceMatchMultipleNonMatchingConditions),
  2003. )
  2004. })
  2005. var _ = Describe("ExternalSecret refresh logic", func() {
  2006. Context("secret refresh", func() {
  2007. It("should refresh when resource version does not match", func() {
  2008. Expect(shouldRefresh(esv1beta1.ExternalSecret{
  2009. Status: esv1beta1.ExternalSecretStatus{
  2010. SyncedResourceVersion: "some resource version",
  2011. },
  2012. })).To(BeTrue())
  2013. })
  2014. It("should refresh when labels change", func() {
  2015. es := esv1beta1.ExternalSecret{
  2016. ObjectMeta: metav1.ObjectMeta{
  2017. Generation: 1,
  2018. Labels: map[string]string{
  2019. "foo": "bar",
  2020. },
  2021. },
  2022. Spec: esv1beta1.ExternalSecretSpec{
  2023. RefreshInterval: &metav1.Duration{Duration: time.Minute},
  2024. },
  2025. Status: esv1beta1.ExternalSecretStatus{
  2026. RefreshTime: metav1.Now(),
  2027. },
  2028. }
  2029. es.Status.SyncedResourceVersion = getResourceVersion(es)
  2030. // this should not refresh, rv matches object
  2031. Expect(shouldRefresh(es)).To(BeFalse())
  2032. // change labels without changing the syncedResourceVersion and expect refresh
  2033. es.ObjectMeta.Labels["new"] = "w00t"
  2034. Expect(shouldRefresh(es)).To(BeTrue())
  2035. })
  2036. It("should refresh when annotations change", func() {
  2037. es := esv1beta1.ExternalSecret{
  2038. ObjectMeta: metav1.ObjectMeta{
  2039. Generation: 1,
  2040. Annotations: map[string]string{
  2041. "foo": "bar",
  2042. },
  2043. },
  2044. Spec: esv1beta1.ExternalSecretSpec{
  2045. RefreshInterval: &metav1.Duration{Duration: time.Minute},
  2046. },
  2047. Status: esv1beta1.ExternalSecretStatus{
  2048. RefreshTime: metav1.Now(),
  2049. },
  2050. }
  2051. es.Status.SyncedResourceVersion = getResourceVersion(es)
  2052. // this should not refresh, rv matches object
  2053. Expect(shouldRefresh(es)).To(BeFalse())
  2054. // change annotations without changing the syncedResourceVersion and expect refresh
  2055. es.ObjectMeta.Annotations["new"] = "w00t"
  2056. Expect(shouldRefresh(es)).To(BeTrue())
  2057. })
  2058. It("should refresh when generation has changed", func() {
  2059. es := esv1beta1.ExternalSecret{
  2060. ObjectMeta: metav1.ObjectMeta{
  2061. Generation: 1,
  2062. },
  2063. Spec: esv1beta1.ExternalSecretSpec{
  2064. RefreshInterval: &metav1.Duration{Duration: 0},
  2065. },
  2066. Status: esv1beta1.ExternalSecretStatus{
  2067. RefreshTime: metav1.Now(),
  2068. },
  2069. }
  2070. es.Status.SyncedResourceVersion = getResourceVersion(es)
  2071. Expect(shouldRefresh(es)).To(BeFalse())
  2072. // update gen -> refresh
  2073. es.ObjectMeta.Generation = 2
  2074. Expect(shouldRefresh(es)).To(BeTrue())
  2075. })
  2076. It("should skip refresh when refreshInterval is 0", func() {
  2077. es := esv1beta1.ExternalSecret{
  2078. ObjectMeta: metav1.ObjectMeta{
  2079. Generation: 1,
  2080. },
  2081. Spec: esv1beta1.ExternalSecretSpec{
  2082. RefreshInterval: &metav1.Duration{Duration: 0},
  2083. },
  2084. Status: esv1beta1.ExternalSecretStatus{},
  2085. }
  2086. // resource version matches
  2087. es.Status.SyncedResourceVersion = getResourceVersion(es)
  2088. Expect(shouldRefresh(es)).To(BeFalse())
  2089. })
  2090. It("should refresh when refresh interval has passed", func() {
  2091. es := esv1beta1.ExternalSecret{
  2092. ObjectMeta: metav1.ObjectMeta{
  2093. Generation: 1,
  2094. },
  2095. Spec: esv1beta1.ExternalSecretSpec{
  2096. RefreshInterval: &metav1.Duration{Duration: time.Second},
  2097. },
  2098. Status: esv1beta1.ExternalSecretStatus{
  2099. RefreshTime: metav1.NewTime(metav1.Now().Add(-time.Second * 5)),
  2100. },
  2101. }
  2102. // resource version matches
  2103. es.Status.SyncedResourceVersion = getResourceVersion(es)
  2104. Expect(shouldRefresh(es)).To(BeTrue())
  2105. })
  2106. It("should refresh when no refresh time was set", func() {
  2107. es := esv1beta1.ExternalSecret{
  2108. ObjectMeta: metav1.ObjectMeta{
  2109. Generation: 1,
  2110. },
  2111. Spec: esv1beta1.ExternalSecretSpec{
  2112. RefreshInterval: &metav1.Duration{Duration: time.Second},
  2113. },
  2114. Status: esv1beta1.ExternalSecretStatus{},
  2115. }
  2116. // resource version matches
  2117. es.Status.SyncedResourceVersion = getResourceVersion(es)
  2118. Expect(shouldRefresh(es)).To(BeTrue())
  2119. })
  2120. })
  2121. Context("objectmeta hash", func() {
  2122. It("should produce different hashes for different k/v pairs", func() {
  2123. h1 := hashMeta(metav1.ObjectMeta{
  2124. Generation: 1,
  2125. Annotations: map[string]string{
  2126. "foo": "bar",
  2127. },
  2128. })
  2129. h2 := hashMeta(metav1.ObjectMeta{
  2130. Generation: 1,
  2131. Annotations: map[string]string{
  2132. "foo": "bing",
  2133. },
  2134. })
  2135. Expect(h1).ToNot(Equal(h2))
  2136. })
  2137. It("should produce different hashes for different generations but same label/annotations", func() {
  2138. h1 := hashMeta(metav1.ObjectMeta{
  2139. Generation: 1,
  2140. Annotations: map[string]string{
  2141. "foo": "bar",
  2142. },
  2143. Labels: map[string]string{
  2144. "foo": "bar",
  2145. },
  2146. })
  2147. h2 := hashMeta(metav1.ObjectMeta{
  2148. Generation: 2,
  2149. Annotations: map[string]string{
  2150. "foo": "bar",
  2151. },
  2152. Labels: map[string]string{
  2153. "foo": "bar",
  2154. },
  2155. })
  2156. Expect(h1).To(Equal(h2))
  2157. })
  2158. It("should produce the same hash for the same k/v pairs", func() {
  2159. h1 := hashMeta(metav1.ObjectMeta{
  2160. Generation: 1,
  2161. })
  2162. h2 := hashMeta(metav1.ObjectMeta{
  2163. Generation: 1,
  2164. })
  2165. Expect(h1).To(Equal(h2))
  2166. h1 = hashMeta(metav1.ObjectMeta{
  2167. Generation: 1,
  2168. Annotations: map[string]string{
  2169. "foo": "bar",
  2170. },
  2171. })
  2172. h2 = hashMeta(metav1.ObjectMeta{
  2173. Generation: 1,
  2174. Annotations: map[string]string{
  2175. "foo": "bar",
  2176. },
  2177. })
  2178. Expect(h1).To(Equal(h2))
  2179. })
  2180. })
  2181. })
  2182. var _ = Describe("Controller Reconcile logic", func() {
  2183. Context("controller reconcile", func() {
  2184. It("should reconcile when resource is not synced", func() {
  2185. Expect(shouldReconcile(esv1beta1.ExternalSecret{
  2186. Status: esv1beta1.ExternalSecretStatus{
  2187. SyncedResourceVersion: "some resource version",
  2188. Conditions: []esv1beta1.ExternalSecretStatusCondition{{Reason: "NotASecretSynced"}},
  2189. },
  2190. })).To(BeTrue())
  2191. })
  2192. It("should reconcile when secret isn't immutable", func() {
  2193. Expect(shouldReconcile(esv1beta1.ExternalSecret{
  2194. Spec: esv1beta1.ExternalSecretSpec{
  2195. Target: esv1beta1.ExternalSecretTarget{
  2196. Immutable: false,
  2197. },
  2198. },
  2199. })).To(BeTrue())
  2200. })
  2201. It("should not reconcile if secret is immutable and has synced condition", func() {
  2202. Expect(shouldReconcile(esv1beta1.ExternalSecret{
  2203. Spec: esv1beta1.ExternalSecretSpec{
  2204. Target: esv1beta1.ExternalSecretTarget{
  2205. Immutable: true,
  2206. },
  2207. },
  2208. Status: esv1beta1.ExternalSecretStatus{
  2209. SyncedResourceVersion: "some resource version",
  2210. Conditions: []esv1beta1.ExternalSecretStatusCondition{{Reason: "SecretSynced"}},
  2211. },
  2212. })).To(BeFalse())
  2213. })
  2214. })
  2215. })
  2216. func externalSecretConditionShouldBe(name, ns string, ct esv1beta1.ExternalSecretConditionType, cs v1.ConditionStatus, v float64) bool {
  2217. return Eventually(func() float64 {
  2218. Expect(testExternalSecretCondition.WithLabelValues(name, ns, string(ct), string(cs)).Write(&metric)).To(Succeed())
  2219. return metric.GetGauge().GetValue()
  2220. }, timeout, interval).Should(Equal(v))
  2221. }
  2222. func init() {
  2223. fakeProvider = fake.New()
  2224. esv1beta1.ForceRegister(fakeProvider, &esv1beta1.SecretStoreProvider{
  2225. AWS: &esv1beta1.AWSProvider{
  2226. Service: esv1beta1.AWSServiceSecretsManager,
  2227. },
  2228. })
  2229. ctrlmetrics.SetUpLabelNames(false)
  2230. esmetrics.SetUpMetrics()
  2231. testSyncCallsTotal = esmetrics.GetCounterVec(esmetrics.SyncCallsKey)
  2232. testSyncCallsError = esmetrics.GetCounterVec(esmetrics.SyncCallsErrorKey)
  2233. testExternalSecretCondition = esmetrics.GetGaugeVec(esmetrics.ExternalSecretStatusConditionKey)
  2234. testExternalSecretReconcileDuration = esmetrics.GetGaugeVec(esmetrics.ExternalSecretReconcileDurationKey)
  2235. }