externalsecret_controller_test.go 85 KB

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