externalsecret_controller_test.go 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266
  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. "context"
  15. "fmt"
  16. "os"
  17. "strconv"
  18. "time"
  19. . "github.com/onsi/ginkgo"
  20. . "github.com/onsi/ginkgo/extensions/table"
  21. . "github.com/onsi/gomega"
  22. dto "github.com/prometheus/client_model/go"
  23. v1 "k8s.io/api/core/v1"
  24. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  25. "k8s.io/apimachinery/pkg/types"
  26. "k8s.io/apimachinery/pkg/util/wait"
  27. "sigs.k8s.io/controller-runtime/pkg/client"
  28. esv1alpha1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1alpha1"
  29. "github.com/external-secrets/external-secrets/pkg/provider"
  30. "github.com/external-secrets/external-secrets/pkg/provider/fake"
  31. "github.com/external-secrets/external-secrets/pkg/provider/schema"
  32. )
  33. var (
  34. fakeProvider *fake.Client
  35. metric dto.Metric
  36. timeout = time.Second * 10
  37. interval = time.Millisecond * 250
  38. )
  39. type testCase struct {
  40. secretStore *esv1alpha1.SecretStore
  41. externalSecret *esv1alpha1.ExternalSecret
  42. // checkCondition should return true if the externalSecret
  43. // has the expected condition
  44. checkCondition func(*esv1alpha1.ExternalSecret) bool
  45. // checkExternalSecret is called after the condition has been verified
  46. // use this to verify the externalSecret
  47. checkExternalSecret func(*esv1alpha1.ExternalSecret)
  48. // optional. use this to test the secret value
  49. checkSecret func(*esv1alpha1.ExternalSecret, *v1.Secret)
  50. }
  51. type testTweaks func(*testCase)
  52. var _ = Describe("Kind=secret existence logic", func() {
  53. type testCase struct {
  54. Name string
  55. Input v1.Secret
  56. ExpectedOutput bool
  57. }
  58. tests := []testCase{
  59. {
  60. Name: "Should not be valid in case of missing uid",
  61. Input: v1.Secret{},
  62. ExpectedOutput: false,
  63. },
  64. {
  65. Name: "A nil annotation should not be valid",
  66. Input: v1.Secret{
  67. ObjectMeta: metav1.ObjectMeta{
  68. UID: "xxx",
  69. Annotations: map[string]string{},
  70. },
  71. },
  72. ExpectedOutput: false,
  73. },
  74. {
  75. Name: "A nil annotation should not be valid",
  76. Input: v1.Secret{
  77. ObjectMeta: metav1.ObjectMeta{
  78. UID: "xxx",
  79. Annotations: map[string]string{},
  80. },
  81. },
  82. ExpectedOutput: false,
  83. },
  84. {
  85. Name: "An invalid annotation hash should not be valid",
  86. Input: v1.Secret{
  87. ObjectMeta: metav1.ObjectMeta{
  88. UID: "xxx",
  89. Annotations: map[string]string{
  90. esv1alpha1.AnnotationDataHash: "xxxxxx",
  91. },
  92. },
  93. },
  94. ExpectedOutput: false,
  95. },
  96. {
  97. Name: "A valid config map should return true",
  98. Input: v1.Secret{
  99. ObjectMeta: metav1.ObjectMeta{
  100. UID: "xxx",
  101. Annotations: map[string]string{
  102. esv1alpha1.AnnotationDataHash: "caa0155759a6a9b3b6ada5a6883ee2bb",
  103. },
  104. },
  105. Data: map[string][]byte{
  106. "foo": []byte("value1"),
  107. "bar": []byte("value2"),
  108. },
  109. },
  110. ExpectedOutput: true,
  111. },
  112. }
  113. for _, tt := range tests {
  114. It(tt.Name, func() {
  115. Expect(isSecretValid(tt.Input)).To(BeEquivalentTo(tt.ExpectedOutput))
  116. })
  117. }
  118. })
  119. var _ = Describe("ExternalSecret controller", func() {
  120. const (
  121. ExternalSecretName = "test-es"
  122. ExternalSecretStore = "test-store"
  123. ExternalSecretTargetSecretName = "test-secret"
  124. FakeManager = "fake.manager"
  125. expectedSecretVal = "SOMEVALUE was templated"
  126. targetPropObj = "{{ .targetProperty | toString | upper }} was templated"
  127. FooValue = "map-foo-value"
  128. BarValue = "map-bar-value"
  129. )
  130. var ExternalSecretNamespace string
  131. // if we are in debug and need to increase the timeout for testing, we can do so by using an env var
  132. if customTimeout := os.Getenv("TEST_CUSTOM_TIMEOUT_SEC"); customTimeout != "" {
  133. if t, err := strconv.Atoi(customTimeout); err == nil {
  134. timeout = time.Second * time.Duration(t)
  135. }
  136. }
  137. BeforeEach(func() {
  138. var err error
  139. ExternalSecretNamespace, err = CreateNamespace("test-ns", k8sClient)
  140. Expect(err).ToNot(HaveOccurred())
  141. metric.Reset()
  142. syncCallsTotal.Reset()
  143. syncCallsError.Reset()
  144. externalSecretCondition.Reset()
  145. })
  146. AfterEach(func() {
  147. Expect(k8sClient.Delete(context.Background(), &v1.Namespace{
  148. ObjectMeta: metav1.ObjectMeta{
  149. Name: ExternalSecretNamespace,
  150. },
  151. }, client.PropagationPolicy(metav1.DeletePropagationBackground)), client.GracePeriodSeconds(0)).To(Succeed())
  152. Expect(k8sClient.Delete(context.Background(), &esv1alpha1.SecretStore{
  153. ObjectMeta: metav1.ObjectMeta{
  154. Name: ExternalSecretStore,
  155. Namespace: ExternalSecretNamespace,
  156. },
  157. }, client.PropagationPolicy(metav1.DeletePropagationBackground)), client.GracePeriodSeconds(0)).To(Succeed())
  158. })
  159. const targetProp = "targetProperty"
  160. const remoteKey = "barz"
  161. const remoteProperty = "bang"
  162. makeDefaultTestcase := func() *testCase {
  163. return &testCase{
  164. // default condition: es should be ready
  165. checkCondition: func(es *esv1alpha1.ExternalSecret) bool {
  166. cond := GetExternalSecretCondition(es.Status, esv1alpha1.ExternalSecretReady)
  167. if cond == nil || cond.Status != v1.ConditionTrue {
  168. return false
  169. }
  170. return true
  171. },
  172. checkExternalSecret: func(es *esv1alpha1.ExternalSecret) {},
  173. secretStore: &esv1alpha1.SecretStore{
  174. ObjectMeta: metav1.ObjectMeta{
  175. Name: ExternalSecretStore,
  176. Namespace: ExternalSecretNamespace,
  177. },
  178. Spec: esv1alpha1.SecretStoreSpec{
  179. Provider: &esv1alpha1.SecretStoreProvider{
  180. AWS: &esv1alpha1.AWSProvider{
  181. Service: esv1alpha1.AWSServiceSecretsManager,
  182. },
  183. },
  184. },
  185. },
  186. externalSecret: &esv1alpha1.ExternalSecret{
  187. ObjectMeta: metav1.ObjectMeta{
  188. Name: ExternalSecretName,
  189. Namespace: ExternalSecretNamespace,
  190. },
  191. Spec: esv1alpha1.ExternalSecretSpec{
  192. SecretStoreRef: esv1alpha1.SecretStoreRef{
  193. Name: ExternalSecretStore,
  194. },
  195. Target: esv1alpha1.ExternalSecretTarget{
  196. Name: ExternalSecretTargetSecretName,
  197. },
  198. Data: []esv1alpha1.ExternalSecretData{
  199. {
  200. SecretKey: targetProp,
  201. RemoteRef: esv1alpha1.ExternalSecretDataRemoteRef{
  202. Key: remoteKey,
  203. Property: remoteProperty,
  204. },
  205. },
  206. },
  207. },
  208. },
  209. }
  210. }
  211. // if target Secret name is not specified it should use the ExternalSecret name.
  212. syncWithoutTargetName := func(tc *testCase) {
  213. tc.externalSecret.Spec.Target.Name = ""
  214. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  215. // check secret name
  216. Expect(secret.ObjectMeta.Name).To(Equal(ExternalSecretName))
  217. }
  218. }
  219. // labels and annotations from the Kind=ExternalSecret
  220. // should be copied over to the Kind=Secret
  221. syncLabelsAnnotations := func(tc *testCase) {
  222. const secretVal = "someValue"
  223. tc.externalSecret.ObjectMeta.Labels = map[string]string{
  224. "fooobar": "bazz",
  225. }
  226. tc.externalSecret.ObjectMeta.Annotations = map[string]string{
  227. "hihihih": "hehehe",
  228. }
  229. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  230. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  231. // check value
  232. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  233. // check labels & annotations
  234. Expect(secret.ObjectMeta.Labels).To(BeEquivalentTo(es.ObjectMeta.Labels))
  235. for k, v := range es.ObjectMeta.Annotations {
  236. Expect(secret.ObjectMeta.Annotations).To(HaveKeyWithValue(k, v))
  237. }
  238. // ownerRef must not not be set!
  239. Expect(hasOwnerRef(secret.ObjectMeta, "ExternalSecret", ExternalSecretName)).To(BeTrue())
  240. }
  241. }
  242. checkPrometheusCounters := func(tc *testCase) {
  243. const secretVal = "someValue"
  244. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  245. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  246. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1alpha1.ExternalSecretReady, v1.ConditionFalse, 0.0)).To(BeTrue())
  247. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1alpha1.ExternalSecretReady, v1.ConditionTrue, 1.0)).To(BeTrue())
  248. Eventually(func() bool {
  249. Expect(syncCallsTotal.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metric)).To(Succeed())
  250. return metric.GetCounter().GetValue() == 1.0
  251. }, timeout, interval).Should(BeTrue())
  252. }
  253. }
  254. // merge with existing secret using creationPolicy=Merge
  255. // it should NOT have a ownerReference
  256. // metadata.managedFields with the correct owner should be added to the secret
  257. mergeWithSecret := func(tc *testCase) {
  258. const secretVal = "someValue"
  259. const existingKey = "pre-existing-key"
  260. existingVal := "pre-existing-value"
  261. tc.externalSecret.Spec.Target.CreationPolicy = esv1alpha1.Merge
  262. // create secret beforehand
  263. Expect(k8sClient.Create(context.Background(), &v1.Secret{
  264. ObjectMeta: metav1.ObjectMeta{
  265. Name: ExternalSecretTargetSecretName,
  266. Namespace: ExternalSecretNamespace,
  267. },
  268. Data: map[string][]byte{
  269. existingKey: []byte(existingVal),
  270. },
  271. }, client.FieldOwner(FakeManager))).To(Succeed())
  272. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  273. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  274. // check value
  275. Expect(string(secret.Data[existingKey])).To(Equal(existingVal))
  276. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  277. // check labels & annotations
  278. Expect(secret.ObjectMeta.Labels).To(BeEquivalentTo(es.ObjectMeta.Labels))
  279. for k, v := range es.ObjectMeta.Annotations {
  280. Expect(secret.ObjectMeta.Annotations).To(HaveKeyWithValue(k, v))
  281. }
  282. Expect(hasOwnerRef(secret.ObjectMeta, "ExternalSecret", ExternalSecretName)).To(BeFalse())
  283. Expect(secret.ObjectMeta.ManagedFields).To(HaveLen(2))
  284. Expect(hasFieldOwnership(
  285. secret.ObjectMeta,
  286. "external-secrets",
  287. fmt.Sprintf("{\"f:data\":{\"f:targetProperty\":{}},\"f:immutable\":{},\"f:metadata\":{\"f:annotations\":{\"f:%s\":{}}}}", esv1alpha1.AnnotationDataHash)),
  288. ).To(BeTrue())
  289. Expect(hasFieldOwnership(secret.ObjectMeta, FakeManager, "{\"f:data\":{\".\":{},\"f:pre-existing-key\":{}},\"f:type\":{}}")).To(BeTrue())
  290. }
  291. }
  292. // should not update if no changes
  293. mergeWithSecretNoChange := func(tc *testCase) {
  294. const existingKey = "pre-existing-key"
  295. existingVal := "someValue"
  296. tc.externalSecret.Spec.Target.CreationPolicy = esv1alpha1.Merge
  297. // create secret beforehand
  298. Expect(k8sClient.Create(context.Background(), &v1.Secret{
  299. ObjectMeta: metav1.ObjectMeta{
  300. Name: ExternalSecretTargetSecretName,
  301. Namespace: ExternalSecretNamespace,
  302. },
  303. Data: map[string][]byte{
  304. existingKey: []byte(existingVal),
  305. },
  306. }, client.FieldOwner(FakeManager))).To(Succeed())
  307. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  308. oldResourceVersion := secret.ResourceVersion
  309. cleanSecret := secret.DeepCopy()
  310. Expect(k8sClient.Patch(context.Background(), secret, client.MergeFrom(cleanSecret))).To(Succeed())
  311. newSecret := &v1.Secret{}
  312. Eventually(func() bool {
  313. secretLookupKey := types.NamespacedName{
  314. Name: ExternalSecretTargetSecretName,
  315. Namespace: ExternalSecretNamespace,
  316. }
  317. err := k8sClient.Get(context.Background(), secretLookupKey, newSecret)
  318. if err != nil {
  319. return false
  320. }
  321. return oldResourceVersion == newSecret.ResourceVersion
  322. }, timeout, interval).Should(Equal(true))
  323. }
  324. }
  325. // should not merge with secret if it doesn't exist
  326. mergeWithSecretErr := func(tc *testCase) {
  327. const secretVal = "someValue"
  328. tc.externalSecret.Spec.Target.CreationPolicy = esv1alpha1.Merge
  329. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  330. tc.checkCondition = func(es *esv1alpha1.ExternalSecret) bool {
  331. cond := GetExternalSecretCondition(es.Status, esv1alpha1.ExternalSecretReady)
  332. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1alpha1.ConditionReasonSecretSyncedError {
  333. return false
  334. }
  335. return true
  336. }
  337. tc.checkExternalSecret = func(es *esv1alpha1.ExternalSecret) {
  338. Eventually(func() bool {
  339. Expect(syncCallsError.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metric)).To(Succeed())
  340. return metric.GetCounter().GetValue() >= 2.0
  341. }, timeout, interval).Should(BeTrue())
  342. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1alpha1.ExternalSecretReady, v1.ConditionFalse, 1.0)).To(BeTrue())
  343. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1alpha1.ExternalSecretReady, v1.ConditionTrue, 0.0)).To(BeTrue())
  344. }
  345. }
  346. // controller should force ownership
  347. mergeWithConflict := func(tc *testCase) {
  348. const secretVal = "someValue"
  349. // this should confict
  350. const existingKey = targetProp
  351. existingVal := "pre-existing-value"
  352. tc.externalSecret.Spec.Target.CreationPolicy = esv1alpha1.Merge
  353. // create secret beforehand
  354. Expect(k8sClient.Create(context.Background(), &v1.Secret{
  355. ObjectMeta: metav1.ObjectMeta{
  356. Name: ExternalSecretTargetSecretName,
  357. Namespace: ExternalSecretNamespace,
  358. },
  359. Data: map[string][]byte{
  360. existingKey: []byte(existingVal),
  361. },
  362. }, client.FieldOwner(FakeManager))).To(Succeed())
  363. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  364. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  365. // check that value stays the same
  366. Expect(string(secret.Data[existingKey])).To(Equal(secretVal))
  367. // check owner/managedFields
  368. Expect(hasOwnerRef(secret.ObjectMeta, "ExternalSecret", ExternalSecretName)).To(BeFalse())
  369. Expect(secret.ObjectMeta.ManagedFields).To(HaveLen(2))
  370. Expect(hasFieldOwnership(secret.ObjectMeta, "external-secrets", "{\"f:data\":{\"f:targetProperty\":{}},\"f:immutable\":{},\"f:metadata\":{\"f:annotations\":{\"f:reconcile.external-secrets.io/data-hash\":{}}}}")).To(BeTrue())
  371. }
  372. }
  373. // when using a template it should be used as a blueprint
  374. // to construct a new secret: labels, annotations and type
  375. syncWithTemplate := func(tc *testCase) {
  376. const secretVal = "someValue"
  377. const tplStaticKey = "tplstatickey"
  378. const tplStaticVal = "tplstaticvalue"
  379. tc.externalSecret.ObjectMeta.Labels = map[string]string{
  380. "fooobar": "bazz",
  381. }
  382. tc.externalSecret.ObjectMeta.Annotations = map[string]string{
  383. "hihihih": "hehehe",
  384. }
  385. tc.externalSecret.Spec.Target.Template = &esv1alpha1.ExternalSecretTemplate{
  386. Metadata: esv1alpha1.ExternalSecretTemplateMetadata{
  387. Labels: map[string]string{
  388. "foos": "ball",
  389. },
  390. Annotations: map[string]string{
  391. "hihi": "ga",
  392. },
  393. },
  394. Type: v1.SecretTypeOpaque,
  395. Data: map[string]string{
  396. targetProp: targetPropObj,
  397. tplStaticKey: tplStaticVal,
  398. },
  399. }
  400. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  401. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  402. // check values
  403. Expect(string(secret.Data[targetProp])).To(Equal(expectedSecretVal))
  404. Expect(string(secret.Data[tplStaticKey])).To(Equal(tplStaticVal))
  405. // labels/annotations should be taken from the template
  406. Expect(secret.ObjectMeta.Labels).To(BeEquivalentTo(es.Spec.Target.Template.Metadata.Labels))
  407. for k, v := range es.Spec.Target.Template.Metadata.Annotations {
  408. Expect(secret.ObjectMeta.Annotations).To(HaveKeyWithValue(k, v))
  409. }
  410. }
  411. }
  412. // secret should be synced with correct value precedence:
  413. // * template
  414. // * templateFrom
  415. // * data
  416. // * dataFrom
  417. syncWithTemplatePrecedence := func(tc *testCase) {
  418. const secretVal = "someValue"
  419. const tplStaticKey = "tplstatickey"
  420. const tplStaticVal = "tplstaticvalue"
  421. const tplFromCMName = "template-cm"
  422. const tplFromSecretName = "template-secret"
  423. const tplFromKey = "tpl-from-key"
  424. const tplFromSecKey = "tpl-from-sec-key"
  425. const tplFromVal = "tpl-from-value: {{ .targetProperty | toString }} // {{ .bar | toString }}"
  426. const tplFromSecVal = "tpl-from-sec-value: {{ .targetProperty | toString }} // {{ .bar | toString }}"
  427. Expect(k8sClient.Create(context.Background(), &v1.ConfigMap{
  428. ObjectMeta: metav1.ObjectMeta{
  429. Name: tplFromCMName,
  430. Namespace: ExternalSecretNamespace,
  431. },
  432. Data: map[string]string{
  433. tplFromKey: tplFromVal,
  434. },
  435. })).To(Succeed())
  436. Expect(k8sClient.Create(context.Background(), &v1.Secret{
  437. ObjectMeta: metav1.ObjectMeta{
  438. Name: tplFromSecretName,
  439. Namespace: ExternalSecretNamespace,
  440. },
  441. Data: map[string][]byte{
  442. tplFromSecKey: []byte(tplFromSecVal),
  443. },
  444. })).To(Succeed())
  445. tc.externalSecret.Spec.Target.Template = &esv1alpha1.ExternalSecretTemplate{
  446. Metadata: esv1alpha1.ExternalSecretTemplateMetadata{},
  447. Type: v1.SecretTypeOpaque,
  448. TemplateFrom: []esv1alpha1.TemplateFrom{
  449. {
  450. ConfigMap: &esv1alpha1.TemplateRef{
  451. Name: tplFromCMName,
  452. Items: []esv1alpha1.TemplateRefItem{
  453. {
  454. Key: tplFromKey,
  455. },
  456. },
  457. },
  458. },
  459. {
  460. Secret: &esv1alpha1.TemplateRef{
  461. Name: tplFromSecretName,
  462. Items: []esv1alpha1.TemplateRefItem{
  463. {
  464. Key: tplFromSecKey,
  465. },
  466. },
  467. },
  468. },
  469. },
  470. Data: map[string]string{
  471. // this should be the data value, not dataFrom
  472. targetProp: targetPropObj,
  473. // this should use the value from the map
  474. "bar": "value from map: {{ .bar | toString }}",
  475. // just a static value
  476. tplStaticKey: tplStaticVal,
  477. },
  478. }
  479. tc.externalSecret.Spec.DataFrom = []esv1alpha1.ExternalSecretDataRemoteRef{
  480. {
  481. Key: "datamap",
  482. },
  483. }
  484. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  485. fakeProvider.WithGetSecretMap(map[string][]byte{
  486. "targetProperty": []byte(FooValue),
  487. "bar": []byte(BarValue),
  488. }, nil)
  489. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  490. // check values
  491. Expect(string(secret.Data[targetProp])).To(Equal(expectedSecretVal))
  492. Expect(string(secret.Data[tplStaticKey])).To(Equal(tplStaticVal))
  493. Expect(string(secret.Data["bar"])).To(Equal("value from map: map-bar-value"))
  494. Expect(string(secret.Data[tplFromKey])).To(Equal("tpl-from-value: someValue // map-bar-value"))
  495. Expect(string(secret.Data[tplFromSecKey])).To(Equal("tpl-from-sec-value: someValue // map-bar-value"))
  496. }
  497. }
  498. refreshWithTemplate := func(tc *testCase) {
  499. const secretVal = "someValue"
  500. const tplStaticKey = "tplstatickey"
  501. const tplStaticVal = "tplstaticvalue"
  502. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Second}
  503. tc.externalSecret.Spec.Target.Template = &esv1alpha1.ExternalSecretTemplate{
  504. Metadata: esv1alpha1.ExternalSecretTemplateMetadata{
  505. Labels: map[string]string{"foo": "bar"},
  506. Annotations: map[string]string{"foo": "bar"},
  507. },
  508. Type: v1.SecretTypeOpaque,
  509. Data: map[string]string{
  510. targetProp: targetPropObj,
  511. tplStaticKey: tplStaticVal,
  512. },
  513. }
  514. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  515. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  516. // check values
  517. Expect(string(secret.Data[targetProp])).To(Equal(expectedSecretVal))
  518. Expect(string(secret.Data[tplStaticKey])).To(Equal(tplStaticVal))
  519. // labels/annotations should be taken from the template
  520. Expect(secret.ObjectMeta.Labels).To(BeEquivalentTo(es.Spec.Target.Template.Metadata.Labels))
  521. // a secret will always have some extra annotations (i.e. hashmap check), so we only check for specific
  522. // source annotations
  523. for k, v := range es.Spec.Target.Template.Metadata.Annotations {
  524. Expect(secret.ObjectMeta.Annotations).To(HaveKeyWithValue(k, v))
  525. }
  526. cleanEs := tc.externalSecret.DeepCopy()
  527. // now update ExternalSecret
  528. tc.externalSecret.Spec.Target.Template.Metadata.Annotations["fuzz"] = "buzz"
  529. tc.externalSecret.Spec.Target.Template.Metadata.Labels["fuzz"] = "buzz"
  530. tc.externalSecret.Spec.Target.Template.Data["new"] = "value"
  531. Expect(k8sClient.Patch(context.Background(), tc.externalSecret, client.MergeFrom(cleanEs))).To(Succeed())
  532. // wait for secret
  533. sec := &v1.Secret{}
  534. secretLookupKey := types.NamespacedName{
  535. Name: ExternalSecretTargetSecretName,
  536. Namespace: ExternalSecretNamespace,
  537. }
  538. Eventually(func() bool {
  539. err := k8sClient.Get(context.Background(), secretLookupKey, sec)
  540. if err != nil {
  541. return false
  542. }
  543. // ensure new data value exist
  544. return string(sec.Data["new"]) == "value"
  545. }, time.Second*10, time.Millisecond*200).Should(BeTrue())
  546. // also check labels/annotations have been updated
  547. Expect(secret.ObjectMeta.Labels).To(BeEquivalentTo(es.Spec.Target.Template.Metadata.Labels))
  548. for k, v := range es.Spec.Target.Template.Metadata.Annotations {
  549. Expect(secret.ObjectMeta.Annotations).To(HaveKeyWithValue(k, v))
  550. }
  551. }
  552. }
  553. onlyMetadataFromTemplate := func(tc *testCase) {
  554. const secretVal = "someValue"
  555. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Second}
  556. tc.externalSecret.Spec.Target.Template = &esv1alpha1.ExternalSecretTemplate{
  557. Metadata: esv1alpha1.ExternalSecretTemplateMetadata{
  558. Labels: map[string]string{"foo": "bar"},
  559. Annotations: map[string]string{"foo": "bar"},
  560. },
  561. }
  562. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  563. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  564. // check values
  565. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  566. // labels/annotations should be taken from the template
  567. Expect(secret.ObjectMeta.Labels).To(BeEquivalentTo(es.Spec.Target.Template.Metadata.Labels))
  568. for k, v := range es.Spec.Target.Template.Metadata.Annotations {
  569. Expect(secret.ObjectMeta.Annotations).To(HaveKeyWithValue(k, v))
  570. }
  571. }
  572. }
  573. // when the provider secret changes the Kind=Secret value
  574. // must change, too.
  575. refreshSecretValue := func(tc *testCase) {
  576. const targetProp = "targetProperty"
  577. const secretVal = "someValue"
  578. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  579. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Second}
  580. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  581. // check values
  582. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  583. // update provider secret
  584. newValue := "NEW VALUE"
  585. sec := &v1.Secret{}
  586. fakeProvider.WithGetSecret([]byte(newValue), nil)
  587. secretLookupKey := types.NamespacedName{
  588. Name: ExternalSecretTargetSecretName,
  589. Namespace: ExternalSecretNamespace,
  590. }
  591. Eventually(func() bool {
  592. err := k8sClient.Get(context.Background(), secretLookupKey, sec)
  593. if err != nil {
  594. return false
  595. }
  596. v := sec.Data[targetProp]
  597. return string(v) == newValue
  598. }, timeout, interval).Should(BeTrue())
  599. }
  600. }
  601. refreshintervalZero := func(tc *testCase) {
  602. const targetProp = "targetProperty"
  603. const secretVal = "someValue"
  604. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  605. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: 0}
  606. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  607. // check values
  608. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  609. // update provider secret
  610. newValue := "NEW VALUE"
  611. sec := &v1.Secret{}
  612. fakeProvider.WithGetSecret([]byte(newValue), nil)
  613. secretLookupKey := types.NamespacedName{
  614. Name: ExternalSecretTargetSecretName,
  615. Namespace: ExternalSecretNamespace,
  616. }
  617. Consistently(func() bool {
  618. err := k8sClient.Get(context.Background(), secretLookupKey, sec)
  619. if err != nil {
  620. return false
  621. }
  622. v := sec.Data[targetProp]
  623. return string(v) == secretVal
  624. }, time.Second*10, time.Second).Should(BeTrue())
  625. }
  626. }
  627. // with dataFrom all properties from the specified secret
  628. // should be put into the secret
  629. syncWithDataFrom := func(tc *testCase) {
  630. tc.externalSecret.Spec.Data = nil
  631. tc.externalSecret.Spec.DataFrom = []esv1alpha1.ExternalSecretDataRemoteRef{
  632. {
  633. Key: remoteKey,
  634. },
  635. }
  636. fakeProvider.WithGetSecretMap(map[string][]byte{
  637. "foo": []byte(FooValue),
  638. "bar": []byte(BarValue),
  639. }, nil)
  640. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  641. // check values
  642. Expect(string(secret.Data["foo"])).To(Equal(FooValue))
  643. Expect(string(secret.Data["bar"])).To(Equal(BarValue))
  644. }
  645. }
  646. // with dataFrom and using a template
  647. // should be put into the secret
  648. syncWithDataFromTemplate := func(tc *testCase) {
  649. tc.externalSecret.Spec.Data = nil
  650. tc.externalSecret.Spec.Target = esv1alpha1.ExternalSecretTarget{
  651. Name: ExternalSecretTargetSecretName,
  652. Template: &esv1alpha1.ExternalSecretTemplate{
  653. Type: v1.SecretTypeTLS,
  654. },
  655. }
  656. tc.externalSecret.Spec.DataFrom = []esv1alpha1.ExternalSecretDataRemoteRef{
  657. {
  658. Key: remoteKey,
  659. },
  660. }
  661. fakeProvider.WithGetSecretMap(map[string][]byte{
  662. "tls.crt": []byte(FooValue),
  663. "tls.key": []byte(BarValue),
  664. }, nil)
  665. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  666. Expect(secret.Type).To(Equal(v1.SecretTypeTLS))
  667. // check values
  668. Expect(string(secret.Data["tls.crt"])).To(Equal(FooValue))
  669. Expect(string(secret.Data["tls.key"])).To(Equal(BarValue))
  670. }
  671. }
  672. // when a provider errors in a GetSecret call
  673. // a error condition must be set.
  674. providerErrCondition := func(tc *testCase) {
  675. const secretVal = "foobar"
  676. fakeProvider.WithGetSecret(nil, fmt.Errorf("boom"))
  677. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Millisecond * 100}
  678. tc.checkCondition = func(es *esv1alpha1.ExternalSecret) bool {
  679. cond := GetExternalSecretCondition(es.Status, esv1alpha1.ExternalSecretReady)
  680. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1alpha1.ConditionReasonSecretSyncedError {
  681. return false
  682. }
  683. return true
  684. }
  685. tc.checkExternalSecret = func(es *esv1alpha1.ExternalSecret) {
  686. Eventually(func() bool {
  687. Expect(syncCallsError.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metric)).To(Succeed())
  688. return metric.GetCounter().GetValue() >= 2.0
  689. }, timeout, interval).Should(BeTrue())
  690. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1alpha1.ExternalSecretReady, v1.ConditionFalse, 1.0)).To(BeTrue())
  691. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1alpha1.ExternalSecretReady, v1.ConditionTrue, 0.0)).To(BeTrue())
  692. // es condition should reflect recovered provider error
  693. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  694. esKey := types.NamespacedName{Name: ExternalSecretName, Namespace: ExternalSecretNamespace}
  695. Eventually(func() bool {
  696. err := k8sClient.Get(context.Background(), esKey, es)
  697. if err != nil {
  698. return false
  699. }
  700. // condition must now be true!
  701. cond := GetExternalSecretCondition(es.Status, esv1alpha1.ExternalSecretReady)
  702. if cond == nil && cond.Status != v1.ConditionTrue {
  703. return false
  704. }
  705. return true
  706. }, timeout, interval).Should(BeTrue())
  707. }
  708. }
  709. // When a ExternalSecret references an non-existing SecretStore
  710. // a error condition must be set.
  711. storeMissingErrCondition := func(tc *testCase) {
  712. tc.externalSecret.Spec.SecretStoreRef.Name = "nonexistent"
  713. tc.checkCondition = func(es *esv1alpha1.ExternalSecret) bool {
  714. cond := GetExternalSecretCondition(es.Status, esv1alpha1.ExternalSecretReady)
  715. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1alpha1.ConditionReasonSecretSyncedError {
  716. return false
  717. }
  718. return true
  719. }
  720. tc.checkExternalSecret = func(es *esv1alpha1.ExternalSecret) {
  721. Eventually(func() bool {
  722. Expect(syncCallsError.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metric)).To(Succeed())
  723. return metric.GetCounter().GetValue() >= 2.0
  724. }, timeout, interval).Should(BeTrue())
  725. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1alpha1.ExternalSecretReady, v1.ConditionFalse, 1.0)).To(BeTrue())
  726. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1alpha1.ExternalSecretReady, v1.ConditionTrue, 0.0)).To(BeTrue())
  727. }
  728. }
  729. // when the provider constructor errors (e.g. invalid configuration)
  730. // a SecretSyncedError status condition must be set
  731. storeConstructErrCondition := func(tc *testCase) {
  732. fakeProvider.WithNew(func(context.Context, esv1alpha1.GenericStore, client.Client,
  733. string) (provider.SecretsClient, error) {
  734. return nil, fmt.Errorf("artificial constructor error")
  735. })
  736. tc.checkCondition = func(es *esv1alpha1.ExternalSecret) bool {
  737. // condition must be false
  738. cond := GetExternalSecretCondition(es.Status, esv1alpha1.ExternalSecretReady)
  739. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1alpha1.ConditionReasonSecretSyncedError {
  740. return false
  741. }
  742. return true
  743. }
  744. tc.checkExternalSecret = func(es *esv1alpha1.ExternalSecret) {
  745. Eventually(func() bool {
  746. Expect(syncCallsError.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metric)).To(Succeed())
  747. return metric.GetCounter().GetValue() >= 2.0
  748. }, timeout, interval).Should(BeTrue())
  749. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1alpha1.ExternalSecretReady, v1.ConditionFalse, 1.0)).To(BeTrue())
  750. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1alpha1.ExternalSecretReady, v1.ConditionTrue, 0.0)).To(BeTrue())
  751. }
  752. }
  753. // when a SecretStore has a controller field set which we don't care about
  754. // the externalSecret must not be touched
  755. ignoreMismatchController := func(tc *testCase) {
  756. tc.secretStore.Spec.Controller = "nop"
  757. tc.checkCondition = func(es *esv1alpha1.ExternalSecret) bool {
  758. cond := GetExternalSecretCondition(es.Status, esv1alpha1.ExternalSecretReady)
  759. return cond == nil
  760. }
  761. tc.checkExternalSecret = func(es *esv1alpha1.ExternalSecret) {
  762. // Condition True and False should be 0, since the Condition was not created
  763. Eventually(func() float64 {
  764. Expect(externalSecretCondition.WithLabelValues(ExternalSecretName, ExternalSecretNamespace, string(esv1alpha1.ExternalSecretReady), string(v1.ConditionTrue)).Write(&metric)).To(Succeed())
  765. return metric.GetGauge().GetValue()
  766. }, timeout, interval).Should(Equal(0.0))
  767. Eventually(func() float64 {
  768. Expect(externalSecretCondition.WithLabelValues(ExternalSecretName, ExternalSecretNamespace, string(esv1alpha1.ExternalSecretReady), string(v1.ConditionFalse)).Write(&metric)).To(Succeed())
  769. return metric.GetGauge().GetValue()
  770. }, timeout, interval).Should(Equal(0.0))
  771. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1alpha1.ExternalSecretReady, v1.ConditionFalse, 0.0)).To(BeTrue())
  772. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1alpha1.ExternalSecretReady, v1.ConditionTrue, 0.0)).To(BeTrue())
  773. }
  774. }
  775. // When the ownership is set to owner, and we delete a dependent child kind=secret
  776. // it should be recreated without waiting for refresh interval
  777. checkDeletion := func(tc *testCase) {
  778. const secretVal = "someValue"
  779. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  780. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Minute * 10}
  781. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  782. // check values
  783. oldUID := secret.UID
  784. Expect(oldUID).NotTo(BeEmpty())
  785. // delete the related config
  786. Expect(k8sClient.Delete(context.TODO(), secret))
  787. var newSecret v1.Secret
  788. secretLookupKey := types.NamespacedName{
  789. Name: ExternalSecretTargetSecretName,
  790. Namespace: ExternalSecretNamespace,
  791. }
  792. Eventually(func() bool {
  793. err := k8sClient.Get(context.Background(), secretLookupKey, &newSecret)
  794. if err != nil {
  795. return false
  796. }
  797. // new secret should be a new, recreated object with a different UID
  798. return newSecret.UID != oldUID
  799. }, timeout, interval).Should(BeTrue())
  800. }
  801. }
  802. // Checks that secret annotation has been written based on the data
  803. checkSecretDataHashAnnotation := func(tc *testCase) {
  804. const secretVal = "someValue"
  805. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  806. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  807. Expect(secret.Annotations[esv1alpha1.AnnotationDataHash]).To(Equal("9d30b95ca81e156f9454b5ef3bfcc6ee"))
  808. }
  809. }
  810. // When we amend the created kind=secret, refresh operation should be run again regardless of refresh interval
  811. checkSecretDataHashAnnotationChange := func(tc *testCase) {
  812. fakeData := map[string][]byte{
  813. "targetProperty": []byte(FooValue),
  814. }
  815. fakeProvider.WithGetSecretMap(fakeData, nil)
  816. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Minute * 10}
  817. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  818. oldHash := secret.Annotations[esv1alpha1.AnnotationDataHash]
  819. oldResourceVersion := secret.ResourceVersion
  820. Expect(oldHash).NotTo(BeEmpty())
  821. cleanSecret := secret.DeepCopy()
  822. secret.Data["new"] = []byte("value")
  823. secret.ObjectMeta.Annotations[esv1alpha1.AnnotationDataHash] = "thisiswronghash"
  824. Expect(k8sClient.Patch(context.Background(), secret, client.MergeFrom(cleanSecret))).To(Succeed())
  825. var refreshedSecret v1.Secret
  826. secretLookupKey := types.NamespacedName{
  827. Name: ExternalSecretTargetSecretName,
  828. Namespace: ExternalSecretNamespace,
  829. }
  830. Eventually(func() bool {
  831. err := k8sClient.Get(context.Background(), secretLookupKey, &refreshedSecret)
  832. if err != nil {
  833. return false
  834. }
  835. // refreshed secret should have a different generation (sign that it was updated), but since
  836. // the secret source is the same (not changed), the hash should be reverted to an old value
  837. return refreshedSecret.ResourceVersion != oldResourceVersion && refreshedSecret.Annotations[esv1alpha1.AnnotationDataHash] == oldHash
  838. }, timeout, interval).Should(BeTrue())
  839. }
  840. }
  841. DescribeTable("When reconciling an ExternalSecret",
  842. func(tweaks ...testTweaks) {
  843. tc := makeDefaultTestcase()
  844. for _, tweak := range tweaks {
  845. tweak(tc)
  846. }
  847. ctx := context.Background()
  848. By("creating a secret store and external secret")
  849. Expect(k8sClient.Create(ctx, tc.secretStore)).To(Succeed())
  850. Expect(k8sClient.Create(ctx, tc.externalSecret)).Should(Succeed())
  851. esKey := types.NamespacedName{Name: ExternalSecretName, Namespace: ExternalSecretNamespace}
  852. createdES := &esv1alpha1.ExternalSecret{}
  853. By("checking the es condition")
  854. Eventually(func() bool {
  855. err := k8sClient.Get(ctx, esKey, createdES)
  856. if err != nil {
  857. return false
  858. }
  859. return tc.checkCondition(createdES)
  860. }, timeout, interval).Should(BeTrue())
  861. tc.checkExternalSecret(createdES)
  862. // this must be optional so we can test faulty es configuration
  863. if tc.checkSecret != nil {
  864. syncedSecret := &v1.Secret{}
  865. secretLookupKey := types.NamespacedName{
  866. Name: ExternalSecretTargetSecretName,
  867. Namespace: ExternalSecretNamespace,
  868. }
  869. if createdES.Spec.Target.Name == "" {
  870. secretLookupKey = types.NamespacedName{
  871. Name: ExternalSecretName,
  872. Namespace: ExternalSecretNamespace,
  873. }
  874. }
  875. Eventually(func() bool {
  876. err := k8sClient.Get(ctx, secretLookupKey, syncedSecret)
  877. return err == nil
  878. }, timeout, interval).Should(BeTrue())
  879. tc.checkSecret(createdES, syncedSecret)
  880. }
  881. },
  882. Entry("should recreate deleted secret", checkDeletion),
  883. Entry("should create proper hash annotation for the external secret", checkSecretDataHashAnnotation),
  884. Entry("should refresh when the hash annotation doesn't correspond to secret data", checkSecretDataHashAnnotationChange),
  885. Entry("should use external secret name if target secret name isn't defined", syncWithoutTargetName),
  886. Entry("should set the condition eventually", syncLabelsAnnotations),
  887. Entry("should set prometheus counters", checkPrometheusCounters),
  888. Entry("should merge with existing secret using creationPolicy=Merge", mergeWithSecret),
  889. Entry("should error if secret doesn't exist when using creationPolicy=Merge", mergeWithSecretErr),
  890. Entry("should not resolve conflicts with creationPolicy=Merge", mergeWithConflict),
  891. Entry("should not update unchanged secret using creationPolicy=Merge", mergeWithSecretNoChange),
  892. Entry("should sync with template", syncWithTemplate),
  893. Entry("should sync template with correct value precedence", syncWithTemplatePrecedence),
  894. Entry("should refresh secret from template", refreshWithTemplate),
  895. Entry("should be able to use only metadata from template", onlyMetadataFromTemplate),
  896. Entry("should refresh secret value when provider secret changes", refreshSecretValue),
  897. Entry("should not refresh secret value when provider secret changes but refreshInterval is zero", refreshintervalZero),
  898. Entry("should fetch secret using dataFrom", syncWithDataFrom),
  899. Entry("should fetch secret using dataFrom and a template", syncWithDataFromTemplate),
  900. Entry("should set error condition when provider errors", providerErrCondition),
  901. Entry("should set an error condition when store does not exist", storeMissingErrCondition),
  902. Entry("should set an error condition when store provider constructor fails", storeConstructErrCondition),
  903. Entry("should not process store with mismatching controller field", ignoreMismatchController),
  904. )
  905. })
  906. var _ = Describe("ExternalSecret refresh logic", func() {
  907. Context("secret refresh", func() {
  908. It("should refresh when resource version does not match", func() {
  909. Expect(shouldRefresh(esv1alpha1.ExternalSecret{
  910. Status: esv1alpha1.ExternalSecretStatus{
  911. SyncedResourceVersion: "some resource version",
  912. },
  913. })).To(BeTrue())
  914. })
  915. It("should refresh when labels change", func() {
  916. es := esv1alpha1.ExternalSecret{
  917. ObjectMeta: metav1.ObjectMeta{
  918. Generation: 1,
  919. Labels: map[string]string{
  920. "foo": "bar",
  921. },
  922. },
  923. Spec: esv1alpha1.ExternalSecretSpec{
  924. RefreshInterval: &metav1.Duration{Duration: time.Minute},
  925. },
  926. Status: esv1alpha1.ExternalSecretStatus{
  927. RefreshTime: metav1.Now(),
  928. },
  929. }
  930. es.Status.SyncedResourceVersion = getResourceVersion(es)
  931. // this should not refresh, rv matches object
  932. Expect(shouldRefresh(es)).To(BeFalse())
  933. // change labels without changing the syncedResourceVersion and expect refresh
  934. es.ObjectMeta.Labels["new"] = "w00t"
  935. Expect(shouldRefresh(es)).To(BeTrue())
  936. })
  937. It("should refresh when annotations change", func() {
  938. es := esv1alpha1.ExternalSecret{
  939. ObjectMeta: metav1.ObjectMeta{
  940. Generation: 1,
  941. Annotations: map[string]string{
  942. "foo": "bar",
  943. },
  944. },
  945. Spec: esv1alpha1.ExternalSecretSpec{
  946. RefreshInterval: &metav1.Duration{Duration: time.Minute},
  947. },
  948. Status: esv1alpha1.ExternalSecretStatus{
  949. RefreshTime: metav1.Now(),
  950. },
  951. }
  952. es.Status.SyncedResourceVersion = getResourceVersion(es)
  953. // this should not refresh, rv matches object
  954. Expect(shouldRefresh(es)).To(BeFalse())
  955. // change annotations without changing the syncedResourceVersion and expect refresh
  956. es.ObjectMeta.Annotations["new"] = "w00t"
  957. Expect(shouldRefresh(es)).To(BeTrue())
  958. })
  959. It("should refresh when generation has changed", func() {
  960. es := esv1alpha1.ExternalSecret{
  961. ObjectMeta: metav1.ObjectMeta{
  962. Generation: 1,
  963. },
  964. Spec: esv1alpha1.ExternalSecretSpec{
  965. RefreshInterval: &metav1.Duration{Duration: 0},
  966. },
  967. Status: esv1alpha1.ExternalSecretStatus{
  968. RefreshTime: metav1.Now(),
  969. },
  970. }
  971. es.Status.SyncedResourceVersion = getResourceVersion(es)
  972. Expect(shouldRefresh(es)).To(BeFalse())
  973. // update gen -> refresh
  974. es.ObjectMeta.Generation = 2
  975. Expect(shouldRefresh(es)).To(BeTrue())
  976. })
  977. It("should skip refresh when refreshInterval is 0", func() {
  978. es := esv1alpha1.ExternalSecret{
  979. ObjectMeta: metav1.ObjectMeta{
  980. Generation: 1,
  981. },
  982. Spec: esv1alpha1.ExternalSecretSpec{
  983. RefreshInterval: &metav1.Duration{Duration: 0},
  984. },
  985. Status: esv1alpha1.ExternalSecretStatus{},
  986. }
  987. // resource version matches
  988. es.Status.SyncedResourceVersion = getResourceVersion(es)
  989. Expect(shouldRefresh(es)).To(BeFalse())
  990. })
  991. It("should refresh when refresh interval has passed", func() {
  992. es := esv1alpha1.ExternalSecret{
  993. ObjectMeta: metav1.ObjectMeta{
  994. Generation: 1,
  995. },
  996. Spec: esv1alpha1.ExternalSecretSpec{
  997. RefreshInterval: &metav1.Duration{Duration: time.Second},
  998. },
  999. Status: esv1alpha1.ExternalSecretStatus{
  1000. RefreshTime: metav1.NewTime(metav1.Now().Add(-time.Second * 5)),
  1001. },
  1002. }
  1003. // resource version matches
  1004. es.Status.SyncedResourceVersion = getResourceVersion(es)
  1005. Expect(shouldRefresh(es)).To(BeTrue())
  1006. })
  1007. It("should refresh when no refresh time was set", func() {
  1008. es := esv1alpha1.ExternalSecret{
  1009. ObjectMeta: metav1.ObjectMeta{
  1010. Generation: 1,
  1011. },
  1012. Spec: esv1alpha1.ExternalSecretSpec{
  1013. RefreshInterval: &metav1.Duration{Duration: time.Second},
  1014. },
  1015. Status: esv1alpha1.ExternalSecretStatus{},
  1016. }
  1017. // resource version matches
  1018. es.Status.SyncedResourceVersion = getResourceVersion(es)
  1019. Expect(shouldRefresh(es)).To(BeTrue())
  1020. })
  1021. })
  1022. Context("objectmeta hash", func() {
  1023. It("should produce different hashes for different k/v pairs", func() {
  1024. h1 := hashMeta(metav1.ObjectMeta{
  1025. Generation: 1,
  1026. Annotations: map[string]string{
  1027. "foo": "bar",
  1028. },
  1029. })
  1030. h2 := hashMeta(metav1.ObjectMeta{
  1031. Generation: 1,
  1032. Annotations: map[string]string{
  1033. "foo": "bing",
  1034. },
  1035. })
  1036. Expect(h1).ToNot(Equal(h2))
  1037. })
  1038. It("should produce different hashes for different generations but same label/annotations", func() {
  1039. h1 := hashMeta(metav1.ObjectMeta{
  1040. Generation: 1,
  1041. Annotations: map[string]string{
  1042. "foo": "bar",
  1043. },
  1044. Labels: map[string]string{
  1045. "foo": "bar",
  1046. },
  1047. })
  1048. h2 := hashMeta(metav1.ObjectMeta{
  1049. Generation: 2,
  1050. Annotations: map[string]string{
  1051. "foo": "bar",
  1052. },
  1053. Labels: map[string]string{
  1054. "foo": "bar",
  1055. },
  1056. })
  1057. Expect(h1).To(Equal(h2))
  1058. })
  1059. It("should produce the same hash for the same k/v pairs", func() {
  1060. h1 := hashMeta(metav1.ObjectMeta{
  1061. Generation: 1,
  1062. })
  1063. h2 := hashMeta(metav1.ObjectMeta{
  1064. Generation: 1,
  1065. })
  1066. Expect(h1).To(Equal(h2))
  1067. h1 = hashMeta(metav1.ObjectMeta{
  1068. Generation: 1,
  1069. Annotations: map[string]string{
  1070. "foo": "bar",
  1071. },
  1072. })
  1073. h2 = hashMeta(metav1.ObjectMeta{
  1074. Generation: 1,
  1075. Annotations: map[string]string{
  1076. "foo": "bar",
  1077. },
  1078. })
  1079. Expect(h1).To(Equal(h2))
  1080. })
  1081. })
  1082. })
  1083. var _ = Describe("Controller Reconcile logic", func() {
  1084. Context("controller reconcile", func() {
  1085. It("should reconcile when resource is not synced", func() {
  1086. Expect(shouldReconcile(esv1alpha1.ExternalSecret{
  1087. Status: esv1alpha1.ExternalSecretStatus{
  1088. SyncedResourceVersion: "some resource version",
  1089. Conditions: []esv1alpha1.ExternalSecretStatusCondition{{Reason: "NotASecretSynced"}},
  1090. },
  1091. })).To(BeTrue())
  1092. })
  1093. It("should reconcile when secret isn't immutable", func() {
  1094. Expect(shouldReconcile(esv1alpha1.ExternalSecret{
  1095. Spec: esv1alpha1.ExternalSecretSpec{
  1096. Target: esv1alpha1.ExternalSecretTarget{
  1097. Immutable: false,
  1098. },
  1099. },
  1100. })).To(BeTrue())
  1101. })
  1102. It("should not reconcile if secret is immutable and has synced condition", func() {
  1103. Expect(shouldReconcile(esv1alpha1.ExternalSecret{
  1104. Spec: esv1alpha1.ExternalSecretSpec{
  1105. Target: esv1alpha1.ExternalSecretTarget{
  1106. Immutable: true,
  1107. },
  1108. },
  1109. Status: esv1alpha1.ExternalSecretStatus{
  1110. SyncedResourceVersion: "some resource version",
  1111. Conditions: []esv1alpha1.ExternalSecretStatusCondition{{Reason: "SecretSynced"}},
  1112. },
  1113. })).To(BeFalse())
  1114. })
  1115. })
  1116. })
  1117. // CreateNamespace creates a new namespace in the cluster.
  1118. func CreateNamespace(baseName string, c client.Client) (string, error) {
  1119. genName := fmt.Sprintf("ctrl-test-%v", baseName)
  1120. ns := &v1.Namespace{
  1121. ObjectMeta: metav1.ObjectMeta{
  1122. GenerateName: genName,
  1123. },
  1124. }
  1125. var err error
  1126. err = wait.Poll(time.Second, 10*time.Second, func() (bool, error) {
  1127. err = c.Create(context.Background(), ns)
  1128. if err != nil {
  1129. return false, nil
  1130. }
  1131. return true, nil
  1132. })
  1133. if err != nil {
  1134. return "", err
  1135. }
  1136. return ns.Name, nil
  1137. }
  1138. func hasOwnerRef(meta metav1.ObjectMeta, kind, name string) bool {
  1139. for _, ref := range meta.OwnerReferences {
  1140. if ref.Kind == kind && ref.Name == name {
  1141. return true
  1142. }
  1143. }
  1144. return false
  1145. }
  1146. func hasFieldOwnership(meta metav1.ObjectMeta, mgr, rawFields string) bool {
  1147. for _, ref := range meta.ManagedFields {
  1148. if ref.Manager == mgr && string(ref.FieldsV1.Raw) == rawFields {
  1149. return true
  1150. }
  1151. }
  1152. return false
  1153. }
  1154. func externalSecretConditionShouldBe(name, ns string, ct esv1alpha1.ExternalSecretConditionType, cs v1.ConditionStatus, v float64) bool {
  1155. return Eventually(func() float64 {
  1156. Expect(externalSecretCondition.WithLabelValues(name, ns, string(ct), string(cs)).Write(&metric)).To(Succeed())
  1157. return metric.GetGauge().GetValue()
  1158. }, timeout, interval).Should(Equal(v))
  1159. }
  1160. func init() {
  1161. fakeProvider = fake.New()
  1162. schema.ForceRegister(fakeProvider, &esv1alpha1.SecretStoreProvider{
  1163. AWS: &esv1alpha1.AWSProvider{
  1164. Service: esv1alpha1.AWSServiceSecretsManager,
  1165. },
  1166. })
  1167. }