externalsecret_controller_test.go 48 KB

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