externalsecret_controller_test.go 114 KB

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