pushsecret_controller_test.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  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 pushsecret
  13. import (
  14. "context"
  15. "errors"
  16. "fmt"
  17. "time"
  18. "github.com/go-logr/logr"
  19. . "github.com/onsi/ginkgo/v2"
  20. . "github.com/onsi/gomega"
  21. v1 "k8s.io/api/core/v1"
  22. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  23. "k8s.io/apimachinery/pkg/types"
  24. ctrl "sigs.k8s.io/controller-runtime"
  25. kubeclient "sigs.k8s.io/controller-runtime/pkg/client"
  26. esapi "github.com/external-secrets/external-secrets/apis/externalsecrets/v1alpha1"
  27. v1beta1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1beta1"
  28. "github.com/external-secrets/external-secrets/pkg/controllers/pushsecret/internal/fakes"
  29. "github.com/external-secrets/external-secrets/pkg/provider/testing/fake"
  30. )
  31. var fakeProvider *fake.Client
  32. var _ = Describe("pushsecret", func() {
  33. var (
  34. reconciler *Reconciler
  35. client *fakes.Client
  36. recorder *fakes.FakeEventRecorder
  37. )
  38. BeforeEach(func() {
  39. client = new(fakes.Client)
  40. recorder = &fakes.FakeEventRecorder{}
  41. reconciler = &Reconciler{client, logr.Discard(), nil, recorder, time.Minute, ""}
  42. })
  43. Describe("#Reconcile", func() {
  44. var (
  45. statusWriter *fakes.StatusWriter
  46. )
  47. BeforeEach(func() {
  48. statusWriter = new(fakes.StatusWriter)
  49. client.StatusReturns(statusWriter)
  50. })
  51. It("succeeds", func() {
  52. namspacedName := types.NamespacedName{Namespace: "foo", Name: "Bar"}
  53. result, err := reconciler.Reconcile(context.Background(), ctrl.Request{NamespacedName: namspacedName})
  54. Expect(result).To(Equal(ctrl.Result{RequeueAfter: time.Minute}))
  55. Expect(err).NotTo(HaveOccurred())
  56. Expect(client.GetCallCount()).To(Equal(2))
  57. Expect(client.StatusCallCount()).To(Equal(1))
  58. _, gotNamespacedName, _ := client.GetArgsForCall(0)
  59. Expect(gotNamespacedName).To(Equal(namspacedName))
  60. Expect(statusWriter.PatchCallCount()).To(Equal(1))
  61. _, _, patch, _ := statusWriter.PatchArgsForCall(0)
  62. Expect(patch.Type()).To(Equal(types.MergePatchType))
  63. Expect(recorder.EventCallCount()).To(Equal(1))
  64. _, _, reason, message := recorder.EventArgsForCall(0)
  65. Expect(reason).To(Equal(esapi.ReasonSynced))
  66. Expect(message).To(Equal("PushSecret synced successfully"))
  67. })
  68. It("requeues after specified time", func() {
  69. client.GetStub = func(context context.Context, name types.NamespacedName, obj kubeclient.Object) error {
  70. myObj := obj
  71. switch obj.(type) {
  72. case *esapi.PushSecret:
  73. t := myObj.(*esapi.PushSecret)
  74. t.Spec.RefreshInterval = &metav1.Duration{Duration: 0 * time.Second}
  75. return nil
  76. default:
  77. return nil
  78. }
  79. }
  80. namspacedName := types.NamespacedName{Namespace: "foo", Name: "Bar"}
  81. result, err := reconciler.Reconcile(context.Background(), ctrl.Request{NamespacedName: namspacedName})
  82. Expect(result).To(Equal(ctrl.Result{RequeueAfter: 0, Requeue: false}))
  83. Expect(err).NotTo(HaveOccurred())
  84. Expect(client.GetCallCount()).To(Equal(2))
  85. Expect(client.StatusCallCount()).To(Equal(1))
  86. _, gotNamespacedName, _ := client.GetArgsForCall(0)
  87. Expect(gotNamespacedName).To(Equal(namspacedName))
  88. Expect(statusWriter.PatchCallCount()).To(Equal(1))
  89. _, _, patch, _ := statusWriter.PatchArgsForCall(0)
  90. Expect(patch.Type()).To(Equal(types.MergePatchType))
  91. Expect(recorder.EventCallCount()).To(Equal(1))
  92. _, _, reason, message := recorder.EventArgsForCall(0)
  93. Expect(reason).To(Equal(esapi.ReasonSynced))
  94. Expect(message).To(Equal("PushSecret synced successfully"))
  95. })
  96. When("an error returns in get", func() {
  97. BeforeEach(func() {
  98. client.GetReturns(errors.New("UnknownError"))
  99. })
  100. It("returns the error", func() {
  101. namspacedName := types.NamespacedName{Namespace: "foo", Name: "Bar"}
  102. _, err := reconciler.Reconcile(context.Background(), ctrl.Request{NamespacedName: namspacedName})
  103. Expect(err).To(MatchError("get resource: UnknownError"))
  104. Expect(client.GetCallCount()).To(Equal(1))
  105. Expect(client.StatusCallCount()).To(Equal(0))
  106. _, _, reason, message := recorder.EventArgsForCall(0)
  107. Expect(reason).To(Equal(esapi.ReasonErrored))
  108. Expect(message).To(Equal("unable to get PushSecret"))
  109. })
  110. })
  111. When("an error returns in get secret", func() {
  112. BeforeEach(func() {
  113. client.GetStub = func(context context.Context, name types.NamespacedName, obj kubeclient.Object) error {
  114. switch obj.(type) {
  115. case *v1.Secret:
  116. return fmt.Errorf("GetSecretError")
  117. default:
  118. return nil
  119. }
  120. }
  121. })
  122. It("returns the error", func() {
  123. namspacedName := types.NamespacedName{Namespace: "foo", Name: "Bar"}
  124. _, err := reconciler.Reconcile(context.Background(), ctrl.Request{NamespacedName: namspacedName})
  125. Expect(err).To(MatchError("GetSecretError"))
  126. _, _, reason, message := recorder.EventArgsForCall(0)
  127. Expect(reason).To(Equal(esapi.ReasonErrored))
  128. Expect(message).To(Equal(errFailedGetSecret))
  129. })
  130. })
  131. When("an error returns in get secret store", func() {
  132. BeforeEach(func() {
  133. client.GetStub = func(context context.Context, name types.NamespacedName, obj kubeclient.Object) error {
  134. switch v := obj.(type) {
  135. case *esapi.PushSecret:
  136. v.Spec.SecretStoreRefs = []esapi.PushSecretStoreRef{
  137. {Name: "a", Kind: "secretstore"},
  138. }
  139. }
  140. switch obj.(type) {
  141. case *v1beta1.SecretStore:
  142. return fmt.Errorf("BORK")
  143. default:
  144. return nil
  145. }
  146. }
  147. })
  148. It("returns the error", func() {
  149. namspacedName := types.NamespacedName{Namespace: "foo", Name: "Bar"}
  150. _, err := reconciler.Reconcile(context.Background(), ctrl.Request{NamespacedName: namspacedName})
  151. Expect(err).To(MatchError("could not get SecretStore \"a\", BORK"))
  152. _, _, reason, message := recorder.EventArgsForCall(0)
  153. Expect(reason).To(Equal(esapi.ReasonErrored))
  154. Expect(message).To(Equal("could not get SecretStore \"a\", BORK"))
  155. })
  156. })
  157. When("an error returns in set secret to providers", func() {
  158. BeforeEach(func() {
  159. client.GetStub = func(context context.Context, name types.NamespacedName, obj kubeclient.Object) error {
  160. switch v := obj.(type) {
  161. case *esapi.PushSecret:
  162. v.Spec.SecretStoreRefs = []esapi.PushSecretStoreRef{
  163. {Name: "a", Kind: "secretstore"},
  164. }
  165. case *v1beta1.SecretStore:
  166. v.Kind = "PotatoStore"
  167. }
  168. switch obj.(type) {
  169. default:
  170. return nil
  171. }
  172. }
  173. })
  174. It("returns the error", func() {
  175. namspacedName := types.NamespacedName{Namespace: "foo", Name: "Bar"}
  176. _, err := reconciler.Reconcile(context.Background(), ctrl.Request{NamespacedName: namspacedName})
  177. Expect(err).To(MatchError("could not start provider"))
  178. _, _, reason, message := recorder.EventArgsForCall(0)
  179. Expect(reason).To(Equal(esapi.ReasonErrored))
  180. Expect(message).To(Equal("set secret failed: could not start provider"))
  181. })
  182. })
  183. When("an object is not found", func() {
  184. BeforeEach(func() {
  185. client.GetReturns(statusErrorNotFound{})
  186. })
  187. It("returns an empty result without error", func() {
  188. namspacedName := types.NamespacedName{Namespace: "foo", Name: "Bar"}
  189. _, err := reconciler.Reconcile(context.Background(), ctrl.Request{NamespacedName: namspacedName})
  190. Expect(err).NotTo(HaveOccurred())
  191. })
  192. })
  193. })
  194. Describe("#GetPushSecretCondition", func() {
  195. It("returns nil for empty secret sink status", func() {
  196. pushSecretStatus := new(esapi.PushSecretStatus)
  197. pushSecretConditionType := new(esapi.PushSecretConditionType)
  198. Expect(GetPushSecretCondition(*pushSecretStatus, *pushSecretConditionType)).To(BeNil())
  199. })
  200. It("returns correct condition for secret sink status", func() {
  201. pushSecretStatusCondition := esapi.PushSecretStatusCondition{Type: esapi.PushSecretReady}
  202. pushSecretStatus := esapi.PushSecretStatus{Conditions: []esapi.PushSecretStatusCondition{pushSecretStatusCondition}}
  203. pushSecretConditionType := esapi.PushSecretReady
  204. Expect(GetPushSecretCondition(pushSecretStatus, pushSecretConditionType)).To(Equal(&pushSecretStatusCondition))
  205. })
  206. })
  207. Describe("#SetPushSecretCondition", func() {
  208. It("appends a condition", func() {
  209. pushSecret := esapi.PushSecret{}
  210. pushSecretStatusCondition := esapi.PushSecretStatusCondition{}
  211. pushSecretStatus := esapi.PushSecretStatus{Conditions: []esapi.PushSecretStatusCondition{pushSecretStatusCondition}}
  212. expected := esapi.PushSecret{Status: pushSecretStatus}
  213. Expect(SetPushSecretCondition(pushSecret, pushSecretStatusCondition)).To(Equal(expected))
  214. })
  215. It("changes an existing condition", func() {
  216. conditionStatusTrue := v1.ConditionTrue
  217. pushSecretWithCondition := esapi.PushSecret{Status: esapi.PushSecretStatus{Conditions: []esapi.PushSecretStatusCondition{
  218. {
  219. Status: conditionStatusTrue,
  220. Type: esapi.PushSecretReady,
  221. },
  222. }},
  223. }
  224. pushSecretStatusConditionTrue := esapi.PushSecretStatusCondition{Status: conditionStatusTrue,
  225. Type: esapi.PushSecretReady,
  226. Message: "Update status",
  227. }
  228. got := SetPushSecretCondition(pushSecretWithCondition, pushSecretStatusConditionTrue)
  229. Expect(len(got.Status.Conditions)).To(Equal(1))
  230. Expect(got.Status.Conditions[0]).To(Equal(pushSecretStatusConditionTrue))
  231. })
  232. })
  233. Describe("#GetSecret", func() {
  234. It("returns a secret if it exists", func() {
  235. sink := esapi.PushSecret{
  236. Spec: esapi.PushSecretSpec{
  237. Selector: esapi.PushSecretSelector{
  238. Secret: esapi.PushSecretSecret{
  239. Name: "foo",
  240. },
  241. },
  242. },
  243. }
  244. sink.Namespace = "foobar"
  245. _, err := reconciler.GetSecret(context.TODO(), sink)
  246. Expect(err).To(BeNil())
  247. _, name, _ := client.GetArgsForCall(0)
  248. Expect(name.Namespace).To(Equal("foobar"))
  249. Expect(name.Name).To(Equal("foo"))
  250. })
  251. It("returns an error if it doesn't exist", func() {
  252. client.GetReturns(errors.New("secret not found"))
  253. _, err := reconciler.GetSecret(context.TODO(), esapi.PushSecret{})
  254. Expect(err).To(HaveOccurred())
  255. })
  256. })
  257. Describe("#GetSecretStore", func() {
  258. sink := esapi.PushSecret{
  259. Spec: esapi.PushSecretSpec{
  260. SecretStoreRefs: []esapi.PushSecretStoreRef{
  261. {
  262. Name: "foo",
  263. },
  264. },
  265. },
  266. }
  267. sink.Namespace = "bar"
  268. clusterSink := esapi.PushSecret{
  269. Spec: esapi.PushSecretSpec{
  270. SecretStoreRefs: []esapi.PushSecretStoreRef{
  271. {
  272. Name: "foo",
  273. Kind: "ClusterSecretStore",
  274. },
  275. },
  276. },
  277. }
  278. It("returns a secretstore if it exists", func() {
  279. _, err := reconciler.GetSecretStores(context.TODO(), sink)
  280. Expect(err).To(BeNil())
  281. Expect(client.GetCallCount()).To(Equal(1))
  282. _, name, store := client.GetArgsForCall(0)
  283. Expect(name.Namespace).To(Equal("bar"))
  284. Expect(name.Name).To(Equal("foo"))
  285. Expect(store).To(BeAssignableToTypeOf(&v1beta1.SecretStore{}))
  286. })
  287. It("returns an error if it doesn't exist", func() {
  288. client.GetReturns(errors.New("secretstore not found"))
  289. _, err := reconciler.GetSecretStores(context.TODO(), sink)
  290. Expect(err).To(HaveOccurred())
  291. })
  292. It("returns a clustersecretstore if it exists", func() {
  293. _, err := reconciler.GetSecretStores(context.TODO(), clusterSink)
  294. Expect(err).To(BeNil())
  295. Expect(client.GetCallCount()).To(Equal(1))
  296. _, name, store := client.GetArgsForCall(0)
  297. Expect(store).To(BeAssignableToTypeOf(&v1beta1.ClusterSecretStore{}))
  298. Expect(name.Name).To(Equal("foo"))
  299. })
  300. })
  301. Describe("#SetSecretToProviders", func() {
  302. val := "supersecret"
  303. secret := &v1.Secret{
  304. Data: map[string][]byte{
  305. "foo": []byte(val),
  306. },
  307. }
  308. sink := esapi.PushSecret{
  309. Spec: esapi.PushSecretSpec{
  310. SecretStoreRefs: []esapi.PushSecretStoreRef{
  311. {
  312. Name: "foo",
  313. },
  314. },
  315. Data: []esapi.PushSecretData{
  316. {
  317. Match: []esapi.PushSecretMatch{
  318. {
  319. SecretKey: "foo",
  320. RemoteRefs: []esapi.PushSecretRemoteRefs{
  321. {
  322. RemoteKey: "bar",
  323. },
  324. },
  325. },
  326. },
  327. },
  328. },
  329. },
  330. }
  331. sink.Namespace = "bar"
  332. secretStore := v1beta1.SecretStore{}
  333. stores := make([]v1beta1.GenericStore, 0)
  334. stores = append(stores, &secretStore)
  335. It("gets the provider and client and then sets the secret", func() {
  336. Expect(reconciler.SetSecretToProviders(context.TODO(), []v1beta1.GenericStore{}, sink, secret)).To(BeNil())
  337. })
  338. It("returns an error if it can't get a provider", func() {
  339. err := reconciler.SetSecretToProviders(context.TODO(), stores, sink, secret)
  340. Expect(err).To(HaveOccurred())
  341. Expect(err.Error()).To(Equal(errGetProviderFailed))
  342. })
  343. It("returns an if it can't get a client", func() {
  344. specWithProvider := v1beta1.SecretStoreSpec{
  345. Provider: &v1beta1.SecretStoreProvider{
  346. Fake: &v1beta1.FakeProvider{},
  347. },
  348. }
  349. fakeProvider.WithNew(func(context.Context, v1beta1.GenericStore, kubeclient.Client,
  350. string) (v1beta1.SecretsClient, error) {
  351. return nil, fmt.Errorf("Something went wrong")
  352. })
  353. secretStore = v1beta1.SecretStore{
  354. Spec: specWithProvider,
  355. }
  356. stores[0] = &secretStore
  357. err := reconciler.SetSecretToProviders(context.TODO(), stores, sink, secret)
  358. Expect(err).To(HaveOccurred())
  359. Expect(err.Error()).To(Equal(errGetSecretsClientFailed))
  360. })
  361. It("returns an error if set secret fails", func() {
  362. specWithProvider := v1beta1.SecretStoreSpec{
  363. Provider: &v1beta1.SecretStoreProvider{
  364. Fake: &v1beta1.FakeProvider{},
  365. },
  366. }
  367. fakeProvider.Reset()
  368. fakeProvider.WithSetSecret(fmt.Errorf("something went wrong"))
  369. secretStore = v1beta1.SecretStore{
  370. Spec: specWithProvider,
  371. }
  372. stores[0] = &secretStore
  373. err := reconciler.SetSecretToProviders(context.TODO(), stores, sink, secret)
  374. Expect(err).To(HaveOccurred())
  375. Expect(err.Error()).To(Equal(fmt.Sprintf(errSetSecretFailed, "foo", "", "something went wrong")))
  376. })
  377. })
  378. })
  379. func init() {
  380. fakeProvider = fake.New()
  381. v1beta1.ForceRegister(fakeProvider, &v1beta1.SecretStoreProvider{
  382. Fake: &v1beta1.FakeProvider{},
  383. })
  384. }