externalsecret_controller_test.go 95 KB

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