externalsecret_controller_test.go 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224
  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 merge with secret if it doesn't exist
  293. mergeWithSecretErr := func(tc *testCase) {
  294. const secretVal = "someValue"
  295. tc.externalSecret.Spec.Target.CreationPolicy = esv1alpha1.Merge
  296. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  297. tc.checkCondition = func(es *esv1alpha1.ExternalSecret) bool {
  298. cond := GetExternalSecretCondition(es.Status, esv1alpha1.ExternalSecretReady)
  299. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1alpha1.ConditionReasonSecretSyncedError {
  300. return false
  301. }
  302. return true
  303. }
  304. tc.checkExternalSecret = func(es *esv1alpha1.ExternalSecret) {
  305. Eventually(func() bool {
  306. Expect(syncCallsError.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metric)).To(Succeed())
  307. return metric.GetCounter().GetValue() >= 2.0
  308. }, timeout, interval).Should(BeTrue())
  309. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1alpha1.ExternalSecretReady, v1.ConditionFalse, 1.0)).To(BeTrue())
  310. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1alpha1.ExternalSecretReady, v1.ConditionTrue, 0.0)).To(BeTrue())
  311. }
  312. }
  313. // controller should force ownership
  314. mergeWithConflict := func(tc *testCase) {
  315. const secretVal = "someValue"
  316. // this should confict
  317. const existingKey = targetProp
  318. existingVal := "pre-existing-value"
  319. tc.externalSecret.Spec.Target.CreationPolicy = esv1alpha1.Merge
  320. // create secret beforehand
  321. Expect(k8sClient.Create(context.Background(), &v1.Secret{
  322. ObjectMeta: metav1.ObjectMeta{
  323. Name: ExternalSecretTargetSecretName,
  324. Namespace: ExternalSecretNamespace,
  325. },
  326. Data: map[string][]byte{
  327. existingKey: []byte(existingVal),
  328. },
  329. }, client.FieldOwner(FakeManager))).To(Succeed())
  330. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  331. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  332. // check that value stays the same
  333. Expect(string(secret.Data[existingKey])).To(Equal(secretVal))
  334. // check owner/managedFields
  335. Expect(hasOwnerRef(secret.ObjectMeta, "ExternalSecret", ExternalSecretName)).To(BeFalse())
  336. Expect(secret.ObjectMeta.ManagedFields).To(HaveLen(2))
  337. 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())
  338. }
  339. }
  340. // when using a template it should be used as a blueprint
  341. // to construct a new secret: labels, annotations and type
  342. syncWithTemplate := func(tc *testCase) {
  343. const secretVal = "someValue"
  344. const tplStaticKey = "tplstatickey"
  345. const tplStaticVal = "tplstaticvalue"
  346. tc.externalSecret.ObjectMeta.Labels = map[string]string{
  347. "fooobar": "bazz",
  348. }
  349. tc.externalSecret.ObjectMeta.Annotations = map[string]string{
  350. "hihihih": "hehehe",
  351. }
  352. tc.externalSecret.Spec.Target.Template = &esv1alpha1.ExternalSecretTemplate{
  353. Metadata: esv1alpha1.ExternalSecretTemplateMetadata{
  354. Labels: map[string]string{
  355. "foos": "ball",
  356. },
  357. Annotations: map[string]string{
  358. "hihi": "ga",
  359. },
  360. },
  361. Type: v1.SecretTypeOpaque,
  362. Data: map[string]string{
  363. targetProp: targetPropObj,
  364. tplStaticKey: tplStaticVal,
  365. },
  366. }
  367. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  368. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  369. // check values
  370. Expect(string(secret.Data[targetProp])).To(Equal(expectedSecretVal))
  371. Expect(string(secret.Data[tplStaticKey])).To(Equal(tplStaticVal))
  372. // labels/annotations should be taken from the template
  373. Expect(secret.ObjectMeta.Labels).To(BeEquivalentTo(es.Spec.Target.Template.Metadata.Labels))
  374. for k, v := range es.Spec.Target.Template.Metadata.Annotations {
  375. Expect(secret.ObjectMeta.Annotations).To(HaveKeyWithValue(k, v))
  376. }
  377. }
  378. }
  379. // secret should be synced with correct value precedence:
  380. // * template
  381. // * templateFrom
  382. // * data
  383. // * dataFrom
  384. syncWithTemplatePrecedence := func(tc *testCase) {
  385. const secretVal = "someValue"
  386. const tplStaticKey = "tplstatickey"
  387. const tplStaticVal = "tplstaticvalue"
  388. const tplFromCMName = "template-cm"
  389. const tplFromSecretName = "template-secret"
  390. const tplFromKey = "tpl-from-key"
  391. const tplFromSecKey = "tpl-from-sec-key"
  392. const tplFromVal = "tpl-from-value: {{ .targetProperty | toString }} // {{ .bar | toString }}"
  393. const tplFromSecVal = "tpl-from-sec-value: {{ .targetProperty | toString }} // {{ .bar | toString }}"
  394. Expect(k8sClient.Create(context.Background(), &v1.ConfigMap{
  395. ObjectMeta: metav1.ObjectMeta{
  396. Name: tplFromCMName,
  397. Namespace: ExternalSecretNamespace,
  398. },
  399. Data: map[string]string{
  400. tplFromKey: tplFromVal,
  401. },
  402. })).To(Succeed())
  403. Expect(k8sClient.Create(context.Background(), &v1.Secret{
  404. ObjectMeta: metav1.ObjectMeta{
  405. Name: tplFromSecretName,
  406. Namespace: ExternalSecretNamespace,
  407. },
  408. Data: map[string][]byte{
  409. tplFromSecKey: []byte(tplFromSecVal),
  410. },
  411. })).To(Succeed())
  412. tc.externalSecret.Spec.Target.Template = &esv1alpha1.ExternalSecretTemplate{
  413. Metadata: esv1alpha1.ExternalSecretTemplateMetadata{},
  414. Type: v1.SecretTypeOpaque,
  415. TemplateFrom: []esv1alpha1.TemplateFrom{
  416. {
  417. ConfigMap: &esv1alpha1.TemplateRef{
  418. Name: tplFromCMName,
  419. Items: []esv1alpha1.TemplateRefItem{
  420. {
  421. Key: tplFromKey,
  422. },
  423. },
  424. },
  425. },
  426. {
  427. Secret: &esv1alpha1.TemplateRef{
  428. Name: tplFromSecretName,
  429. Items: []esv1alpha1.TemplateRefItem{
  430. {
  431. Key: tplFromSecKey,
  432. },
  433. },
  434. },
  435. },
  436. },
  437. Data: map[string]string{
  438. // this should be the data value, not dataFrom
  439. targetProp: targetPropObj,
  440. // this should use the value from the map
  441. "bar": "value from map: {{ .bar | toString }}",
  442. // just a static value
  443. tplStaticKey: tplStaticVal,
  444. },
  445. }
  446. tc.externalSecret.Spec.DataFrom = []esv1alpha1.ExternalSecretDataRemoteRef{
  447. {
  448. Key: "datamap",
  449. },
  450. }
  451. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  452. fakeProvider.WithGetSecretMap(map[string][]byte{
  453. "targetProperty": []byte(FooValue),
  454. "bar": []byte(BarValue),
  455. }, nil)
  456. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  457. // check values
  458. Expect(string(secret.Data[targetProp])).To(Equal(expectedSecretVal))
  459. Expect(string(secret.Data[tplStaticKey])).To(Equal(tplStaticVal))
  460. Expect(string(secret.Data["bar"])).To(Equal("value from map: map-bar-value"))
  461. Expect(string(secret.Data[tplFromKey])).To(Equal("tpl-from-value: someValue // map-bar-value"))
  462. Expect(string(secret.Data[tplFromSecKey])).To(Equal("tpl-from-sec-value: someValue // map-bar-value"))
  463. }
  464. }
  465. refreshWithTemplate := func(tc *testCase) {
  466. const secretVal = "someValue"
  467. const tplStaticKey = "tplstatickey"
  468. const tplStaticVal = "tplstaticvalue"
  469. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Second}
  470. tc.externalSecret.Spec.Target.Template = &esv1alpha1.ExternalSecretTemplate{
  471. Metadata: esv1alpha1.ExternalSecretTemplateMetadata{
  472. Labels: map[string]string{"foo": "bar"},
  473. Annotations: map[string]string{"foo": "bar"},
  474. },
  475. Type: v1.SecretTypeOpaque,
  476. Data: map[string]string{
  477. targetProp: targetPropObj,
  478. tplStaticKey: tplStaticVal,
  479. },
  480. }
  481. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  482. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  483. // check values
  484. Expect(string(secret.Data[targetProp])).To(Equal(expectedSecretVal))
  485. Expect(string(secret.Data[tplStaticKey])).To(Equal(tplStaticVal))
  486. // labels/annotations should be taken from the template
  487. Expect(secret.ObjectMeta.Labels).To(BeEquivalentTo(es.Spec.Target.Template.Metadata.Labels))
  488. // a secret will always have some extra annotations (i.e. hashmap check), so we only check for specific
  489. // source annotations
  490. for k, v := range es.Spec.Target.Template.Metadata.Annotations {
  491. Expect(secret.ObjectMeta.Annotations).To(HaveKeyWithValue(k, v))
  492. }
  493. cleanEs := tc.externalSecret.DeepCopy()
  494. // now update ExternalSecret
  495. tc.externalSecret.Spec.Target.Template.Metadata.Annotations["fuzz"] = "buzz"
  496. tc.externalSecret.Spec.Target.Template.Metadata.Labels["fuzz"] = "buzz"
  497. tc.externalSecret.Spec.Target.Template.Data["new"] = "value"
  498. Expect(k8sClient.Patch(context.Background(), tc.externalSecret, client.MergeFrom(cleanEs))).To(Succeed())
  499. // wait for secret
  500. sec := &v1.Secret{}
  501. secretLookupKey := types.NamespacedName{
  502. Name: ExternalSecretTargetSecretName,
  503. Namespace: ExternalSecretNamespace,
  504. }
  505. Eventually(func() bool {
  506. err := k8sClient.Get(context.Background(), secretLookupKey, sec)
  507. if err != nil {
  508. return false
  509. }
  510. // ensure new data value exist
  511. return string(sec.Data["new"]) == "value"
  512. }, time.Second*10, time.Millisecond*200).Should(BeTrue())
  513. // also check labels/annotations have been updated
  514. Expect(secret.ObjectMeta.Labels).To(BeEquivalentTo(es.Spec.Target.Template.Metadata.Labels))
  515. for k, v := range es.Spec.Target.Template.Metadata.Annotations {
  516. Expect(secret.ObjectMeta.Annotations).To(HaveKeyWithValue(k, v))
  517. }
  518. }
  519. }
  520. onlyMetadataFromTemplate := func(tc *testCase) {
  521. const secretVal = "someValue"
  522. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Second}
  523. tc.externalSecret.Spec.Target.Template = &esv1alpha1.ExternalSecretTemplate{
  524. Metadata: esv1alpha1.ExternalSecretTemplateMetadata{
  525. Labels: map[string]string{"foo": "bar"},
  526. Annotations: map[string]string{"foo": "bar"},
  527. },
  528. }
  529. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  530. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  531. // check values
  532. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  533. // labels/annotations should be taken from the template
  534. Expect(secret.ObjectMeta.Labels).To(BeEquivalentTo(es.Spec.Target.Template.Metadata.Labels))
  535. for k, v := range es.Spec.Target.Template.Metadata.Annotations {
  536. Expect(secret.ObjectMeta.Annotations).To(HaveKeyWithValue(k, v))
  537. }
  538. }
  539. }
  540. // when the provider secret changes the Kind=Secret value
  541. // must change, too.
  542. refreshSecretValue := func(tc *testCase) {
  543. const targetProp = "targetProperty"
  544. const secretVal = "someValue"
  545. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  546. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Second}
  547. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  548. // check values
  549. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  550. // update provider secret
  551. newValue := "NEW VALUE"
  552. sec := &v1.Secret{}
  553. fakeProvider.WithGetSecret([]byte(newValue), nil)
  554. secretLookupKey := types.NamespacedName{
  555. Name: ExternalSecretTargetSecretName,
  556. Namespace: ExternalSecretNamespace,
  557. }
  558. Eventually(func() bool {
  559. err := k8sClient.Get(context.Background(), secretLookupKey, sec)
  560. if err != nil {
  561. return false
  562. }
  563. v := sec.Data[targetProp]
  564. return string(v) == newValue
  565. }, timeout, interval).Should(BeTrue())
  566. }
  567. }
  568. refreshintervalZero := func(tc *testCase) {
  569. const targetProp = "targetProperty"
  570. const secretVal = "someValue"
  571. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  572. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: 0}
  573. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  574. // check values
  575. Expect(string(secret.Data[targetProp])).To(Equal(secretVal))
  576. // update provider secret
  577. newValue := "NEW VALUE"
  578. sec := &v1.Secret{}
  579. fakeProvider.WithGetSecret([]byte(newValue), nil)
  580. secretLookupKey := types.NamespacedName{
  581. Name: ExternalSecretTargetSecretName,
  582. Namespace: ExternalSecretNamespace,
  583. }
  584. Consistently(func() bool {
  585. err := k8sClient.Get(context.Background(), secretLookupKey, sec)
  586. if err != nil {
  587. return false
  588. }
  589. v := sec.Data[targetProp]
  590. return string(v) == secretVal
  591. }, time.Second*10, time.Second).Should(BeTrue())
  592. }
  593. }
  594. // with dataFrom all properties from the specified secret
  595. // should be put into the secret
  596. syncWithDataFrom := func(tc *testCase) {
  597. tc.externalSecret.Spec.Data = nil
  598. tc.externalSecret.Spec.DataFrom = []esv1alpha1.ExternalSecretDataRemoteRef{
  599. {
  600. Key: remoteKey,
  601. },
  602. }
  603. fakeProvider.WithGetSecretMap(map[string][]byte{
  604. "foo": []byte(FooValue),
  605. "bar": []byte(BarValue),
  606. }, nil)
  607. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  608. // check values
  609. Expect(string(secret.Data["foo"])).To(Equal(FooValue))
  610. Expect(string(secret.Data["bar"])).To(Equal(BarValue))
  611. }
  612. }
  613. // with dataFrom and using a template
  614. // should be put into the secret
  615. syncWithDataFromTemplate := func(tc *testCase) {
  616. tc.externalSecret.Spec.Data = nil
  617. tc.externalSecret.Spec.Target = esv1alpha1.ExternalSecretTarget{
  618. Name: ExternalSecretTargetSecretName,
  619. Template: &esv1alpha1.ExternalSecretTemplate{
  620. Type: v1.SecretTypeTLS,
  621. },
  622. }
  623. tc.externalSecret.Spec.DataFrom = []esv1alpha1.ExternalSecretDataRemoteRef{
  624. {
  625. Key: remoteKey,
  626. },
  627. }
  628. fakeProvider.WithGetSecretMap(map[string][]byte{
  629. "tls.crt": []byte(FooValue),
  630. "tls.key": []byte(BarValue),
  631. }, nil)
  632. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  633. Expect(secret.Type).To(Equal(v1.SecretTypeTLS))
  634. // check values
  635. Expect(string(secret.Data["tls.crt"])).To(Equal(FooValue))
  636. Expect(string(secret.Data["tls.key"])).To(Equal(BarValue))
  637. }
  638. }
  639. // when a provider errors in a GetSecret call
  640. // a error condition must be set.
  641. providerErrCondition := func(tc *testCase) {
  642. const secretVal = "foobar"
  643. fakeProvider.WithGetSecret(nil, fmt.Errorf("boom"))
  644. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Millisecond * 100}
  645. tc.checkCondition = func(es *esv1alpha1.ExternalSecret) bool {
  646. cond := GetExternalSecretCondition(es.Status, esv1alpha1.ExternalSecretReady)
  647. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1alpha1.ConditionReasonSecretSyncedError {
  648. return false
  649. }
  650. return true
  651. }
  652. tc.checkExternalSecret = func(es *esv1alpha1.ExternalSecret) {
  653. Eventually(func() bool {
  654. Expect(syncCallsError.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metric)).To(Succeed())
  655. return metric.GetCounter().GetValue() >= 2.0
  656. }, timeout, interval).Should(BeTrue())
  657. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1alpha1.ExternalSecretReady, v1.ConditionFalse, 1.0)).To(BeTrue())
  658. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1alpha1.ExternalSecretReady, v1.ConditionTrue, 0.0)).To(BeTrue())
  659. // es condition should reflect recovered provider error
  660. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  661. esKey := types.NamespacedName{Name: ExternalSecretName, Namespace: ExternalSecretNamespace}
  662. Eventually(func() bool {
  663. err := k8sClient.Get(context.Background(), esKey, es)
  664. if err != nil {
  665. return false
  666. }
  667. // condition must now be true!
  668. cond := GetExternalSecretCondition(es.Status, esv1alpha1.ExternalSecretReady)
  669. if cond == nil && cond.Status != v1.ConditionTrue {
  670. return false
  671. }
  672. return true
  673. }, timeout, interval).Should(BeTrue())
  674. }
  675. }
  676. // When a ExternalSecret references an non-existing SecretStore
  677. // a error condition must be set.
  678. storeMissingErrCondition := func(tc *testCase) {
  679. tc.externalSecret.Spec.SecretStoreRef.Name = "nonexistent"
  680. tc.checkCondition = func(es *esv1alpha1.ExternalSecret) bool {
  681. cond := GetExternalSecretCondition(es.Status, esv1alpha1.ExternalSecretReady)
  682. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1alpha1.ConditionReasonSecretSyncedError {
  683. return false
  684. }
  685. return true
  686. }
  687. tc.checkExternalSecret = func(es *esv1alpha1.ExternalSecret) {
  688. Eventually(func() bool {
  689. Expect(syncCallsError.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metric)).To(Succeed())
  690. return metric.GetCounter().GetValue() >= 2.0
  691. }, timeout, interval).Should(BeTrue())
  692. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1alpha1.ExternalSecretReady, v1.ConditionFalse, 1.0)).To(BeTrue())
  693. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1alpha1.ExternalSecretReady, v1.ConditionTrue, 0.0)).To(BeTrue())
  694. }
  695. }
  696. // when the provider constructor errors (e.g. invalid configuration)
  697. // a SecretSyncedError status condition must be set
  698. storeConstructErrCondition := func(tc *testCase) {
  699. fakeProvider.WithNew(func(context.Context, esv1alpha1.GenericStore, client.Client,
  700. string) (provider.SecretsClient, error) {
  701. return nil, fmt.Errorf("artificial constructor error")
  702. })
  703. tc.checkCondition = func(es *esv1alpha1.ExternalSecret) bool {
  704. // condition must be false
  705. cond := GetExternalSecretCondition(es.Status, esv1alpha1.ExternalSecretReady)
  706. if cond == nil || cond.Status != v1.ConditionFalse || cond.Reason != esv1alpha1.ConditionReasonSecretSyncedError {
  707. return false
  708. }
  709. return true
  710. }
  711. tc.checkExternalSecret = func(es *esv1alpha1.ExternalSecret) {
  712. Eventually(func() bool {
  713. Expect(syncCallsError.WithLabelValues(ExternalSecretName, ExternalSecretNamespace).Write(&metric)).To(Succeed())
  714. return metric.GetCounter().GetValue() >= 2.0
  715. }, timeout, interval).Should(BeTrue())
  716. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1alpha1.ExternalSecretReady, v1.ConditionFalse, 1.0)).To(BeTrue())
  717. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1alpha1.ExternalSecretReady, v1.ConditionTrue, 0.0)).To(BeTrue())
  718. }
  719. }
  720. // when a SecretStore has a controller field set which we don't care about
  721. // the externalSecret must not be touched
  722. ignoreMismatchController := func(tc *testCase) {
  723. tc.secretStore.Spec.Controller = "nop"
  724. tc.checkCondition = func(es *esv1alpha1.ExternalSecret) bool {
  725. cond := GetExternalSecretCondition(es.Status, esv1alpha1.ExternalSecretReady)
  726. return cond == nil
  727. }
  728. tc.checkExternalSecret = func(es *esv1alpha1.ExternalSecret) {
  729. // Condition True and False should be 0, since the Condition was not created
  730. Eventually(func() float64 {
  731. Expect(externalSecretCondition.WithLabelValues(ExternalSecretName, ExternalSecretNamespace, string(esv1alpha1.ExternalSecretReady), string(v1.ConditionTrue)).Write(&metric)).To(Succeed())
  732. return metric.GetGauge().GetValue()
  733. }, timeout, interval).Should(Equal(0.0))
  734. Eventually(func() float64 {
  735. Expect(externalSecretCondition.WithLabelValues(ExternalSecretName, ExternalSecretNamespace, string(esv1alpha1.ExternalSecretReady), string(v1.ConditionFalse)).Write(&metric)).To(Succeed())
  736. return metric.GetGauge().GetValue()
  737. }, timeout, interval).Should(Equal(0.0))
  738. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1alpha1.ExternalSecretReady, v1.ConditionFalse, 0.0)).To(BeTrue())
  739. Expect(externalSecretConditionShouldBe(ExternalSecretName, ExternalSecretNamespace, esv1alpha1.ExternalSecretReady, v1.ConditionTrue, 0.0)).To(BeTrue())
  740. }
  741. }
  742. // When the ownership is set to owner, and we delete a dependent child kind=secret
  743. // it should be recreated without waiting for refresh interval
  744. checkDeletion := func(tc *testCase) {
  745. const secretVal = "someValue"
  746. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  747. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Minute * 10}
  748. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  749. // check values
  750. oldUID := secret.UID
  751. Expect(oldUID).NotTo(BeEmpty())
  752. // delete the related config
  753. Expect(k8sClient.Delete(context.TODO(), secret))
  754. var newSecret v1.Secret
  755. secretLookupKey := types.NamespacedName{
  756. Name: ExternalSecretTargetSecretName,
  757. Namespace: ExternalSecretNamespace,
  758. }
  759. Eventually(func() bool {
  760. err := k8sClient.Get(context.Background(), secretLookupKey, &newSecret)
  761. if err != nil {
  762. return false
  763. }
  764. // new secret should be a new, recreated object with a different UID
  765. return newSecret.UID != oldUID
  766. }, timeout, interval).Should(BeTrue())
  767. }
  768. }
  769. // Checks that secret annotation has been written based on the data
  770. checkSecretDataHashAnnotation := func(tc *testCase) {
  771. const secretVal = "someValue"
  772. fakeProvider.WithGetSecret([]byte(secretVal), nil)
  773. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  774. Expect(secret.Annotations[esv1alpha1.AnnotationDataHash]).To(Equal("9d30b95ca81e156f9454b5ef3bfcc6ee"))
  775. }
  776. }
  777. // When we amend the created kind=secret, refresh operation should be run again regardless of refresh interval
  778. checkSecretDataHashAnnotationChange := func(tc *testCase) {
  779. fakeData := map[string][]byte{
  780. "targetProperty": []byte(FooValue),
  781. }
  782. fakeProvider.WithGetSecretMap(fakeData, nil)
  783. tc.externalSecret.Spec.RefreshInterval = &metav1.Duration{Duration: time.Minute * 10}
  784. tc.checkSecret = func(es *esv1alpha1.ExternalSecret, secret *v1.Secret) {
  785. oldHash := secret.Annotations[esv1alpha1.AnnotationDataHash]
  786. oldResourceVersion := secret.ResourceVersion
  787. Expect(oldHash).NotTo(BeEmpty())
  788. cleanSecret := secret.DeepCopy()
  789. secret.Data["new"] = []byte("value")
  790. secret.ObjectMeta.Annotations[esv1alpha1.AnnotationDataHash] = "thisiswronghash"
  791. Expect(k8sClient.Patch(context.Background(), secret, client.MergeFrom(cleanSecret))).To(Succeed())
  792. var refreshedSecret v1.Secret
  793. secretLookupKey := types.NamespacedName{
  794. Name: ExternalSecretTargetSecretName,
  795. Namespace: ExternalSecretNamespace,
  796. }
  797. Eventually(func() bool {
  798. err := k8sClient.Get(context.Background(), secretLookupKey, &refreshedSecret)
  799. if err != nil {
  800. return false
  801. }
  802. // refreshed secret should have a different generation (sign that it was updated), but since
  803. // the secret source is the same (not changed), the hash should be reverted to an old value
  804. return refreshedSecret.ResourceVersion != oldResourceVersion && refreshedSecret.Annotations[esv1alpha1.AnnotationDataHash] == oldHash
  805. }, timeout, interval).Should(BeTrue())
  806. }
  807. }
  808. DescribeTable("When reconciling an ExternalSecret",
  809. func(tweaks ...testTweaks) {
  810. tc := makeDefaultTestcase()
  811. for _, tweak := range tweaks {
  812. tweak(tc)
  813. }
  814. ctx := context.Background()
  815. By("creating a secret store and external secret")
  816. Expect(k8sClient.Create(ctx, tc.secretStore)).To(Succeed())
  817. Expect(k8sClient.Create(ctx, tc.externalSecret)).Should(Succeed())
  818. esKey := types.NamespacedName{Name: ExternalSecretName, Namespace: ExternalSecretNamespace}
  819. createdES := &esv1alpha1.ExternalSecret{}
  820. By("checking the es condition")
  821. Eventually(func() bool {
  822. err := k8sClient.Get(ctx, esKey, createdES)
  823. if err != nil {
  824. return false
  825. }
  826. return tc.checkCondition(createdES)
  827. }, timeout, interval).Should(BeTrue())
  828. tc.checkExternalSecret(createdES)
  829. // this must be optional so we can test faulty es configuration
  830. if tc.checkSecret != nil {
  831. syncedSecret := &v1.Secret{}
  832. secretLookupKey := types.NamespacedName{
  833. Name: ExternalSecretTargetSecretName,
  834. Namespace: ExternalSecretNamespace,
  835. }
  836. if createdES.Spec.Target.Name == "" {
  837. secretLookupKey = types.NamespacedName{
  838. Name: ExternalSecretName,
  839. Namespace: ExternalSecretNamespace,
  840. }
  841. }
  842. Eventually(func() bool {
  843. err := k8sClient.Get(ctx, secretLookupKey, syncedSecret)
  844. return err == nil
  845. }, timeout, interval).Should(BeTrue())
  846. tc.checkSecret(createdES, syncedSecret)
  847. }
  848. },
  849. Entry("should recreate deleted secret", checkDeletion),
  850. Entry("should create proper hash annotation for the external secret", checkSecretDataHashAnnotation),
  851. Entry("should refresh when the hash annotation doesn't correspond to secret data", checkSecretDataHashAnnotationChange),
  852. Entry("should use external secret name if target secret name isn't defined", syncWithoutTargetName),
  853. Entry("should set the condition eventually", syncLabelsAnnotations),
  854. Entry("should set prometheus counters", checkPrometheusCounters),
  855. Entry("should merge with existing secret using creationPolicy=Merge", mergeWithSecret),
  856. Entry("should error if secret doesn't exist when using creationPolicy=Merge", mergeWithSecretErr),
  857. Entry("should not resolve conflicts with creationPolicy=Merge", mergeWithConflict),
  858. Entry("should sync with template", syncWithTemplate),
  859. Entry("should sync template with correct value precedence", syncWithTemplatePrecedence),
  860. Entry("should refresh secret from template", refreshWithTemplate),
  861. Entry("should be able to use only metadata from template", onlyMetadataFromTemplate),
  862. Entry("should refresh secret value when provider secret changes", refreshSecretValue),
  863. Entry("should not refresh secret value when provider secret changes but refreshInterval is zero", refreshintervalZero),
  864. Entry("should fetch secret using dataFrom", syncWithDataFrom),
  865. Entry("should fetch secret using dataFrom and a template", syncWithDataFromTemplate),
  866. Entry("should set error condition when provider errors", providerErrCondition),
  867. Entry("should set an error condition when store does not exist", storeMissingErrCondition),
  868. Entry("should set an error condition when store provider constructor fails", storeConstructErrCondition),
  869. Entry("should not process store with mismatching controller field", ignoreMismatchController),
  870. )
  871. })
  872. var _ = Describe("ExternalSecret refresh logic", func() {
  873. Context("secret refresh", func() {
  874. It("should refresh when resource version does not match", func() {
  875. Expect(shouldRefresh(esv1alpha1.ExternalSecret{
  876. Status: esv1alpha1.ExternalSecretStatus{
  877. SyncedResourceVersion: "some resource version",
  878. },
  879. })).To(BeTrue())
  880. })
  881. It("should refresh when labels change", func() {
  882. es := esv1alpha1.ExternalSecret{
  883. ObjectMeta: metav1.ObjectMeta{
  884. Generation: 1,
  885. Labels: map[string]string{
  886. "foo": "bar",
  887. },
  888. },
  889. Spec: esv1alpha1.ExternalSecretSpec{
  890. RefreshInterval: &metav1.Duration{Duration: time.Minute},
  891. },
  892. Status: esv1alpha1.ExternalSecretStatus{
  893. RefreshTime: metav1.Now(),
  894. },
  895. }
  896. es.Status.SyncedResourceVersion = getResourceVersion(es)
  897. // this should not refresh, rv matches object
  898. Expect(shouldRefresh(es)).To(BeFalse())
  899. // change labels without changing the syncedResourceVersion and expect refresh
  900. es.ObjectMeta.Labels["new"] = "w00t"
  901. Expect(shouldRefresh(es)).To(BeTrue())
  902. })
  903. It("should refresh when annotations change", func() {
  904. es := esv1alpha1.ExternalSecret{
  905. ObjectMeta: metav1.ObjectMeta{
  906. Generation: 1,
  907. Annotations: map[string]string{
  908. "foo": "bar",
  909. },
  910. },
  911. Spec: esv1alpha1.ExternalSecretSpec{
  912. RefreshInterval: &metav1.Duration{Duration: time.Minute},
  913. },
  914. Status: esv1alpha1.ExternalSecretStatus{
  915. RefreshTime: metav1.Now(),
  916. },
  917. }
  918. es.Status.SyncedResourceVersion = getResourceVersion(es)
  919. // this should not refresh, rv matches object
  920. Expect(shouldRefresh(es)).To(BeFalse())
  921. // change annotations without changing the syncedResourceVersion and expect refresh
  922. es.ObjectMeta.Annotations["new"] = "w00t"
  923. Expect(shouldRefresh(es)).To(BeTrue())
  924. })
  925. It("should refresh when generation has changed", func() {
  926. es := esv1alpha1.ExternalSecret{
  927. ObjectMeta: metav1.ObjectMeta{
  928. Generation: 1,
  929. },
  930. Spec: esv1alpha1.ExternalSecretSpec{
  931. RefreshInterval: &metav1.Duration{Duration: 0},
  932. },
  933. Status: esv1alpha1.ExternalSecretStatus{
  934. RefreshTime: metav1.Now(),
  935. },
  936. }
  937. es.Status.SyncedResourceVersion = getResourceVersion(es)
  938. Expect(shouldRefresh(es)).To(BeFalse())
  939. // update gen -> refresh
  940. es.ObjectMeta.Generation = 2
  941. Expect(shouldRefresh(es)).To(BeTrue())
  942. })
  943. It("should skip refresh when refreshInterval is 0", func() {
  944. es := esv1alpha1.ExternalSecret{
  945. ObjectMeta: metav1.ObjectMeta{
  946. Generation: 1,
  947. },
  948. Spec: esv1alpha1.ExternalSecretSpec{
  949. RefreshInterval: &metav1.Duration{Duration: 0},
  950. },
  951. Status: esv1alpha1.ExternalSecretStatus{},
  952. }
  953. // resource version matches
  954. es.Status.SyncedResourceVersion = getResourceVersion(es)
  955. Expect(shouldRefresh(es)).To(BeFalse())
  956. })
  957. It("should refresh when refresh interval has passed", func() {
  958. es := esv1alpha1.ExternalSecret{
  959. ObjectMeta: metav1.ObjectMeta{
  960. Generation: 1,
  961. },
  962. Spec: esv1alpha1.ExternalSecretSpec{
  963. RefreshInterval: &metav1.Duration{Duration: time.Second},
  964. },
  965. Status: esv1alpha1.ExternalSecretStatus{
  966. RefreshTime: metav1.NewTime(metav1.Now().Add(-time.Second * 5)),
  967. },
  968. }
  969. // resource version matches
  970. es.Status.SyncedResourceVersion = getResourceVersion(es)
  971. Expect(shouldRefresh(es)).To(BeTrue())
  972. })
  973. It("should refresh when no refresh time was set", func() {
  974. es := esv1alpha1.ExternalSecret{
  975. ObjectMeta: metav1.ObjectMeta{
  976. Generation: 1,
  977. },
  978. Spec: esv1alpha1.ExternalSecretSpec{
  979. RefreshInterval: &metav1.Duration{Duration: time.Second},
  980. },
  981. Status: esv1alpha1.ExternalSecretStatus{},
  982. }
  983. // resource version matches
  984. es.Status.SyncedResourceVersion = getResourceVersion(es)
  985. Expect(shouldRefresh(es)).To(BeTrue())
  986. })
  987. })
  988. Context("objectmeta hash", func() {
  989. It("should produce different hashes for different k/v pairs", func() {
  990. h1 := hashMeta(metav1.ObjectMeta{
  991. Generation: 1,
  992. Annotations: map[string]string{
  993. "foo": "bar",
  994. },
  995. })
  996. h2 := hashMeta(metav1.ObjectMeta{
  997. Generation: 1,
  998. Annotations: map[string]string{
  999. "foo": "bing",
  1000. },
  1001. })
  1002. Expect(h1).ToNot(Equal(h2))
  1003. })
  1004. It("should produce different hashes for different generations but same label/annotations", func() {
  1005. h1 := hashMeta(metav1.ObjectMeta{
  1006. Generation: 1,
  1007. Annotations: map[string]string{
  1008. "foo": "bar",
  1009. },
  1010. Labels: map[string]string{
  1011. "foo": "bar",
  1012. },
  1013. })
  1014. h2 := hashMeta(metav1.ObjectMeta{
  1015. Generation: 2,
  1016. Annotations: map[string]string{
  1017. "foo": "bar",
  1018. },
  1019. Labels: map[string]string{
  1020. "foo": "bar",
  1021. },
  1022. })
  1023. Expect(h1).To(Equal(h2))
  1024. })
  1025. It("should produce the same hash for the same k/v pairs", func() {
  1026. h1 := hashMeta(metav1.ObjectMeta{
  1027. Generation: 1,
  1028. })
  1029. h2 := hashMeta(metav1.ObjectMeta{
  1030. Generation: 1,
  1031. })
  1032. Expect(h1).To(Equal(h2))
  1033. h1 = hashMeta(metav1.ObjectMeta{
  1034. Generation: 1,
  1035. Annotations: map[string]string{
  1036. "foo": "bar",
  1037. },
  1038. })
  1039. h2 = hashMeta(metav1.ObjectMeta{
  1040. Generation: 1,
  1041. Annotations: map[string]string{
  1042. "foo": "bar",
  1043. },
  1044. })
  1045. Expect(h1).To(Equal(h2))
  1046. })
  1047. })
  1048. })
  1049. var _ = Describe("Controller Reconcile logic", func() {
  1050. Context("controller reconcile", func() {
  1051. It("should reconcile when resource is not synced", func() {
  1052. Expect(shouldReconcile(esv1alpha1.ExternalSecret{
  1053. Status: esv1alpha1.ExternalSecretStatus{
  1054. SyncedResourceVersion: "some resource version",
  1055. Conditions: []esv1alpha1.ExternalSecretStatusCondition{{Reason: "NotASecretSynced"}},
  1056. },
  1057. })).To(BeTrue())
  1058. })
  1059. It("should reconcile when secret isn't immutable", func() {
  1060. Expect(shouldReconcile(esv1alpha1.ExternalSecret{
  1061. Spec: esv1alpha1.ExternalSecretSpec{
  1062. Target: esv1alpha1.ExternalSecretTarget{
  1063. Immutable: false,
  1064. },
  1065. },
  1066. })).To(BeTrue())
  1067. })
  1068. It("should not reconcile if secret is immutable and has synced condition", func() {
  1069. Expect(shouldReconcile(esv1alpha1.ExternalSecret{
  1070. Spec: esv1alpha1.ExternalSecretSpec{
  1071. Target: esv1alpha1.ExternalSecretTarget{
  1072. Immutable: true,
  1073. },
  1074. },
  1075. Status: esv1alpha1.ExternalSecretStatus{
  1076. SyncedResourceVersion: "some resource version",
  1077. Conditions: []esv1alpha1.ExternalSecretStatusCondition{{Reason: "SecretSynced"}},
  1078. },
  1079. })).To(BeFalse())
  1080. })
  1081. })
  1082. })
  1083. // CreateNamespace creates a new namespace in the cluster.
  1084. func CreateNamespace(baseName string, c client.Client) (string, error) {
  1085. genName := fmt.Sprintf("ctrl-test-%v", baseName)
  1086. ns := &v1.Namespace{
  1087. ObjectMeta: metav1.ObjectMeta{
  1088. GenerateName: genName,
  1089. },
  1090. }
  1091. var err error
  1092. err = wait.Poll(time.Second, 10*time.Second, func() (bool, error) {
  1093. err = c.Create(context.Background(), ns)
  1094. if err != nil {
  1095. return false, nil
  1096. }
  1097. return true, nil
  1098. })
  1099. if err != nil {
  1100. return "", err
  1101. }
  1102. return ns.Name, nil
  1103. }
  1104. func hasOwnerRef(meta metav1.ObjectMeta, kind, name string) bool {
  1105. for _, ref := range meta.OwnerReferences {
  1106. if ref.Kind == kind && ref.Name == name {
  1107. return true
  1108. }
  1109. }
  1110. return false
  1111. }
  1112. func hasFieldOwnership(meta metav1.ObjectMeta, mgr, rawFields string) bool {
  1113. for _, ref := range meta.ManagedFields {
  1114. if ref.Manager == mgr && string(ref.FieldsV1.Raw) == rawFields {
  1115. return true
  1116. }
  1117. }
  1118. return false
  1119. }
  1120. func externalSecretConditionShouldBe(name, ns string, ct esv1alpha1.ExternalSecretConditionType, cs v1.ConditionStatus, v float64) bool {
  1121. return Eventually(func() float64 {
  1122. Expect(externalSecretCondition.WithLabelValues(name, ns, string(ct), string(cs)).Write(&metric)).To(Succeed())
  1123. return metric.GetGauge().GetValue()
  1124. }, timeout, interval).Should(Equal(v))
  1125. }
  1126. func init() {
  1127. fakeProvider = fake.New()
  1128. schema.ForceRegister(fakeProvider, &esv1alpha1.SecretStoreProvider{
  1129. AWS: &esv1alpha1.AWSProvider{
  1130. Service: esv1alpha1.AWSServiceSecretsManager,
  1131. },
  1132. })
  1133. }