externalsecret_controller_test.go 95 KB

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