externalsecret_controller_test.go 84 KB

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