clusterexternalsecret_controller_test.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  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 clusterexternalsecret
  13. import (
  14. "context"
  15. "fmt"
  16. "math/rand"
  17. "time"
  18. . "github.com/onsi/ginkgo/v2"
  19. . "github.com/onsi/gomega"
  20. v1 "k8s.io/api/core/v1"
  21. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  22. "k8s.io/apimachinery/pkg/types"
  23. crclient "sigs.k8s.io/controller-runtime/pkg/client"
  24. esv1beta1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1beta1"
  25. "github.com/external-secrets/external-secrets/pkg/controllers/clusterexternalsecret/cesmetrics"
  26. ctrlmetrics "github.com/external-secrets/external-secrets/pkg/controllers/metrics"
  27. )
  28. func init() {
  29. ctrlmetrics.SetUpLabelNames(false)
  30. cesmetrics.SetUpMetrics()
  31. }
  32. var (
  33. timeout = time.Second * 3
  34. interval = time.Millisecond * 250
  35. )
  36. type testCase struct {
  37. namespaces []v1.Namespace
  38. clusterExternalSecret func(namespaces []v1.Namespace) esv1beta1.ClusterExternalSecret
  39. beforeCheck func(ctx context.Context, namespaces []v1.Namespace, created esv1beta1.ClusterExternalSecret)
  40. expectedClusterExternalSecret func(namespaces []v1.Namespace, created esv1beta1.ClusterExternalSecret) esv1beta1.ClusterExternalSecret
  41. expectedExternalSecrets func(namespaces []v1.Namespace, created esv1beta1.ClusterExternalSecret) []esv1beta1.ExternalSecret
  42. }
  43. var _ = Describe("ClusterExternalSecret controller", func() {
  44. defaultClusterExternalSecret := func() *esv1beta1.ClusterExternalSecret {
  45. return &esv1beta1.ClusterExternalSecret{
  46. ObjectMeta: metav1.ObjectMeta{
  47. Name: fmt.Sprintf("test-ces-%s", randString(10)),
  48. },
  49. Spec: esv1beta1.ClusterExternalSecretSpec{
  50. ExternalSecretSpec: esv1beta1.ExternalSecretSpec{
  51. SecretStoreRef: esv1beta1.SecretStoreRef{
  52. Name: "test-store",
  53. },
  54. Target: esv1beta1.ExternalSecretTarget{
  55. Name: "test-secret",
  56. },
  57. Data: []esv1beta1.ExternalSecretData{
  58. {
  59. SecretKey: "test-secret-key",
  60. RemoteRef: esv1beta1.ExternalSecretDataRemoteRef{
  61. Key: "test-remote-key",
  62. },
  63. },
  64. },
  65. },
  66. },
  67. }
  68. }
  69. DescribeTable("When reconciling a ClusterExternal Secret",
  70. func(tc testCase) {
  71. ctx := context.Background()
  72. By("creating namespaces")
  73. var namespaces []v1.Namespace
  74. for _, ns := range tc.namespaces {
  75. err := k8sClient.Create(ctx, &ns)
  76. Expect(err).ShouldNot(HaveOccurred())
  77. namespaces = append(namespaces, ns)
  78. }
  79. By("creating a cluster external secret")
  80. ces := tc.clusterExternalSecret(tc.namespaces)
  81. err := k8sClient.Create(ctx, &ces)
  82. Expect(err).ShouldNot(HaveOccurred())
  83. By("running before check")
  84. if tc.beforeCheck != nil {
  85. tc.beforeCheck(ctx, namespaces, ces)
  86. }
  87. // the before check above may have updated the namespaces, so refresh them
  88. for i, ns := range namespaces {
  89. err := k8sClient.Get(ctx, types.NamespacedName{Name: ns.Name}, &ns)
  90. Expect(err).ShouldNot(HaveOccurred())
  91. namespaces[i] = ns
  92. }
  93. By("checking the cluster external secret")
  94. expectedCES := tc.expectedClusterExternalSecret(namespaces, ces)
  95. Eventually(func(g Gomega) {
  96. key := types.NamespacedName{Name: expectedCES.Name}
  97. var gotCes esv1beta1.ClusterExternalSecret
  98. err = k8sClient.Get(ctx, key, &gotCes)
  99. g.Expect(err).ShouldNot(HaveOccurred())
  100. g.Expect(gotCes.Labels).To(Equal(expectedCES.Labels))
  101. g.Expect(gotCes.Annotations).To(Equal(expectedCES.Annotations))
  102. g.Expect(gotCes.Spec).To(Equal(expectedCES.Spec))
  103. g.Expect(gotCes.Status).To(Equal(expectedCES.Status))
  104. }).WithTimeout(timeout).WithPolling(interval).Should(Succeed())
  105. By("checking the external secrets")
  106. expectedESs := tc.expectedExternalSecrets(namespaces, ces)
  107. Eventually(func(g Gomega) {
  108. var gotESs []esv1beta1.ExternalSecret
  109. for _, ns := range namespaces {
  110. var externalSecrets esv1beta1.ExternalSecretList
  111. err := k8sClient.List(ctx, &externalSecrets, crclient.InNamespace(ns.Name))
  112. g.Expect(err).ShouldNot(HaveOccurred())
  113. gotESs = append(gotESs, externalSecrets.Items...)
  114. }
  115. g.Expect(len(gotESs)).Should(Equal(len(expectedESs)))
  116. for _, gotES := range gotESs {
  117. found := false
  118. for _, expectedES := range expectedESs {
  119. if gotES.Namespace == expectedES.Namespace && gotES.Name == expectedES.Name {
  120. found = true
  121. g.Expect(gotES.Labels).To(Equal(expectedES.Labels))
  122. g.Expect(gotES.Annotations).To(Equal(expectedES.Annotations))
  123. g.Expect(gotES.Spec).To(Equal(expectedES.Spec))
  124. }
  125. }
  126. g.Expect(found).To(Equal(true))
  127. }
  128. }).WithTimeout(timeout).WithPolling(interval).Should(Succeed())
  129. },
  130. Entry("Should use cluster external secret name if external secret name isn't defined", testCase{
  131. namespaces: []v1.Namespace{
  132. {ObjectMeta: metav1.ObjectMeta{Name: randomNamespaceName()}},
  133. },
  134. clusterExternalSecret: func(namespaces []v1.Namespace) esv1beta1.ClusterExternalSecret {
  135. ces := defaultClusterExternalSecret()
  136. ces.Spec.NamespaceSelector.MatchLabels = map[string]string{"kubernetes.io/metadata.name": namespaces[0].Name}
  137. return *ces
  138. },
  139. expectedClusterExternalSecret: func(namespaces []v1.Namespace, created esv1beta1.ClusterExternalSecret) esv1beta1.ClusterExternalSecret {
  140. return esv1beta1.ClusterExternalSecret{
  141. ObjectMeta: metav1.ObjectMeta{
  142. Name: created.Name,
  143. },
  144. Spec: created.Spec,
  145. Status: esv1beta1.ClusterExternalSecretStatus{
  146. ProvisionedNamespaces: []string{namespaces[0].Name},
  147. Conditions: []esv1beta1.ClusterExternalSecretStatusCondition{
  148. {
  149. Type: esv1beta1.ClusterExternalSecretReady,
  150. Status: v1.ConditionTrue,
  151. },
  152. },
  153. },
  154. }
  155. },
  156. expectedExternalSecrets: func(namespaces []v1.Namespace, created esv1beta1.ClusterExternalSecret) []esv1beta1.ExternalSecret {
  157. return []esv1beta1.ExternalSecret{
  158. {
  159. ObjectMeta: metav1.ObjectMeta{
  160. Namespace: namespaces[0].Name,
  161. Name: created.Name,
  162. },
  163. Spec: created.Spec.ExternalSecretSpec,
  164. },
  165. }
  166. },
  167. }),
  168. Entry("Should set external secret name and metadata if the fields are set", testCase{
  169. namespaces: []v1.Namespace{
  170. {ObjectMeta: metav1.ObjectMeta{Name: randomNamespaceName()}},
  171. },
  172. clusterExternalSecret: func(namespaces []v1.Namespace) esv1beta1.ClusterExternalSecret {
  173. ces := defaultClusterExternalSecret()
  174. ces.Spec.NamespaceSelector.MatchLabels = map[string]string{"kubernetes.io/metadata.name": namespaces[0].Name}
  175. ces.Spec.ExternalSecretName = "test-es"
  176. ces.Spec.ExternalSecretMetadata = esv1beta1.ExternalSecretMetadata{
  177. Labels: map[string]string{"test-label-key1": "test-label-value1", "test-label-key2": "test-label-value2"},
  178. Annotations: map[string]string{"test-annotation-key1": "test-annotation-value1", "test-annotation-key2": "test-annotation-value2"},
  179. }
  180. return *ces
  181. },
  182. expectedClusterExternalSecret: func(namespaces []v1.Namespace, created esv1beta1.ClusterExternalSecret) esv1beta1.ClusterExternalSecret {
  183. return esv1beta1.ClusterExternalSecret{
  184. ObjectMeta: metav1.ObjectMeta{
  185. Name: created.Name,
  186. },
  187. Spec: created.Spec,
  188. Status: esv1beta1.ClusterExternalSecretStatus{
  189. ProvisionedNamespaces: []string{namespaces[0].Name},
  190. Conditions: []esv1beta1.ClusterExternalSecretStatusCondition{
  191. {
  192. Type: esv1beta1.ClusterExternalSecretReady,
  193. Status: v1.ConditionTrue,
  194. },
  195. },
  196. },
  197. }
  198. },
  199. expectedExternalSecrets: func(namespaces []v1.Namespace, created esv1beta1.ClusterExternalSecret) []esv1beta1.ExternalSecret {
  200. return []esv1beta1.ExternalSecret{
  201. {
  202. ObjectMeta: metav1.ObjectMeta{
  203. Namespace: namespaces[0].Name,
  204. Name: "test-es",
  205. Labels: map[string]string{"test-label-key1": "test-label-value1", "test-label-key2": "test-label-value2"},
  206. Annotations: map[string]string{"test-annotation-key1": "test-annotation-value1", "test-annotation-key2": "test-annotation-value2"},
  207. },
  208. Spec: created.Spec.ExternalSecretSpec,
  209. },
  210. }
  211. },
  212. }),
  213. Entry("Should not overwrite existing external secrets and error out if one is present", testCase{
  214. namespaces: []v1.Namespace{
  215. {ObjectMeta: metav1.ObjectMeta{Name: randomNamespaceName()}},
  216. },
  217. clusterExternalSecret: func(namespaces []v1.Namespace) esv1beta1.ClusterExternalSecret {
  218. ces := defaultClusterExternalSecret()
  219. ces.Spec.NamespaceSelector.MatchLabels = map[string]string{"kubernetes.io/metadata.name": namespaces[0].Name}
  220. return *ces
  221. },
  222. beforeCheck: func(ctx context.Context, namespaces []v1.Namespace, created esv1beta1.ClusterExternalSecret) {
  223. es := &esv1beta1.ExternalSecret{
  224. ObjectMeta: metav1.ObjectMeta{
  225. Name: created.Name,
  226. Namespace: namespaces[0].Name,
  227. },
  228. }
  229. Expect(k8sClient.Create(ctx, es)).ShouldNot(HaveOccurred())
  230. },
  231. expectedClusterExternalSecret: func(namespaces []v1.Namespace, created esv1beta1.ClusterExternalSecret) esv1beta1.ClusterExternalSecret {
  232. return esv1beta1.ClusterExternalSecret{
  233. ObjectMeta: metav1.ObjectMeta{
  234. Name: created.Name,
  235. },
  236. Spec: created.Spec,
  237. Status: esv1beta1.ClusterExternalSecretStatus{
  238. FailedNamespaces: []esv1beta1.ClusterExternalSecretNamespaceFailure{
  239. {
  240. Namespace: namespaces[0].Name,
  241. Reason: "external secret already exists in namespace",
  242. },
  243. },
  244. Conditions: []esv1beta1.ClusterExternalSecretStatusCondition{
  245. {
  246. Type: esv1beta1.ClusterExternalSecretNotReady,
  247. Status: v1.ConditionTrue,
  248. Message: "one or more namespaces failed",
  249. },
  250. },
  251. },
  252. }
  253. },
  254. expectedExternalSecrets: func(namespaces []v1.Namespace, created esv1beta1.ClusterExternalSecret) []esv1beta1.ExternalSecret {
  255. return []esv1beta1.ExternalSecret{
  256. {
  257. ObjectMeta: metav1.ObjectMeta{
  258. Namespace: namespaces[0].Name,
  259. Name: created.Name,
  260. },
  261. Spec: esv1beta1.ExternalSecretSpec{
  262. Target: esv1beta1.ExternalSecretTarget{
  263. CreationPolicy: "Owner",
  264. DeletionPolicy: "Retain",
  265. },
  266. RefreshInterval: &metav1.Duration{Duration: time.Hour},
  267. },
  268. },
  269. }
  270. },
  271. }),
  272. Entry("Should delete external secrets when namespaces no longer match", testCase{
  273. namespaces: []v1.Namespace{
  274. {
  275. ObjectMeta: metav1.ObjectMeta{
  276. Name: randomNamespaceName(),
  277. Labels: map[string]string{"no-longer-match-label-key": "no-longer-match-label-value"},
  278. },
  279. },
  280. {
  281. ObjectMeta: metav1.ObjectMeta{
  282. Name: randomNamespaceName(),
  283. Labels: map[string]string{"no-longer-match-label-key": "no-longer-match-label-value"},
  284. },
  285. },
  286. },
  287. clusterExternalSecret: func(namespaces []v1.Namespace) esv1beta1.ClusterExternalSecret {
  288. ces := defaultClusterExternalSecret()
  289. ces.Spec.RefreshInterval = &metav1.Duration{Duration: 100 * time.Millisecond}
  290. ces.Spec.NamespaceSelector.MatchLabels = map[string]string{"no-longer-match-label-key": "no-longer-match-label-value"}
  291. return *ces
  292. },
  293. beforeCheck: func(ctx context.Context, namespaces []v1.Namespace, created esv1beta1.ClusterExternalSecret) {
  294. // Wait until the target ESs have been created
  295. Eventually(func(g Gomega) {
  296. for _, ns := range namespaces {
  297. key := types.NamespacedName{Namespace: ns.Name, Name: created.Name}
  298. g.Expect(k8sClient.Get(ctx, key, &esv1beta1.ExternalSecret{})).ShouldNot(HaveOccurred())
  299. }
  300. }).WithTimeout(timeout).WithPolling(interval).Should(Succeed())
  301. for _, ns := range namespaces {
  302. ns.Labels = map[string]string{}
  303. Expect(k8sClient.Update(ctx, &ns)).ShouldNot(HaveOccurred())
  304. }
  305. },
  306. expectedClusterExternalSecret: func(namespaces []v1.Namespace, created esv1beta1.ClusterExternalSecret) esv1beta1.ClusterExternalSecret {
  307. return esv1beta1.ClusterExternalSecret{
  308. ObjectMeta: metav1.ObjectMeta{
  309. Name: created.Name,
  310. },
  311. Spec: created.Spec,
  312. Status: esv1beta1.ClusterExternalSecretStatus{
  313. ProvisionedNamespaces: []string{namespaces[0].Name, namespaces[1].Name},
  314. Conditions: []esv1beta1.ClusterExternalSecretStatusCondition{
  315. {
  316. Type: esv1beta1.ClusterExternalSecretReady,
  317. Status: v1.ConditionTrue,
  318. },
  319. },
  320. },
  321. }
  322. },
  323. expectedExternalSecrets: func(namespaces []v1.Namespace, created esv1beta1.ClusterExternalSecret) []esv1beta1.ExternalSecret {
  324. return []esv1beta1.ExternalSecret{}
  325. },
  326. }),
  327. Entry("Should sync with match expression", testCase{
  328. namespaces: []v1.Namespace{
  329. {
  330. ObjectMeta: metav1.ObjectMeta{
  331. Name: randomNamespaceName(),
  332. Labels: map[string]string{"prefix": "foo"},
  333. },
  334. },
  335. {
  336. ObjectMeta: metav1.ObjectMeta{
  337. Name: randomNamespaceName(),
  338. Labels: map[string]string{"prefix": "bar"},
  339. },
  340. },
  341. {
  342. ObjectMeta: metav1.ObjectMeta{
  343. Name: randomNamespaceName(),
  344. Labels: map[string]string{"prefix": "baz"},
  345. },
  346. },
  347. },
  348. clusterExternalSecret: func(namespaces []v1.Namespace) esv1beta1.ClusterExternalSecret {
  349. ces := defaultClusterExternalSecret()
  350. ces.Spec.RefreshInterval = &metav1.Duration{Duration: 100 * time.Millisecond}
  351. ces.Spec.NamespaceSelector.MatchExpressions = []metav1.LabelSelectorRequirement{
  352. {
  353. Key: "prefix",
  354. Operator: metav1.LabelSelectorOpIn,
  355. Values: []string{"foo", "bar"}, // "baz" is excluded
  356. },
  357. }
  358. return *ces
  359. },
  360. expectedClusterExternalSecret: func(namespaces []v1.Namespace, created esv1beta1.ClusterExternalSecret) esv1beta1.ClusterExternalSecret {
  361. return esv1beta1.ClusterExternalSecret{
  362. ObjectMeta: metav1.ObjectMeta{
  363. Name: created.Name,
  364. },
  365. Spec: created.Spec,
  366. Status: esv1beta1.ClusterExternalSecretStatus{
  367. ProvisionedNamespaces: []string{namespaces[0].Name, namespaces[1].Name},
  368. Conditions: []esv1beta1.ClusterExternalSecretStatusCondition{
  369. {
  370. Type: esv1beta1.ClusterExternalSecretReady,
  371. Status: v1.ConditionTrue,
  372. },
  373. },
  374. },
  375. }
  376. },
  377. expectedExternalSecrets: func(namespaces []v1.Namespace, created esv1beta1.ClusterExternalSecret) []esv1beta1.ExternalSecret {
  378. return []esv1beta1.ExternalSecret{
  379. {
  380. ObjectMeta: metav1.ObjectMeta{
  381. Namespace: namespaces[0].Name,
  382. Name: created.Name,
  383. },
  384. Spec: created.Spec.ExternalSecretSpec,
  385. },
  386. {
  387. ObjectMeta: metav1.ObjectMeta{
  388. Namespace: namespaces[1].Name,
  389. Name: created.Name,
  390. },
  391. Spec: created.Spec.ExternalSecretSpec,
  392. },
  393. }
  394. },
  395. }))
  396. })
  397. var letterRunes = []rune("abcdefghijklmnopqrstuvwxyz")
  398. func randString(n int) string {
  399. b := make([]rune, n)
  400. for i := range b {
  401. b[i] = letterRunes[rand.Intn(len(letterRunes))]
  402. }
  403. return string(b)
  404. }
  405. func randomNamespaceName() string {
  406. return fmt.Sprintf("testns-%s", randString(10))
  407. }