externalsecret_controller_test.go 107 KB

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