pushsecret_controller_test.go 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335
  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. "bytes"
  15. "context"
  16. "fmt"
  17. "os"
  18. "strconv"
  19. "time"
  20. v1 "k8s.io/api/core/v1"
  21. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  22. "k8s.io/apimachinery/pkg/types"
  23. "sigs.k8s.io/controller-runtime/pkg/client"
  24. "github.com/external-secrets/external-secrets/apis/externalsecrets/v1alpha1"
  25. "github.com/external-secrets/external-secrets/apis/externalsecrets/v1beta1"
  26. ctest "github.com/external-secrets/external-secrets/pkg/controllers/commontest"
  27. "github.com/external-secrets/external-secrets/pkg/controllers/pushsecret/psmetrics"
  28. "github.com/external-secrets/external-secrets/pkg/provider/testing/fake"
  29. . "github.com/onsi/ginkgo/v2"
  30. . "github.com/onsi/gomega"
  31. )
  32. var (
  33. fakeProvider *fake.Client
  34. timeout = time.Second * 10
  35. interval = time.Millisecond * 250
  36. )
  37. type testCase struct {
  38. store v1beta1.GenericStore
  39. managedStore1 v1beta1.GenericStore
  40. managedStore2 v1beta1.GenericStore
  41. unmanagedStore1 v1beta1.GenericStore
  42. unmanagedStore2 v1beta1.GenericStore
  43. pushsecret *v1alpha1.PushSecret
  44. secret *v1.Secret
  45. assert func(pushsecret *v1alpha1.PushSecret, secret *v1.Secret) bool
  46. }
  47. func init() {
  48. fakeProvider = fake.New()
  49. v1beta1.ForceRegister(fakeProvider, &v1beta1.SecretStoreProvider{
  50. Fake: &v1beta1.FakeProvider{},
  51. })
  52. psmetrics.SetUpMetrics()
  53. }
  54. func checkCondition(status v1alpha1.PushSecretStatus, cond v1alpha1.PushSecretStatusCondition) bool {
  55. fmt.Printf("status: %+v\ncond: %+v\n", status.Conditions, cond)
  56. for _, condition := range status.Conditions {
  57. if condition.Message == cond.Message &&
  58. condition.Reason == cond.Reason &&
  59. condition.Status == cond.Status &&
  60. condition.Type == cond.Type {
  61. return true
  62. }
  63. }
  64. return false
  65. }
  66. type testTweaks func(*testCase)
  67. var _ = Describe("PushSecret controller", func() {
  68. const (
  69. PushSecretName = "test-ps"
  70. PushSecretStore = "test-store"
  71. SecretName = "test-secret"
  72. )
  73. var PushSecretNamespace string
  74. // if we are in debug and need to increase the timeout for testing, we can do so by using an env var
  75. if customTimeout := os.Getenv("TEST_CUSTOM_TIMEOUT_SEC"); customTimeout != "" {
  76. if t, err := strconv.Atoi(customTimeout); err == nil {
  77. timeout = time.Second * time.Duration(t)
  78. }
  79. }
  80. BeforeEach(func() {
  81. var err error
  82. PushSecretNamespace, err = ctest.CreateNamespace("test-ns", k8sClient)
  83. Expect(err).ToNot(HaveOccurred())
  84. fakeProvider.Reset()
  85. })
  86. AfterEach(func() {
  87. k8sClient.Delete(context.Background(), &v1alpha1.PushSecret{
  88. ObjectMeta: metav1.ObjectMeta{
  89. Name: PushSecretName,
  90. Namespace: PushSecretNamespace,
  91. },
  92. })
  93. // give a time for reconciler to remove finalizers before removing SecretStores
  94. // TODO: Secret Stores should have finalizers bound to PushSecrets if DeletionPolicy == Delete
  95. time.Sleep(2 * time.Second)
  96. k8sClient.Delete(context.Background(), &v1beta1.SecretStore{
  97. ObjectMeta: metav1.ObjectMeta{
  98. Name: PushSecretStore,
  99. Namespace: PushSecretNamespace,
  100. },
  101. })
  102. k8sClient.Delete(context.Background(), &v1beta1.ClusterSecretStore{
  103. ObjectMeta: metav1.ObjectMeta{
  104. Name: PushSecretStore,
  105. },
  106. })
  107. k8sClient.Delete(context.Background(), &v1.Secret{
  108. ObjectMeta: metav1.ObjectMeta{
  109. Name: SecretName,
  110. Namespace: PushSecretNamespace,
  111. },
  112. })
  113. Expect(k8sClient.Delete(context.Background(), &v1.Namespace{
  114. ObjectMeta: metav1.ObjectMeta{
  115. Name: PushSecretNamespace,
  116. },
  117. })).To(Succeed())
  118. })
  119. const (
  120. defaultKey = "key"
  121. defaultVal = "value"
  122. defaultPath = "path/to/key"
  123. otherKey = "other-key"
  124. otherVal = "other-value"
  125. otherPath = "path/to/other-key"
  126. newKey = "new-key"
  127. newVal = "new-value"
  128. storePrefixTemplate = "SecretStore/%v"
  129. )
  130. makeDefaultTestcase := func() *testCase {
  131. return &testCase{
  132. pushsecret: &v1alpha1.PushSecret{
  133. ObjectMeta: metav1.ObjectMeta{
  134. Name: PushSecretName,
  135. Namespace: PushSecretNamespace,
  136. },
  137. Spec: v1alpha1.PushSecretSpec{
  138. SecretStoreRefs: []v1alpha1.PushSecretStoreRef{
  139. {
  140. Name: PushSecretStore,
  141. Kind: "SecretStore",
  142. },
  143. },
  144. Selector: v1alpha1.PushSecretSelector{
  145. Secret: v1alpha1.PushSecretSecret{
  146. Name: SecretName,
  147. },
  148. },
  149. Data: []v1alpha1.PushSecretData{
  150. {
  151. Match: v1alpha1.PushSecretMatch{
  152. SecretKey: defaultKey,
  153. RemoteRef: v1alpha1.PushSecretRemoteRef{
  154. RemoteKey: defaultPath,
  155. },
  156. },
  157. },
  158. },
  159. },
  160. },
  161. secret: &v1.Secret{
  162. ObjectMeta: metav1.ObjectMeta{
  163. Name: SecretName,
  164. Namespace: PushSecretNamespace,
  165. },
  166. Data: map[string][]byte{
  167. defaultKey: []byte(defaultVal),
  168. },
  169. },
  170. store: &v1beta1.SecretStore{
  171. ObjectMeta: metav1.ObjectMeta{
  172. Name: PushSecretStore,
  173. Namespace: PushSecretNamespace,
  174. },
  175. TypeMeta: metav1.TypeMeta{
  176. Kind: "SecretStore",
  177. },
  178. Spec: v1beta1.SecretStoreSpec{
  179. Provider: &v1beta1.SecretStoreProvider{
  180. Fake: &v1beta1.FakeProvider{
  181. Data: []v1beta1.FakeProviderData{},
  182. },
  183. },
  184. },
  185. },
  186. }
  187. }
  188. // if target Secret name is not specified it should use the ExternalSecret name.
  189. syncSuccessfully := func(tc *testCase) {
  190. fakeProvider.SetSecretFn = func() error {
  191. return nil
  192. }
  193. tc.assert = func(ps *v1alpha1.PushSecret, secret *v1.Secret) bool {
  194. Eventually(func() bool {
  195. By("checking if Provider value got updated")
  196. secretValue := secret.Data[defaultKey]
  197. providerValue, ok := fakeProvider.SetSecretArgs[ps.Spec.Data[0].Match.RemoteRef.RemoteKey]
  198. if !ok {
  199. return false
  200. }
  201. got := providerValue.Value
  202. return bytes.Equal(got, secretValue)
  203. }, time.Second*10, time.Second).Should(BeTrue())
  204. return true
  205. }
  206. }
  207. updateIfNotExists := func(tc *testCase) {
  208. fakeProvider.SetSecretFn = func() error {
  209. return nil
  210. }
  211. fakeProvider.SecretExistsFn = func(ctx context.Context, ref v1beta1.PushSecretRemoteRef) (bool, error) {
  212. _, ok := fakeProvider.SetSecretArgs[ref.GetRemoteKey()]
  213. return ok, nil
  214. }
  215. tc.pushsecret.Spec.UpdatePolicy = v1alpha1.PushSecretUpdatePolicyIfNotExists
  216. initialValue := fakeProvider.SetSecretArgs[tc.pushsecret.Spec.Data[0].Match.RemoteRef.RemoteKey].Value
  217. tc.secret.Data[defaultKey] = []byte(newVal)
  218. tc.assert = func(ps *v1alpha1.PushSecret, secret *v1.Secret) bool {
  219. Eventually(func() bool {
  220. By("checking if Provider value did not get updated")
  221. Expect(k8sClient.Update(context.Background(), secret, &client.UpdateOptions{})).Should(Succeed())
  222. providerValue, ok := fakeProvider.SetSecretArgs[ps.Spec.Data[0].Match.RemoteRef.RemoteKey]
  223. if !ok {
  224. return false
  225. }
  226. got := providerValue.Value
  227. return bytes.Equal(got, initialValue)
  228. }, time.Second*10, time.Second).Should(BeTrue())
  229. return true
  230. }
  231. }
  232. updateIfNotExistsPartialSecrets := func(tc *testCase) {
  233. fakeProvider.SetSecretFn = func() error {
  234. return nil
  235. }
  236. fakeProvider.SecretExistsFn = func(ctx context.Context, ref v1beta1.PushSecretRemoteRef) (bool, error) {
  237. _, ok := fakeProvider.SetSecretArgs[ref.GetRemoteKey()]
  238. return ok, nil
  239. }
  240. tc.pushsecret.Spec.UpdatePolicy = v1alpha1.PushSecretUpdatePolicyIfNotExists
  241. tc.pushsecret.Spec.Data = append(tc.pushsecret.Spec.Data, v1alpha1.PushSecretData{
  242. Match: v1alpha1.PushSecretMatch{
  243. SecretKey: otherKey,
  244. RemoteRef: v1alpha1.PushSecretRemoteRef{
  245. RemoteKey: otherPath,
  246. },
  247. },
  248. })
  249. initialValue := fakeProvider.SetSecretArgs[tc.pushsecret.Spec.Data[0].Match.RemoteRef.RemoteKey].Value
  250. tc.secret.Data[defaultKey] = []byte(newVal) // change initial value in secret
  251. tc.secret.Data[otherKey] = []byte(otherVal)
  252. tc.assert = func(ps *v1alpha1.PushSecret, secret *v1.Secret) bool {
  253. Eventually(func() bool {
  254. By("checking if only not existing Provider value got updated")
  255. Expect(k8sClient.Update(context.Background(), secret, &client.UpdateOptions{})).Should(Succeed())
  256. providerValue, ok := fakeProvider.SetSecretArgs[ps.Spec.Data[0].Match.RemoteRef.RemoteKey]
  257. if !ok {
  258. return false
  259. }
  260. got := providerValue.Value
  261. otherProviderValue, ok := fakeProvider.SetSecretArgs[ps.Spec.Data[1].Match.RemoteRef.RemoteKey]
  262. if !ok {
  263. return false
  264. }
  265. gotOther := otherProviderValue.Value
  266. return bytes.Equal(gotOther, tc.secret.Data[otherKey]) && bytes.Equal(got, initialValue)
  267. }, time.Second*10, time.Second).Should(BeTrue())
  268. return true
  269. }
  270. }
  271. updateIfNotExistsSyncStatus := func(tc *testCase) {
  272. fakeProvider.SetSecretFn = func() error {
  273. return nil
  274. }
  275. fakeProvider.SecretExistsFn = func(ctx context.Context, ref v1beta1.PushSecretRemoteRef) (bool, error) {
  276. _, ok := fakeProvider.SetSecretArgs[ref.GetRemoteKey()]
  277. return ok, nil
  278. }
  279. tc.pushsecret.Spec.UpdatePolicy = v1alpha1.PushSecretUpdatePolicyIfNotExists
  280. tc.pushsecret.Spec.Data = append(tc.pushsecret.Spec.Data, v1alpha1.PushSecretData{
  281. Match: v1alpha1.PushSecretMatch{
  282. SecretKey: otherKey,
  283. RemoteRef: v1alpha1.PushSecretRemoteRef{
  284. RemoteKey: otherPath,
  285. },
  286. },
  287. })
  288. tc.secret.Data[defaultKey] = []byte(newVal)
  289. tc.secret.Data[otherKey] = []byte(otherVal)
  290. updatedPS := &v1alpha1.PushSecret{}
  291. tc.assert = func(ps *v1alpha1.PushSecret, secret *v1.Secret) bool {
  292. Eventually(func() bool {
  293. By("checking if PushSecret status gets updated correctly with UpdatePolicy=IfNotExists")
  294. Expect(k8sClient.Update(context.Background(), secret, &client.UpdateOptions{})).Should(Succeed())
  295. psKey := types.NamespacedName{Name: PushSecretName, Namespace: PushSecretNamespace}
  296. err := k8sClient.Get(context.Background(), psKey, updatedPS)
  297. if err != nil {
  298. return false
  299. }
  300. _, ok := updatedPS.Status.SyncedPushSecrets[fmt.Sprintf(storePrefixTemplate, PushSecretStore)][defaultPath]
  301. if !ok {
  302. return false
  303. }
  304. _, ok = updatedPS.Status.SyncedPushSecrets[fmt.Sprintf(storePrefixTemplate, PushSecretStore)][otherPath]
  305. if !ok {
  306. return false
  307. }
  308. expected := v1alpha1.PushSecretStatusCondition{
  309. Type: v1alpha1.PushSecretReady,
  310. Status: v1.ConditionTrue,
  311. Reason: v1alpha1.ReasonSynced,
  312. Message: "PushSecret synced successfully. Existing secrets in providers unchanged.",
  313. }
  314. return checkCondition(ps.Status, expected)
  315. }, time.Second*10, time.Second).Should(BeTrue())
  316. return true
  317. }
  318. }
  319. updateIfNotExistsSyncFailed := func(tc *testCase) {
  320. fakeProvider.SetSecretFn = func() error {
  321. return nil
  322. }
  323. fakeProvider.SecretExistsFn = func(ctx context.Context, ref v1beta1.PushSecretRemoteRef) (bool, error) {
  324. return false, fmt.Errorf("don't know")
  325. }
  326. tc.pushsecret.Spec.UpdatePolicy = v1alpha1.PushSecretUpdatePolicyIfNotExists
  327. initialValue := fakeProvider.SetSecretArgs[tc.pushsecret.Spec.Data[0].Match.RemoteRef.RemoteKey].Value
  328. tc.secret.Data[defaultKey] = []byte(newVal)
  329. tc.assert = func(ps *v1alpha1.PushSecret, secret *v1.Secret) bool {
  330. Eventually(func() bool {
  331. By("checking if sync failed if secret existence cannot be verified in Provider")
  332. providerValue, ok := fakeProvider.SetSecretArgs[ps.Spec.Data[0].Match.RemoteRef.RemoteKey]
  333. if !ok {
  334. return false
  335. }
  336. got := providerValue.Value
  337. expected := v1alpha1.PushSecretStatusCondition{
  338. Type: v1alpha1.PushSecretReady,
  339. Status: v1.ConditionFalse,
  340. Reason: v1alpha1.ReasonErrored,
  341. Message: "set secret failed: could not verify if secret exists in store: don't know",
  342. }
  343. return checkCondition(ps.Status, expected) && bytes.Equal(got, initialValue)
  344. }, time.Second*10, time.Second).Should(BeTrue())
  345. return true
  346. }
  347. }
  348. // if target Secret name is not specified it should use the ExternalSecret name.
  349. syncSuccessfullyWithTemplate := func(tc *testCase) {
  350. fakeProvider.SetSecretFn = func() error {
  351. return nil
  352. }
  353. tc.pushsecret = &v1alpha1.PushSecret{
  354. ObjectMeta: metav1.ObjectMeta{
  355. Name: PushSecretName,
  356. Namespace: PushSecretNamespace,
  357. },
  358. Spec: v1alpha1.PushSecretSpec{
  359. SecretStoreRefs: []v1alpha1.PushSecretStoreRef{
  360. {
  361. Name: PushSecretStore,
  362. Kind: "SecretStore",
  363. },
  364. },
  365. Selector: v1alpha1.PushSecretSelector{
  366. Secret: v1alpha1.PushSecretSecret{
  367. Name: SecretName,
  368. },
  369. },
  370. Data: []v1alpha1.PushSecretData{
  371. {
  372. Match: v1alpha1.PushSecretMatch{
  373. SecretKey: defaultKey,
  374. RemoteRef: v1alpha1.PushSecretRemoteRef{
  375. RemoteKey: defaultPath,
  376. },
  377. },
  378. },
  379. },
  380. Template: &v1beta1.ExternalSecretTemplate{
  381. Metadata: v1beta1.ExternalSecretTemplateMetadata{
  382. Labels: map[string]string{
  383. "foos": "ball",
  384. },
  385. Annotations: map[string]string{
  386. "hihi": "ga",
  387. },
  388. },
  389. Type: v1.SecretTypeOpaque,
  390. EngineVersion: v1beta1.TemplateEngineV2,
  391. Data: map[string]string{
  392. defaultKey: "{{ .key | toString | upper }} was templated",
  393. },
  394. },
  395. },
  396. }
  397. tc.assert = func(ps *v1alpha1.PushSecret, secret *v1.Secret) bool {
  398. Eventually(func() bool {
  399. By("checking if Provider value got updated")
  400. providerValue, ok := fakeProvider.SetSecretArgs[ps.Spec.Data[0].Match.RemoteRef.RemoteKey]
  401. if !ok {
  402. return false
  403. }
  404. got := providerValue.Value
  405. return bytes.Equal(got, []byte("VALUE was templated"))
  406. }, time.Second*10, time.Second).Should(BeTrue())
  407. return true
  408. }
  409. }
  410. // if target Secret name is not specified it should use the ExternalSecret name.
  411. syncAndDeleteSuccessfully := func(tc *testCase) {
  412. fakeProvider.SetSecretFn = func() error {
  413. return nil
  414. }
  415. tc.pushsecret = &v1alpha1.PushSecret{
  416. ObjectMeta: metav1.ObjectMeta{
  417. Name: PushSecretName,
  418. Namespace: PushSecretNamespace,
  419. },
  420. Spec: v1alpha1.PushSecretSpec{
  421. DeletionPolicy: v1alpha1.PushSecretDeletionPolicyDelete,
  422. SecretStoreRefs: []v1alpha1.PushSecretStoreRef{
  423. {
  424. Name: PushSecretStore,
  425. Kind: "SecretStore",
  426. },
  427. },
  428. Selector: v1alpha1.PushSecretSelector{
  429. Secret: v1alpha1.PushSecretSecret{
  430. Name: SecretName,
  431. },
  432. },
  433. Data: []v1alpha1.PushSecretData{
  434. {
  435. Match: v1alpha1.PushSecretMatch{
  436. SecretKey: defaultKey,
  437. RemoteRef: v1alpha1.PushSecretRemoteRef{
  438. RemoteKey: defaultPath,
  439. },
  440. },
  441. },
  442. },
  443. },
  444. }
  445. tc.assert = func(ps *v1alpha1.PushSecret, secret *v1.Secret) bool {
  446. ps.Spec.Data[0].Match.RemoteRef.RemoteKey = newKey
  447. updatedPS := &v1alpha1.PushSecret{}
  448. Expect(k8sClient.Update(context.Background(), ps, &client.UpdateOptions{})).Should(Succeed())
  449. Eventually(func() bool {
  450. psKey := types.NamespacedName{Name: PushSecretName, Namespace: PushSecretNamespace}
  451. By("checking if Provider value got updated")
  452. err := k8sClient.Get(context.Background(), psKey, updatedPS)
  453. if err != nil {
  454. return false
  455. }
  456. key, ok := updatedPS.Status.SyncedPushSecrets[fmt.Sprintf(storePrefixTemplate, PushSecretStore)][newKey]
  457. if !ok {
  458. return false
  459. }
  460. return key.Match.SecretKey == defaultKey
  461. }, time.Second*10, time.Second).Should(BeTrue())
  462. return true
  463. }
  464. }
  465. failDelete := func(tc *testCase) {
  466. fakeProvider.SetSecretFn = func() error {
  467. return nil
  468. }
  469. fakeProvider.DeleteSecretFn = func() error {
  470. return fmt.Errorf("Nope")
  471. }
  472. tc.pushsecret = &v1alpha1.PushSecret{
  473. ObjectMeta: metav1.ObjectMeta{
  474. Name: PushSecretName,
  475. Namespace: PushSecretNamespace,
  476. },
  477. Spec: v1alpha1.PushSecretSpec{
  478. DeletionPolicy: v1alpha1.PushSecretDeletionPolicyDelete,
  479. SecretStoreRefs: []v1alpha1.PushSecretStoreRef{
  480. {
  481. Name: PushSecretStore,
  482. Kind: "SecretStore",
  483. },
  484. },
  485. Selector: v1alpha1.PushSecretSelector{
  486. Secret: v1alpha1.PushSecretSecret{
  487. Name: SecretName,
  488. },
  489. },
  490. Data: []v1alpha1.PushSecretData{
  491. {
  492. Match: v1alpha1.PushSecretMatch{
  493. SecretKey: defaultKey,
  494. RemoteRef: v1alpha1.PushSecretRemoteRef{
  495. RemoteKey: defaultPath,
  496. },
  497. },
  498. },
  499. },
  500. },
  501. }
  502. tc.assert = func(ps *v1alpha1.PushSecret, secret *v1.Secret) bool {
  503. ps.Spec.Data[0].Match.RemoteRef.RemoteKey = newKey
  504. updatedPS := &v1alpha1.PushSecret{}
  505. Expect(k8sClient.Update(context.Background(), ps, &client.UpdateOptions{})).Should(Succeed())
  506. Eventually(func() bool {
  507. psKey := types.NamespacedName{Name: PushSecretName, Namespace: PushSecretNamespace}
  508. By("checking if synced secrets correspond to both keys")
  509. err := k8sClient.Get(context.Background(), psKey, updatedPS)
  510. if err != nil {
  511. return false
  512. }
  513. _, ok := updatedPS.Status.SyncedPushSecrets[fmt.Sprintf(storePrefixTemplate, PushSecretStore)][newKey]
  514. if !ok {
  515. return false
  516. }
  517. _, ok = updatedPS.Status.SyncedPushSecrets[fmt.Sprintf(storePrefixTemplate, PushSecretStore)][defaultPath]
  518. return ok
  519. }, time.Second*10, time.Second).Should(BeTrue())
  520. return true
  521. }
  522. }
  523. failDeleteStore := func(tc *testCase) {
  524. fakeProvider.SetSecretFn = func() error {
  525. return nil
  526. }
  527. fakeProvider.DeleteSecretFn = func() error {
  528. return fmt.Errorf("boom")
  529. }
  530. tc.pushsecret.Spec.DeletionPolicy = v1alpha1.PushSecretDeletionPolicyDelete
  531. tc.assert = func(ps *v1alpha1.PushSecret, secret *v1.Secret) bool {
  532. secondStore := &v1beta1.SecretStore{
  533. ObjectMeta: metav1.ObjectMeta{
  534. Name: "new-store",
  535. Namespace: PushSecretNamespace,
  536. },
  537. TypeMeta: metav1.TypeMeta{
  538. Kind: "SecretStore",
  539. },
  540. Spec: v1beta1.SecretStoreSpec{
  541. Provider: &v1beta1.SecretStoreProvider{
  542. Fake: &v1beta1.FakeProvider{
  543. Data: []v1beta1.FakeProviderData{},
  544. },
  545. },
  546. },
  547. }
  548. Expect(k8sClient.Create(context.Background(), secondStore, &client.CreateOptions{})).Should(Succeed())
  549. ps.Spec.SecretStoreRefs[0].Name = "new-store"
  550. updatedPS := &v1alpha1.PushSecret{}
  551. Expect(k8sClient.Update(context.Background(), ps, &client.UpdateOptions{})).Should(Succeed())
  552. Eventually(func() bool {
  553. psKey := types.NamespacedName{Name: PushSecretName, Namespace: PushSecretNamespace}
  554. By("checking if Provider value got updated")
  555. err := k8sClient.Get(context.Background(), psKey, updatedPS)
  556. if err != nil {
  557. return false
  558. }
  559. syncedLen := len(updatedPS.Status.SyncedPushSecrets)
  560. return syncedLen == 2
  561. }, time.Second*10, time.Second).Should(BeTrue())
  562. return true
  563. }
  564. }
  565. deleteWholeStore := func(tc *testCase) {
  566. fakeProvider.SetSecretFn = func() error {
  567. return nil
  568. }
  569. fakeProvider.DeleteSecretFn = func() error {
  570. return nil
  571. }
  572. tc.pushsecret.Spec.DeletionPolicy = v1alpha1.PushSecretDeletionPolicyDelete
  573. tc.assert = func(ps *v1alpha1.PushSecret, secret *v1.Secret) bool {
  574. secondStore := &v1beta1.SecretStore{
  575. ObjectMeta: metav1.ObjectMeta{
  576. Name: "new-store",
  577. Namespace: PushSecretNamespace,
  578. },
  579. TypeMeta: metav1.TypeMeta{
  580. Kind: "SecretStore",
  581. },
  582. Spec: v1beta1.SecretStoreSpec{
  583. Provider: &v1beta1.SecretStoreProvider{
  584. Fake: &v1beta1.FakeProvider{
  585. Data: []v1beta1.FakeProviderData{},
  586. },
  587. },
  588. },
  589. }
  590. Expect(k8sClient.Create(context.Background(), secondStore, &client.CreateOptions{})).Should(Succeed())
  591. ps.Spec.SecretStoreRefs[0].Name = "new-store"
  592. updatedPS := &v1alpha1.PushSecret{}
  593. Expect(k8sClient.Update(context.Background(), ps, &client.UpdateOptions{})).Should(Succeed())
  594. Eventually(func() bool {
  595. psKey := types.NamespacedName{Name: PushSecretName, Namespace: PushSecretNamespace}
  596. By("checking if Provider value got updated")
  597. err := k8sClient.Get(context.Background(), psKey, updatedPS)
  598. if err != nil {
  599. return false
  600. }
  601. key, ok := updatedPS.Status.SyncedPushSecrets["SecretStore/new-store"][defaultPath]
  602. if !ok {
  603. return false
  604. }
  605. syncedLen := len(updatedPS.Status.SyncedPushSecrets)
  606. if syncedLen != 1 {
  607. return false
  608. }
  609. return key.Match.SecretKey == defaultKey
  610. }, time.Second*10, time.Second).Should(BeTrue())
  611. return true
  612. }
  613. }
  614. // if conversion strategy is defined, revert the keys based on the strategy.
  615. syncSuccessfullyWithConversionStrategy := func(tc *testCase) {
  616. fakeProvider.SetSecretFn = func() error {
  617. return nil
  618. }
  619. tc.pushsecret = &v1alpha1.PushSecret{
  620. ObjectMeta: metav1.ObjectMeta{
  621. Name: PushSecretName,
  622. Namespace: PushSecretNamespace,
  623. },
  624. Spec: v1alpha1.PushSecretSpec{
  625. SecretStoreRefs: []v1alpha1.PushSecretStoreRef{
  626. {
  627. Name: PushSecretStore,
  628. Kind: "SecretStore",
  629. },
  630. },
  631. Selector: v1alpha1.PushSecretSelector{
  632. Secret: v1alpha1.PushSecretSecret{
  633. Name: SecretName,
  634. },
  635. },
  636. Data: []v1alpha1.PushSecretData{
  637. {
  638. ConversionStrategy: v1alpha1.PushSecretConversionReverseUnicode,
  639. Match: v1alpha1.PushSecretMatch{
  640. SecretKey: "some-array[0].entity",
  641. RemoteRef: v1alpha1.PushSecretRemoteRef{
  642. RemoteKey: "path/to/key",
  643. },
  644. },
  645. },
  646. },
  647. },
  648. }
  649. tc.secret = &v1.Secret{
  650. ObjectMeta: metav1.ObjectMeta{
  651. Name: SecretName,
  652. Namespace: PushSecretNamespace,
  653. },
  654. Data: map[string][]byte{
  655. "some-array_U005b_0_U005d_.entity": []byte("value"),
  656. },
  657. }
  658. tc.assert = func(ps *v1alpha1.PushSecret, secret *v1.Secret) bool {
  659. Eventually(func() bool {
  660. By("checking if Provider value got updated")
  661. secretValue := secret.Data["some-array_U005b_0_U005d_.entity"]
  662. providerValue, ok := fakeProvider.SetSecretArgs[ps.Spec.Data[0].Match.RemoteRef.RemoteKey]
  663. if !ok {
  664. return false
  665. }
  666. got := providerValue.Value
  667. return bytes.Equal(got, secretValue)
  668. }, time.Second*10, time.Second).Should(BeTrue())
  669. return true
  670. }
  671. }
  672. // if target Secret name is not specified it should use the ExternalSecret name.
  673. syncMatchingLabels := func(tc *testCase) {
  674. fakeProvider.SetSecretFn = func() error {
  675. return nil
  676. }
  677. fakeProvider.DeleteSecretFn = func() error {
  678. return nil
  679. }
  680. tc.pushsecret = &v1alpha1.PushSecret{
  681. ObjectMeta: metav1.ObjectMeta{
  682. Name: PushSecretName,
  683. Namespace: PushSecretNamespace,
  684. },
  685. Spec: v1alpha1.PushSecretSpec{
  686. SecretStoreRefs: []v1alpha1.PushSecretStoreRef{
  687. {
  688. LabelSelector: &metav1.LabelSelector{
  689. MatchLabels: map[string]string{
  690. "foo": "bar",
  691. },
  692. },
  693. Kind: "SecretStore",
  694. Name: PushSecretStore,
  695. },
  696. },
  697. Selector: v1alpha1.PushSecretSelector{
  698. Secret: v1alpha1.PushSecretSecret{
  699. Name: SecretName,
  700. },
  701. },
  702. Data: []v1alpha1.PushSecretData{
  703. {
  704. Match: v1alpha1.PushSecretMatch{
  705. SecretKey: defaultKey,
  706. RemoteRef: v1alpha1.PushSecretRemoteRef{
  707. RemoteKey: defaultPath,
  708. },
  709. },
  710. },
  711. },
  712. },
  713. }
  714. tc.store = &v1beta1.SecretStore{
  715. TypeMeta: metav1.TypeMeta{
  716. Kind: "SecretStore",
  717. },
  718. ObjectMeta: metav1.ObjectMeta{
  719. Name: PushSecretStore,
  720. Namespace: PushSecretNamespace,
  721. Labels: map[string]string{
  722. "foo": "bar",
  723. },
  724. },
  725. Spec: v1beta1.SecretStoreSpec{
  726. Provider: &v1beta1.SecretStoreProvider{
  727. Fake: &v1beta1.FakeProvider{
  728. Data: []v1beta1.FakeProviderData{},
  729. },
  730. },
  731. },
  732. }
  733. tc.assert = func(ps *v1alpha1.PushSecret, secret *v1.Secret) bool {
  734. secretValue := secret.Data[defaultKey]
  735. providerValue := fakeProvider.SetSecretArgs[ps.Spec.Data[0].Match.RemoteRef.RemoteKey].Value
  736. expected := v1alpha1.PushSecretStatusCondition{
  737. Type: v1alpha1.PushSecretReady,
  738. Status: v1.ConditionTrue,
  739. Reason: v1alpha1.ReasonSynced,
  740. Message: "PushSecret synced successfully",
  741. }
  742. return bytes.Equal(secretValue, providerValue) && checkCondition(ps.Status, expected)
  743. }
  744. }
  745. syncWithClusterStore := func(tc *testCase) {
  746. fakeProvider.SetSecretFn = func() error {
  747. return nil
  748. }
  749. tc.store = &v1beta1.ClusterSecretStore{
  750. TypeMeta: metav1.TypeMeta{
  751. Kind: "ClusterSecretStore",
  752. },
  753. ObjectMeta: metav1.ObjectMeta{
  754. Name: PushSecretStore,
  755. },
  756. Spec: v1beta1.SecretStoreSpec{
  757. Provider: &v1beta1.SecretStoreProvider{
  758. Fake: &v1beta1.FakeProvider{
  759. Data: []v1beta1.FakeProviderData{},
  760. },
  761. },
  762. },
  763. }
  764. tc.pushsecret.Spec.SecretStoreRefs[0].Kind = "ClusterSecretStore"
  765. tc.assert = func(ps *v1alpha1.PushSecret, secret *v1.Secret) bool {
  766. secretValue := secret.Data[defaultKey]
  767. providerValue := fakeProvider.SetSecretArgs[ps.Spec.Data[0].Match.RemoteRef.RemoteKey].Value
  768. expected := v1alpha1.PushSecretStatusCondition{
  769. Type: v1alpha1.PushSecretReady,
  770. Status: v1.ConditionTrue,
  771. Reason: v1alpha1.ReasonSynced,
  772. Message: "PushSecret synced successfully",
  773. }
  774. return bytes.Equal(secretValue, providerValue) && checkCondition(ps.Status, expected)
  775. }
  776. }
  777. // if target Secret name is not specified it should use the ExternalSecret name.
  778. syncWithClusterStoreMatchingLabels := func(tc *testCase) {
  779. fakeProvider.SetSecretFn = func() error {
  780. return nil
  781. }
  782. tc.pushsecret = &v1alpha1.PushSecret{
  783. ObjectMeta: metav1.ObjectMeta{
  784. Name: PushSecretName,
  785. Namespace: PushSecretNamespace,
  786. },
  787. Spec: v1alpha1.PushSecretSpec{
  788. SecretStoreRefs: []v1alpha1.PushSecretStoreRef{
  789. {
  790. LabelSelector: &metav1.LabelSelector{
  791. MatchLabels: map[string]string{
  792. "foo": "bar",
  793. },
  794. },
  795. Kind: "ClusterSecretStore",
  796. Name: PushSecretStore,
  797. },
  798. },
  799. Selector: v1alpha1.PushSecretSelector{
  800. Secret: v1alpha1.PushSecretSecret{
  801. Name: SecretName,
  802. },
  803. },
  804. Data: []v1alpha1.PushSecretData{
  805. {
  806. Match: v1alpha1.PushSecretMatch{
  807. SecretKey: defaultKey,
  808. RemoteRef: v1alpha1.PushSecretRemoteRef{
  809. RemoteKey: defaultPath,
  810. },
  811. },
  812. },
  813. },
  814. },
  815. }
  816. tc.store = &v1beta1.ClusterSecretStore{
  817. ObjectMeta: metav1.ObjectMeta{
  818. Name: PushSecretStore,
  819. Labels: map[string]string{
  820. "foo": "bar",
  821. },
  822. },
  823. Spec: v1beta1.SecretStoreSpec{
  824. Provider: &v1beta1.SecretStoreProvider{
  825. Fake: &v1beta1.FakeProvider{
  826. Data: []v1beta1.FakeProviderData{},
  827. },
  828. },
  829. },
  830. }
  831. tc.assert = func(ps *v1alpha1.PushSecret, secret *v1.Secret) bool {
  832. secretValue := secret.Data[defaultKey]
  833. providerValue := fakeProvider.SetSecretArgs[ps.Spec.Data[0].Match.RemoteRef.RemoteKey].Value
  834. expected := v1alpha1.PushSecretStatusCondition{
  835. Type: v1alpha1.PushSecretReady,
  836. Status: v1.ConditionTrue,
  837. Reason: v1alpha1.ReasonSynced,
  838. Message: "PushSecret synced successfully",
  839. }
  840. return bytes.Equal(secretValue, providerValue) && checkCondition(ps.Status, expected)
  841. }
  842. }
  843. // if target Secret name is not specified it should use the ExternalSecret name.
  844. failNoSecret := func(tc *testCase) {
  845. fakeProvider.SetSecretFn = func() error {
  846. return nil
  847. }
  848. tc.secret = nil
  849. tc.assert = func(ps *v1alpha1.PushSecret, secret *v1.Secret) bool {
  850. expected := v1alpha1.PushSecretStatusCondition{
  851. Type: v1alpha1.PushSecretReady,
  852. Status: v1.ConditionFalse,
  853. Reason: v1alpha1.ReasonErrored,
  854. Message: "could not get source secret",
  855. }
  856. return checkCondition(ps.Status, expected)
  857. }
  858. }
  859. // if target Secret name is not specified it should use the ExternalSecret name.
  860. failNoSecretKey := func(tc *testCase) {
  861. fakeProvider.SetSecretFn = func() error {
  862. return nil
  863. }
  864. tc.pushsecret.Spec.Data[0].Match.SecretKey = "unexisting"
  865. tc.assert = func(ps *v1alpha1.PushSecret, secret *v1.Secret) bool {
  866. expected := v1alpha1.PushSecretStatusCondition{
  867. Type: v1alpha1.PushSecretReady,
  868. Status: v1.ConditionFalse,
  869. Reason: v1alpha1.ReasonErrored,
  870. Message: "set secret failed: secret key unexisting does not exist",
  871. }
  872. return checkCondition(ps.Status, expected)
  873. }
  874. }
  875. // if target Secret name is not specified it should use the ExternalSecret name.
  876. failNoSecretStore := func(tc *testCase) {
  877. fakeProvider.SetSecretFn = func() error {
  878. return nil
  879. }
  880. tc.store = nil
  881. tc.assert = func(ps *v1alpha1.PushSecret, secret *v1.Secret) bool {
  882. expected := v1alpha1.PushSecretStatusCondition{
  883. Type: v1alpha1.PushSecretReady,
  884. Status: v1.ConditionFalse,
  885. Reason: v1alpha1.ReasonErrored,
  886. Message: "could not get SecretStore \"test-store\", secretstores.external-secrets.io \"test-store\" not found",
  887. }
  888. return checkCondition(ps.Status, expected)
  889. }
  890. }
  891. // if target Secret name is not specified it should use the ExternalSecret name.
  892. failNoClusterStore := func(tc *testCase) {
  893. fakeProvider.SetSecretFn = func() error {
  894. return nil
  895. }
  896. tc.store = nil
  897. tc.pushsecret.Spec.SecretStoreRefs[0].Kind = "ClusterSecretStore"
  898. tc.pushsecret.Spec.SecretStoreRefs[0].Name = "unexisting"
  899. tc.assert = func(ps *v1alpha1.PushSecret, secret *v1.Secret) bool {
  900. expected := v1alpha1.PushSecretStatusCondition{
  901. Type: v1alpha1.PushSecretReady,
  902. Status: v1.ConditionFalse,
  903. Reason: v1alpha1.ReasonErrored,
  904. Message: "could not get ClusterSecretStore \"unexisting\", clustersecretstores.external-secrets.io \"unexisting\" not found",
  905. }
  906. return checkCondition(ps.Status, expected)
  907. }
  908. }
  909. // if target Secret name is not specified it should use the ExternalSecret name.
  910. setSecretFail := func(tc *testCase) {
  911. fakeProvider.SetSecretFn = func() error {
  912. return fmt.Errorf("boom")
  913. }
  914. tc.assert = func(ps *v1alpha1.PushSecret, secret *v1.Secret) bool {
  915. expected := v1alpha1.PushSecretStatusCondition{
  916. Type: v1alpha1.PushSecretReady,
  917. Status: v1.ConditionFalse,
  918. Reason: v1alpha1.ReasonErrored,
  919. Message: "set secret failed: could not write remote ref key to target secretstore test-store: boom",
  920. }
  921. return checkCondition(ps.Status, expected)
  922. }
  923. }
  924. // if target Secret name is not specified it should use the ExternalSecret name.
  925. newClientFail := func(tc *testCase) {
  926. fakeProvider.NewFn = func(context.Context, v1beta1.GenericStore, client.Client, string) (v1beta1.SecretsClient, error) {
  927. return nil, fmt.Errorf("boom")
  928. }
  929. tc.assert = func(ps *v1alpha1.PushSecret, secret *v1.Secret) bool {
  930. expected := v1alpha1.PushSecretStatusCondition{
  931. Type: v1alpha1.PushSecretReady,
  932. Status: v1.ConditionFalse,
  933. Reason: v1alpha1.ReasonErrored,
  934. Message: "set secret failed: could not get secrets client for store test-store: boom",
  935. }
  936. return checkCondition(ps.Status, expected)
  937. }
  938. }
  939. DescribeTable("When reconciling a PushSecret",
  940. func(tweaks ...testTweaks) {
  941. tc := makeDefaultTestcase()
  942. for _, tweak := range tweaks {
  943. tweak(tc)
  944. }
  945. ctx := context.Background()
  946. By("creating a secret store, secret and pushsecret")
  947. if tc.store != nil {
  948. Expect(k8sClient.Create(ctx, tc.store)).To(Succeed())
  949. }
  950. if tc.secret != nil {
  951. Expect(k8sClient.Create(ctx, tc.secret)).To(Succeed())
  952. }
  953. if tc.pushsecret != nil {
  954. Expect(k8sClient.Create(ctx, tc.pushsecret)).Should(Succeed())
  955. }
  956. time.Sleep(2 * time.Second) // prevents race conditions during tests causing failures
  957. psKey := types.NamespacedName{Name: PushSecretName, Namespace: PushSecretNamespace}
  958. createdPS := &v1alpha1.PushSecret{}
  959. By("checking the pushSecret condition")
  960. Eventually(func() bool {
  961. err := k8sClient.Get(ctx, psKey, createdPS)
  962. if err != nil {
  963. return false
  964. }
  965. return tc.assert(createdPS, tc.secret)
  966. }, timeout, interval).Should(BeTrue())
  967. // this must be optional so we can test faulty es configuration
  968. },
  969. Entry("should sync", syncSuccessfully),
  970. Entry("should not update existing secret if UpdatePolicy=IfNotExists", updateIfNotExists),
  971. Entry("should only update parts of secret that don't already exist if UpdatePolicy=IfNotExists", updateIfNotExistsPartialSecrets),
  972. Entry("should update the PushSecret status correctly if UpdatePolicy=IfNotExists", updateIfNotExistsSyncStatus),
  973. Entry("should fail if secret existence cannot be verified if UpdatePolicy=IfNotExists", updateIfNotExistsSyncFailed),
  974. Entry("should sync with template", syncSuccessfullyWithTemplate),
  975. Entry("should sync with conversion strategy", syncSuccessfullyWithConversionStrategy),
  976. Entry("should delete if DeletionPolicy=Delete", syncAndDeleteSuccessfully),
  977. Entry("should track deletion tasks if Delete fails", failDelete),
  978. Entry("should track deleted stores if Delete fails", failDeleteStore),
  979. Entry("should delete all secrets if SecretStore changes", deleteWholeStore),
  980. Entry("should sync to stores matching labels", syncMatchingLabels),
  981. Entry("should sync with ClusterStore", syncWithClusterStore),
  982. Entry("should sync with ClusterStore matching labels", syncWithClusterStoreMatchingLabels),
  983. Entry("should fail if Secret is not created", failNoSecret),
  984. Entry("should fail if Secret Key does not exist", failNoSecretKey),
  985. Entry("should fail if SetSecret fails", setSecretFail),
  986. Entry("should fail if no valid SecretStore", failNoSecretStore),
  987. Entry("should fail if no valid ClusterSecretStore", failNoClusterStore),
  988. Entry("should fail if NewClient fails", newClientFail),
  989. )
  990. })
  991. var _ = Describe("PushSecret Controller Un/Managed Stores", func() {
  992. const (
  993. PushSecretName = "test-ps"
  994. ManagedPushSecretStore1 = "test-managed-store-1"
  995. ManagedPushSecretStore2 = "test-managed-store-2"
  996. UnmanagedPushSecretStore1 = "test-unmanaged-store-1"
  997. UnmanagedPushSecretStore2 = "test-unmanaged-store-2"
  998. SecretName = "test-secret"
  999. )
  1000. var PushSecretNamespace string
  1001. PushSecretStores := []string{ManagedPushSecretStore1, ManagedPushSecretStore2, UnmanagedPushSecretStore1, UnmanagedPushSecretStore2}
  1002. // if we are in debug and need to increase the timeout for testing, we can do so by using an env var
  1003. if customTimeout := os.Getenv("TEST_CUSTOM_TIMEOUT_SEC"); customTimeout != "" {
  1004. if t, err := strconv.Atoi(customTimeout); err == nil {
  1005. timeout = time.Second * time.Duration(t)
  1006. }
  1007. }
  1008. BeforeEach(func() {
  1009. var err error
  1010. PushSecretNamespace, err = ctest.CreateNamespace("test-ns", k8sClient)
  1011. Expect(err).ToNot(HaveOccurred())
  1012. fakeProvider.Reset()
  1013. })
  1014. AfterEach(func() {
  1015. k8sClient.Delete(context.Background(), &v1alpha1.PushSecret{
  1016. ObjectMeta: metav1.ObjectMeta{
  1017. Name: PushSecretName,
  1018. Namespace: PushSecretNamespace,
  1019. },
  1020. })
  1021. // give a time for reconciler to remove finalizers before removing SecretStores
  1022. // TODO: Secret Stores should have finalizers bound to PushSecrets if DeletionPolicy == Delete
  1023. time.Sleep(2 * time.Second)
  1024. for _, psstore := range PushSecretStores {
  1025. k8sClient.Delete(context.Background(), &v1beta1.SecretStore{
  1026. ObjectMeta: metav1.ObjectMeta{
  1027. Name: psstore,
  1028. Namespace: PushSecretNamespace,
  1029. },
  1030. })
  1031. k8sClient.Delete(context.Background(), &v1beta1.ClusterSecretStore{
  1032. ObjectMeta: metav1.ObjectMeta{
  1033. Name: psstore,
  1034. },
  1035. })
  1036. }
  1037. k8sClient.Delete(context.Background(), &v1.Secret{
  1038. ObjectMeta: metav1.ObjectMeta{
  1039. Name: SecretName,
  1040. Namespace: PushSecretNamespace,
  1041. },
  1042. })
  1043. Expect(k8sClient.Delete(context.Background(), &v1.Namespace{
  1044. ObjectMeta: metav1.ObjectMeta{
  1045. Name: PushSecretNamespace,
  1046. },
  1047. })).To(Succeed())
  1048. })
  1049. const (
  1050. defaultKey = "key"
  1051. defaultVal = "value"
  1052. defaultPath = "path/to/key"
  1053. otherKey = "other-key"
  1054. otherVal = "other-value"
  1055. otherPath = "path/to/other-key"
  1056. newKey = "new-key"
  1057. newVal = "new-value"
  1058. storePrefixTemplate = "SecretStore/%v"
  1059. )
  1060. makeDefaultTestcase := func() *testCase {
  1061. return &testCase{
  1062. pushsecret: &v1alpha1.PushSecret{
  1063. ObjectMeta: metav1.ObjectMeta{
  1064. Name: PushSecretName,
  1065. Namespace: PushSecretNamespace,
  1066. },
  1067. Spec: v1alpha1.PushSecretSpec{
  1068. SecretStoreRefs: []v1alpha1.PushSecretStoreRef{
  1069. {
  1070. Name: ManagedPushSecretStore1,
  1071. Kind: "SecretStore",
  1072. },
  1073. },
  1074. Selector: v1alpha1.PushSecretSelector{
  1075. Secret: v1alpha1.PushSecretSecret{
  1076. Name: SecretName,
  1077. },
  1078. },
  1079. Data: []v1alpha1.PushSecretData{
  1080. {
  1081. Match: v1alpha1.PushSecretMatch{
  1082. SecretKey: defaultKey,
  1083. RemoteRef: v1alpha1.PushSecretRemoteRef{
  1084. RemoteKey: defaultPath,
  1085. },
  1086. },
  1087. },
  1088. },
  1089. },
  1090. },
  1091. secret: &v1.Secret{
  1092. ObjectMeta: metav1.ObjectMeta{
  1093. Name: SecretName,
  1094. Namespace: PushSecretNamespace,
  1095. },
  1096. Data: map[string][]byte{
  1097. defaultKey: []byte(defaultVal),
  1098. },
  1099. },
  1100. managedStore1: &v1beta1.SecretStore{
  1101. ObjectMeta: metav1.ObjectMeta{
  1102. Name: ManagedPushSecretStore1,
  1103. Namespace: PushSecretNamespace,
  1104. },
  1105. TypeMeta: metav1.TypeMeta{
  1106. Kind: "SecretStore",
  1107. },
  1108. Spec: v1beta1.SecretStoreSpec{
  1109. Provider: &v1beta1.SecretStoreProvider{
  1110. Fake: &v1beta1.FakeProvider{
  1111. Data: []v1beta1.FakeProviderData{},
  1112. },
  1113. },
  1114. },
  1115. },
  1116. managedStore2: &v1beta1.SecretStore{
  1117. ObjectMeta: metav1.ObjectMeta{
  1118. Name: ManagedPushSecretStore2,
  1119. Namespace: PushSecretNamespace,
  1120. },
  1121. TypeMeta: metav1.TypeMeta{
  1122. Kind: "SecretStore",
  1123. },
  1124. Spec: v1beta1.SecretStoreSpec{
  1125. Provider: &v1beta1.SecretStoreProvider{
  1126. Fake: &v1beta1.FakeProvider{
  1127. Data: []v1beta1.FakeProviderData{},
  1128. },
  1129. },
  1130. },
  1131. },
  1132. unmanagedStore1: &v1beta1.SecretStore{
  1133. ObjectMeta: metav1.ObjectMeta{
  1134. Name: UnmanagedPushSecretStore1,
  1135. Namespace: PushSecretNamespace,
  1136. },
  1137. TypeMeta: metav1.TypeMeta{
  1138. Kind: "SecretStore",
  1139. },
  1140. Spec: v1beta1.SecretStoreSpec{
  1141. Provider: &v1beta1.SecretStoreProvider{
  1142. Fake: &v1beta1.FakeProvider{
  1143. Data: []v1beta1.FakeProviderData{},
  1144. },
  1145. },
  1146. Controller: "not-managed",
  1147. },
  1148. },
  1149. unmanagedStore2: &v1beta1.SecretStore{
  1150. ObjectMeta: metav1.ObjectMeta{
  1151. Name: UnmanagedPushSecretStore2,
  1152. Namespace: PushSecretNamespace,
  1153. },
  1154. TypeMeta: metav1.TypeMeta{
  1155. Kind: "SecretStore",
  1156. },
  1157. Spec: v1beta1.SecretStoreSpec{
  1158. Provider: &v1beta1.SecretStoreProvider{
  1159. Fake: &v1beta1.FakeProvider{
  1160. Data: []v1beta1.FakeProviderData{},
  1161. },
  1162. },
  1163. Controller: "not-managed",
  1164. },
  1165. },
  1166. }
  1167. }
  1168. multipleManagedStoresSyncsSuccessfully := func(tc *testCase) {
  1169. fakeProvider.SetSecretFn = func() error {
  1170. return nil
  1171. }
  1172. tc.pushsecret.Spec.SecretStoreRefs = append(tc.pushsecret.Spec.SecretStoreRefs,
  1173. v1alpha1.PushSecretStoreRef{
  1174. Name: ManagedPushSecretStore2,
  1175. Kind: "SecretStore",
  1176. },
  1177. )
  1178. tc.assert = func(ps *v1alpha1.PushSecret, secret *v1.Secret) bool {
  1179. Eventually(func() bool {
  1180. By("checking if Provider value got updated")
  1181. secretValue := secret.Data[defaultKey]
  1182. providerValue, ok := fakeProvider.SetSecretArgs[ps.Spec.Data[0].Match.RemoteRef.RemoteKey]
  1183. if !ok {
  1184. return false
  1185. }
  1186. got := providerValue.Value
  1187. return bytes.Equal(got, secretValue)
  1188. }, time.Second*10, time.Second).Should(BeTrue())
  1189. return true
  1190. }
  1191. }
  1192. skipUnmanagedStores := func(tc *testCase) {
  1193. tc.pushsecret.Spec.SecretStoreRefs = []v1alpha1.PushSecretStoreRef{
  1194. {
  1195. Name: UnmanagedPushSecretStore1,
  1196. Kind: "SecretStore",
  1197. },
  1198. {
  1199. Name: UnmanagedPushSecretStore2,
  1200. Kind: "SecretStore",
  1201. },
  1202. }
  1203. tc.assert = func(ps *v1alpha1.PushSecret, secret *v1.Secret) bool {
  1204. return len(ps.Status.Conditions) == 0
  1205. }
  1206. }
  1207. warnUnmanagedStoresAndSyncManagedStores := func(tc *testCase) {
  1208. fakeProvider.SetSecretFn = func() error {
  1209. return nil
  1210. }
  1211. tc.pushsecret.Spec.SecretStoreRefs = []v1alpha1.PushSecretStoreRef{
  1212. {
  1213. Name: ManagedPushSecretStore1,
  1214. Kind: "SecretStore",
  1215. },
  1216. {
  1217. Name: ManagedPushSecretStore2,
  1218. Kind: "SecretStore",
  1219. },
  1220. {
  1221. Name: UnmanagedPushSecretStore1,
  1222. Kind: "SecretStore",
  1223. },
  1224. {
  1225. Name: UnmanagedPushSecretStore2,
  1226. Kind: "SecretStore",
  1227. },
  1228. }
  1229. tc.assert = func(ps *v1alpha1.PushSecret, secret *v1.Secret) bool {
  1230. Eventually(func() bool {
  1231. By("checking if Provider value got updated")
  1232. secretValue := secret.Data[defaultKey]
  1233. providerValue, ok := fakeProvider.SetSecretArgs[ps.Spec.Data[0].Match.RemoteRef.RemoteKey]
  1234. if !ok {
  1235. return false
  1236. }
  1237. got := providerValue.Value
  1238. return bytes.Equal(got, secretValue)
  1239. }, time.Second*10, time.Second).Should(BeTrue())
  1240. return true
  1241. }
  1242. }
  1243. DescribeTable("When reconciling a PushSecret with multiple secret stores",
  1244. func(tweaks ...testTweaks) {
  1245. tc := makeDefaultTestcase()
  1246. for _, tweak := range tweaks {
  1247. tweak(tc)
  1248. }
  1249. ctx := context.Background()
  1250. By("creating secret stores, a secret and a pushsecret")
  1251. if tc.managedStore1 != nil {
  1252. Expect(k8sClient.Create(ctx, tc.managedStore1)).To(Succeed())
  1253. }
  1254. if tc.managedStore2 != nil {
  1255. Expect(k8sClient.Create(ctx, tc.managedStore2)).To(Succeed())
  1256. }
  1257. if tc.unmanagedStore1 != nil {
  1258. Expect(k8sClient.Create(ctx, tc.unmanagedStore1)).To(Succeed())
  1259. }
  1260. if tc.unmanagedStore2 != nil {
  1261. Expect(k8sClient.Create(ctx, tc.unmanagedStore2)).To(Succeed())
  1262. }
  1263. if tc.secret != nil {
  1264. Expect(k8sClient.Create(ctx, tc.secret)).To(Succeed())
  1265. }
  1266. if tc.pushsecret != nil {
  1267. Expect(k8sClient.Create(ctx, tc.pushsecret)).Should(Succeed())
  1268. }
  1269. time.Sleep(2 * time.Second) // prevents race conditions during tests causing failures
  1270. psKey := types.NamespacedName{Name: PushSecretName, Namespace: PushSecretNamespace}
  1271. createdPS := &v1alpha1.PushSecret{}
  1272. By("checking the pushSecret condition")
  1273. Eventually(func() bool {
  1274. err := k8sClient.Get(ctx, psKey, createdPS)
  1275. if err != nil {
  1276. return false
  1277. }
  1278. return tc.assert(createdPS, tc.secret)
  1279. }, timeout, interval).Should(BeTrue())
  1280. // this must be optional so we can test faulty es configuration
  1281. },
  1282. Entry("should sync successfully if there are multiple managed stores", multipleManagedStoresSyncsSuccessfully),
  1283. Entry("should skip unmanaged stores", skipUnmanagedStores),
  1284. Entry("should skip unmanaged stores and sync managed stores", warnUnmanagedStoresAndSyncManagedStores),
  1285. )
  1286. })