doppler_test.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. /*
  2. Copyright © 2025 ESO Maintainer Team
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. https://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package doppler
  14. import (
  15. "context"
  16. "errors"
  17. "strings"
  18. "testing"
  19. "github.com/google/go-cmp/cmp"
  20. corev1 "k8s.io/api/core/v1"
  21. esv1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1"
  22. esv1alpha1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1alpha1"
  23. v1 "github.com/external-secrets/external-secrets/apis/meta/v1"
  24. "github.com/external-secrets/external-secrets/pkg/provider/doppler/client"
  25. "github.com/external-secrets/external-secrets/pkg/provider/doppler/fake"
  26. )
  27. const (
  28. validSecretName = "API_KEY"
  29. validSecretValue = "3a3ea4f5"
  30. validRemoteKey = "REMOTE_KEY"
  31. dopplerProject = "DOPPLER_PROJECT"
  32. dopplerProjectVal = "auth-api"
  33. missingSecret = "INVALID_NAME"
  34. invalidSecret = "doppler_project"
  35. invalidRemoteKey = "INVALID_REMOTE_KEY"
  36. missingSecretErr = "could not get secret"
  37. missingDeleteErr = "could not delete secrets"
  38. missingPushErr = "could not push secrets"
  39. )
  40. type dopplerTestCase struct {
  41. label string
  42. fakeClient *fake.DopplerClient
  43. request client.SecretRequest
  44. response *client.SecretResponse
  45. remoteRef *esv1.ExternalSecretDataRemoteRef
  46. apiErr error
  47. expectError string
  48. expectedSecret string
  49. expectedData map[string][]byte
  50. }
  51. type updateSecretCase struct {
  52. label string
  53. fakeClient *fake.DopplerClient
  54. request client.UpdateSecretsRequest
  55. remoteRef *esv1alpha1.PushSecretRemoteRef
  56. secret corev1.Secret
  57. secretData esv1.PushSecretData
  58. apiErr error
  59. expectError string
  60. }
  61. func makeValidAPIRequest() client.SecretRequest {
  62. return client.SecretRequest{
  63. Name: validSecretName,
  64. }
  65. }
  66. func makeValidPushRequest() client.UpdateSecretsRequest {
  67. return client.UpdateSecretsRequest{
  68. Secrets: client.Secrets{
  69. validRemoteKey: validSecretValue,
  70. },
  71. }
  72. }
  73. func makeValidDeleteRequest() client.UpdateSecretsRequest {
  74. return client.UpdateSecretsRequest{
  75. ChangeRequests: []client.Change{
  76. {
  77. Name: validRemoteKey,
  78. OriginalName: validRemoteKey,
  79. ShouldDelete: true,
  80. },
  81. },
  82. }
  83. }
  84. func makeValidAPIOutput() *client.SecretResponse {
  85. return &client.SecretResponse{
  86. Name: validSecretName,
  87. Value: validSecretValue,
  88. }
  89. }
  90. func makeValidRemoteRef() *esv1.ExternalSecretDataRemoteRef {
  91. return &esv1.ExternalSecretDataRemoteRef{
  92. Key: validSecretName,
  93. }
  94. }
  95. func makeValidPushRemoteRef() *esv1alpha1.PushSecretRemoteRef {
  96. return &esv1alpha1.PushSecretRemoteRef{
  97. RemoteKey: validRemoteKey,
  98. }
  99. }
  100. func makeValidSecret() corev1.Secret {
  101. return corev1.Secret{
  102. Data: map[string][]byte{
  103. validSecretName: []byte(validSecretValue),
  104. },
  105. }
  106. }
  107. func makeValidSecretData() esv1alpha1.PushSecretData {
  108. return makeSecretData(validSecretName, *makeValidPushRemoteRef())
  109. }
  110. func makeSecretData(key string, ref esv1alpha1.PushSecretRemoteRef) esv1alpha1.PushSecretData {
  111. return esv1alpha1.PushSecretData{
  112. Match: esv1alpha1.PushSecretMatch{
  113. SecretKey: key,
  114. RemoteRef: ref,
  115. },
  116. }
  117. }
  118. func makeValidDopplerTestCase() *dopplerTestCase {
  119. return &dopplerTestCase{
  120. fakeClient: &fake.DopplerClient{},
  121. request: makeValidAPIRequest(),
  122. response: makeValidAPIOutput(),
  123. remoteRef: makeValidRemoteRef(),
  124. apiErr: nil,
  125. expectError: "",
  126. expectedSecret: "",
  127. expectedData: make(map[string][]byte),
  128. }
  129. }
  130. func makeValidUpdateSecretTestCase() *updateSecretCase {
  131. return &updateSecretCase{
  132. fakeClient: &fake.DopplerClient{},
  133. remoteRef: makeValidPushRemoteRef(),
  134. secret: makeValidSecret(),
  135. secretData: makeValidSecretData(),
  136. apiErr: nil,
  137. expectError: "",
  138. }
  139. }
  140. func makeValidDopplerTestCaseCustom(tweaks ...func(pstc *dopplerTestCase)) *dopplerTestCase {
  141. pstc := makeValidDopplerTestCase()
  142. for _, fn := range tweaks {
  143. fn(pstc)
  144. }
  145. pstc.fakeClient.WithValue(pstc.request, pstc.response, pstc.apiErr)
  146. return pstc
  147. }
  148. func makeValidUpdateSecretCaseCustom(tweaks ...func(pstc *updateSecretCase)) *updateSecretCase {
  149. pstc := makeValidUpdateSecretTestCase()
  150. for _, fn := range tweaks {
  151. fn(pstc)
  152. }
  153. pstc.fakeClient.WithUpdateValue(pstc.request, pstc.apiErr)
  154. return pstc
  155. }
  156. func TestGetSecret(t *testing.T) {
  157. setSecret := func(pstc *dopplerTestCase) {
  158. pstc.label = "set secret"
  159. pstc.request.Name = dopplerProject
  160. pstc.response.Name = dopplerProject
  161. pstc.response.Value = dopplerProjectVal
  162. pstc.expectedSecret = dopplerProjectVal
  163. pstc.remoteRef.Key = dopplerProject
  164. }
  165. setMissingSecret := func(pstc *dopplerTestCase) {
  166. pstc.label = "invalid missing secret"
  167. pstc.remoteRef.Key = missingSecret
  168. pstc.request.Name = missingSecret
  169. pstc.response = nil
  170. pstc.expectError = missingSecretErr
  171. pstc.apiErr = errors.New("")
  172. }
  173. setInvalidSecret := func(pstc *dopplerTestCase) {
  174. pstc.label = "invalid secret name format"
  175. pstc.remoteRef.Key = invalidSecret
  176. pstc.request.Name = invalidSecret
  177. pstc.response = nil
  178. pstc.expectError = missingSecretErr
  179. pstc.apiErr = errors.New("")
  180. }
  181. setClientError := func(pstc *dopplerTestCase) {
  182. pstc.label = "invalid client error" //nolint:goconst
  183. pstc.response = &client.SecretResponse{}
  184. pstc.expectError = missingSecretErr
  185. pstc.apiErr = errors.New("")
  186. }
  187. testCases := []*dopplerTestCase{
  188. makeValidDopplerTestCaseCustom(setSecret),
  189. makeValidDopplerTestCaseCustom(setMissingSecret),
  190. makeValidDopplerTestCaseCustom(setInvalidSecret),
  191. makeValidDopplerTestCaseCustom(setClientError),
  192. }
  193. c := Client{}
  194. for k, tc := range testCases {
  195. c.doppler = tc.fakeClient
  196. out, err := c.GetSecret(context.Background(), *tc.remoteRef)
  197. if !ErrorContains(err, tc.expectError) {
  198. t.Errorf("[%d] unexpected error: %s, expected: '%s'", k, err.Error(), tc.expectError)
  199. }
  200. if err == nil && !cmp.Equal(string(out), tc.expectedSecret) {
  201. t.Errorf("[%d] unexpected secret data: expected %#v, got %#v", k, tc.expectedSecret, string(out))
  202. }
  203. }
  204. }
  205. func TestGetSecretMap(t *testing.T) {
  206. simpleJSON := func(pstc *dopplerTestCase) {
  207. pstc.label = "valid unmarshalling"
  208. pstc.response.Value = `{"API_KEY":"3a3ea4f5"}`
  209. pstc.expectedData["API_KEY"] = []byte("3a3ea4f5")
  210. }
  211. complexJSON := func(pstc *dopplerTestCase) {
  212. pstc.label = "valid unmarshalling for nested json"
  213. pstc.response.Value = `{"API_KEY": "3a3ea4f5", "AUTH_SA": {"appID": "a1ea-48bd-8749-b6f5ec3c5a1f"}}`
  214. pstc.expectedData["API_KEY"] = []byte("3a3ea4f5")
  215. pstc.expectedData["AUTH_SA"] = []byte(`{"appID": "a1ea-48bd-8749-b6f5ec3c5a1f"}`)
  216. }
  217. setInvalidJSON := func(pstc *dopplerTestCase) {
  218. pstc.label = "invalid json"
  219. pstc.response.Value = `{"API_KEY": "3a3ea4f`
  220. pstc.expectError = "unable to unmarshal secret"
  221. }
  222. setAPIError := func(pstc *dopplerTestCase) {
  223. pstc.label = "client error"
  224. pstc.response = &client.SecretResponse{}
  225. pstc.expectError = missingSecretErr
  226. pstc.apiErr = errors.New("")
  227. }
  228. testCases := []*dopplerTestCase{
  229. makeValidDopplerTestCaseCustom(simpleJSON),
  230. makeValidDopplerTestCaseCustom(complexJSON),
  231. makeValidDopplerTestCaseCustom(setInvalidJSON),
  232. makeValidDopplerTestCaseCustom(setAPIError),
  233. }
  234. d := Client{}
  235. for k, tc := range testCases {
  236. t.Run(tc.label, func(t *testing.T) {
  237. d.doppler = tc.fakeClient
  238. out, err := d.GetSecretMap(context.Background(), *tc.remoteRef)
  239. if !ErrorContains(err, tc.expectError) {
  240. t.Errorf("[%d] unexpected error: %q, expected: %q", k, err.Error(), tc.expectError)
  241. }
  242. if err == nil && !cmp.Equal(out, tc.expectedData) {
  243. t.Errorf("[%d] unexpected secret data: expected %#v, got %#v", k, tc.expectedData, out)
  244. }
  245. })
  246. }
  247. }
  248. func ErrorContains(out error, want string) bool {
  249. if out == nil {
  250. return want == ""
  251. }
  252. if want == "" {
  253. return false
  254. }
  255. return strings.Contains(out.Error(), want)
  256. }
  257. func TestDeleteSecret(t *testing.T) {
  258. deleteSecret := func(pstc *updateSecretCase) {
  259. pstc.label = "delete secret"
  260. pstc.request = makeValidDeleteRequest()
  261. }
  262. deleteMissingSecret := func(pstc *updateSecretCase) {
  263. pstc.label = "delete missing secret"
  264. pstc.request = makeValidDeleteRequest()
  265. pstc.remoteRef.RemoteKey = invalidRemoteKey
  266. pstc.expectError = missingDeleteErr
  267. pstc.apiErr = errors.New("")
  268. }
  269. setClientError := func(pstc *updateSecretCase) {
  270. pstc.label = "invalid client error"
  271. pstc.request = makeValidDeleteRequest()
  272. pstc.expectError = missingDeleteErr
  273. pstc.apiErr = errors.New("")
  274. }
  275. testCases := []*updateSecretCase{
  276. makeValidUpdateSecretCaseCustom(deleteSecret),
  277. makeValidUpdateSecretCaseCustom(deleteMissingSecret),
  278. makeValidUpdateSecretCaseCustom(setClientError),
  279. }
  280. c := Client{}
  281. for k, tc := range testCases {
  282. c.doppler = tc.fakeClient
  283. err := c.DeleteSecret(context.Background(), tc.remoteRef)
  284. if !ErrorContains(err, tc.expectError) {
  285. t.Errorf("[%d] unexpected error: %s, expected: '%s'", k, err.Error(), tc.expectError)
  286. }
  287. }
  288. }
  289. func TestPushSecret(t *testing.T) {
  290. pushSecret := func(pstc *updateSecretCase) {
  291. pstc.label = "push secret"
  292. pstc.request = makeValidPushRequest()
  293. }
  294. pushMissingSecretKey := func(pstc *updateSecretCase) {
  295. pstc.label = "push missing secret key"
  296. pstc.secretData = makeSecretData(invalidSecret, *makeValidPushRemoteRef())
  297. pstc.expectError = missingPushErr
  298. pstc.apiErr = errors.New("")
  299. }
  300. pushMissingRemoteSecret := func(pstc *updateSecretCase) {
  301. pstc.label = "push missing remote secret"
  302. pstc.secretData = makeSecretData(
  303. validSecretName,
  304. esv1alpha1.PushSecretRemoteRef{
  305. RemoteKey: invalidRemoteKey,
  306. },
  307. )
  308. pstc.expectError = missingPushErr
  309. pstc.apiErr = errors.New("")
  310. }
  311. setClientError := func(pstc *updateSecretCase) {
  312. pstc.label = "invalid client error"
  313. pstc.expectError = missingPushErr
  314. pstc.apiErr = errors.New("")
  315. }
  316. testCases := []*updateSecretCase{
  317. makeValidUpdateSecretCaseCustom(pushSecret),
  318. makeValidUpdateSecretCaseCustom(pushMissingSecretKey),
  319. makeValidUpdateSecretCaseCustom(pushMissingRemoteSecret),
  320. makeValidUpdateSecretCaseCustom(setClientError),
  321. }
  322. c := Client{}
  323. for k, tc := range testCases {
  324. c.doppler = tc.fakeClient
  325. err := c.PushSecret(context.Background(), &tc.secret, tc.secretData)
  326. if !ErrorContains(err, tc.expectError) {
  327. t.Errorf("[%d] unexpected error: %s, expected: '%s'", k, err.Error(), tc.expectError)
  328. }
  329. }
  330. }
  331. type storeModifier func(*esv1.SecretStore) *esv1.SecretStore
  332. func makeSecretStore(fn ...storeModifier) *esv1.SecretStore {
  333. store := &esv1.SecretStore{
  334. Spec: esv1.SecretStoreSpec{
  335. Provider: &esv1.SecretStoreProvider{
  336. Doppler: &esv1.DopplerProvider{
  337. Auth: &esv1.DopplerAuth{},
  338. },
  339. },
  340. },
  341. }
  342. for _, f := range fn {
  343. store = f(store)
  344. }
  345. return store
  346. }
  347. func withAuth(name, key string, namespace *string) storeModifier {
  348. return func(store *esv1.SecretStore) *esv1.SecretStore {
  349. store.Spec.Provider.Doppler.Auth.SecretRef.DopplerToken = v1.SecretKeySelector{
  350. Name: name,
  351. Key: key,
  352. Namespace: namespace,
  353. }
  354. return store
  355. }
  356. }
  357. type ValidateStoreTestCase struct {
  358. label string
  359. store *esv1.SecretStore
  360. err error
  361. }
  362. func TestValidateStore(t *testing.T) {
  363. namespace := "ns"
  364. secretName := "doppler-token-secret"
  365. testCases := []ValidateStoreTestCase{
  366. {
  367. label: "invalid store missing dopplerToken.name",
  368. store: makeSecretStore(withAuth("", "", nil)),
  369. err: errors.New("invalid store: dopplerToken.name cannot be empty"),
  370. },
  371. {
  372. label: "invalid store namespace not allowed",
  373. store: makeSecretStore(withAuth(secretName, "", &namespace)),
  374. err: errors.New("invalid store: namespace should either be empty or match the namespace of the SecretStore for a namespaced SecretStore"),
  375. },
  376. {
  377. label: "valid provide optional dopplerToken.key",
  378. store: makeSecretStore(withAuth(secretName, "customSecretKey", nil)),
  379. err: nil,
  380. },
  381. {
  382. label: "valid namespace not set",
  383. store: makeSecretStore(withAuth(secretName, "", nil)),
  384. err: nil,
  385. },
  386. }
  387. p := Provider{}
  388. for _, tc := range testCases {
  389. t.Run(tc.label, func(t *testing.T) {
  390. _, err := p.ValidateStore(tc.store)
  391. if tc.err != nil && err != nil && err.Error() != tc.err.Error() {
  392. t.Errorf("test failed! want %v, got %v", tc.err, err)
  393. } else if tc.err == nil && err != nil {
  394. t.Errorf("want nil got err %v", err)
  395. } else if tc.err != nil && err == nil {
  396. t.Errorf("want err %v got nil", tc.err)
  397. }
  398. })
  399. }
  400. }