externalsecret_controller_test.go 83 KB

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