gitlab_test.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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 gitlab
  13. import (
  14. "context"
  15. "fmt"
  16. "net/http"
  17. "reflect"
  18. "strings"
  19. "testing"
  20. gitlab "github.com/xanzy/go-gitlab"
  21. esv1beta1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1beta1"
  22. v1 "github.com/external-secrets/external-secrets/apis/meta/v1"
  23. fakegitlab "github.com/external-secrets/external-secrets/pkg/provider/gitlab/fake"
  24. )
  25. type secretManagerTestCase struct {
  26. mockClient *fakegitlab.GitlabMockClient
  27. apiInputProjectID string
  28. apiInputKey string
  29. apiOutput *gitlab.ProjectVariable
  30. apiResponse *gitlab.Response
  31. ref *esv1beta1.ExternalSecretDataRemoteRef
  32. projectID *string
  33. apiErr error
  34. expectError string
  35. expectedSecret string
  36. expectedValidationResult esv1beta1.ValidationResult
  37. // for testing secretmap
  38. expectedData map[string][]byte
  39. }
  40. func makeValidSecretManagerTestCase() *secretManagerTestCase {
  41. smtc := secretManagerTestCase{
  42. mockClient: &fakegitlab.GitlabMockClient{},
  43. apiInputProjectID: makeValidAPIInputProjectID(),
  44. apiInputKey: makeValidAPIInputKey(),
  45. ref: makeValidRef(),
  46. projectID: nil,
  47. apiOutput: makeValidAPIOutput(),
  48. apiResponse: makeValidAPIResponse(),
  49. apiErr: nil,
  50. expectError: "",
  51. expectedSecret: "",
  52. expectedValidationResult: esv1beta1.ValidationResultReady,
  53. expectedData: map[string][]byte{},
  54. }
  55. smtc.mockClient.WithValue(smtc.apiInputProjectID, smtc.apiInputKey, smtc.apiOutput, smtc.apiResponse, smtc.apiErr)
  56. return &smtc
  57. }
  58. func makeValidRef() *esv1beta1.ExternalSecretDataRemoteRef {
  59. return &esv1beta1.ExternalSecretDataRemoteRef{
  60. Key: "test-secret",
  61. Version: "default",
  62. }
  63. }
  64. func makeValidAPIInputProjectID() string {
  65. return "testID"
  66. }
  67. func makeValidAPIInputKey() string {
  68. return "testKey"
  69. }
  70. func makeValidAPIResponse() *gitlab.Response {
  71. return &gitlab.Response{
  72. Response: &http.Response{
  73. StatusCode: http.StatusOK,
  74. },
  75. }
  76. }
  77. func makeValidAPIOutput() *gitlab.ProjectVariable {
  78. return &gitlab.ProjectVariable{
  79. Key: "testKey",
  80. Value: "",
  81. }
  82. }
  83. func makeValidSecretManagerTestCaseCustom(tweaks ...func(smtc *secretManagerTestCase)) *secretManagerTestCase {
  84. smtc := makeValidSecretManagerTestCase()
  85. for _, fn := range tweaks {
  86. fn(smtc)
  87. }
  88. smtc.mockClient.WithValue(smtc.apiInputProjectID, smtc.apiInputKey, smtc.apiOutput, smtc.apiResponse, smtc.apiErr)
  89. return smtc
  90. }
  91. // This case can be shared by both GetSecret and GetSecretMap tests.
  92. // bad case: set apiErr.
  93. var setAPIErr = func(smtc *secretManagerTestCase) {
  94. smtc.apiErr = fmt.Errorf("oh no")
  95. smtc.expectError = "oh no"
  96. smtc.expectedValidationResult = esv1beta1.ValidationResultError
  97. }
  98. var setListAPIErr = func(smtc *secretManagerTestCase) {
  99. err := fmt.Errorf("oh no")
  100. smtc.apiErr = err
  101. smtc.expectError = fmt.Errorf(errList, err).Error()
  102. smtc.expectedValidationResult = esv1beta1.ValidationResultError
  103. }
  104. var setListAPIRespNil = func(smtc *secretManagerTestCase) {
  105. smtc.apiResponse = nil
  106. smtc.expectError = errAuth
  107. smtc.expectedValidationResult = esv1beta1.ValidationResultError
  108. }
  109. var setListAPIRespBadCode = func(smtc *secretManagerTestCase) {
  110. smtc.apiResponse.StatusCode = http.StatusUnauthorized
  111. smtc.expectError = errAuth
  112. smtc.expectedValidationResult = esv1beta1.ValidationResultError
  113. }
  114. var setNilMockClient = func(smtc *secretManagerTestCase) {
  115. smtc.mockClient = nil
  116. smtc.expectError = errUninitalizedGitlabProvider
  117. }
  118. // test the sm<->gcp interface
  119. // make sure correct values are passed and errors are handled accordingly.
  120. func TestGitlabSecretManagerGetSecret(t *testing.T) {
  121. secretValue := "changedvalue"
  122. // good case: default version is set
  123. // key is passed in, output is sent back
  124. setSecretString := func(smtc *secretManagerTestCase) {
  125. smtc.apiOutput = &gitlab.ProjectVariable{
  126. Key: "testkey",
  127. Value: "changedvalue",
  128. }
  129. smtc.expectedSecret = secretValue
  130. }
  131. successCases := []*secretManagerTestCase{
  132. makeValidSecretManagerTestCaseCustom(setSecretString),
  133. makeValidSecretManagerTestCaseCustom(setAPIErr),
  134. makeValidSecretManagerTestCaseCustom(setNilMockClient),
  135. }
  136. sm := Gitlab{}
  137. for k, v := range successCases {
  138. sm.client = v.mockClient
  139. out, err := sm.GetSecret(context.Background(), *v.ref)
  140. if !ErrorContains(err, v.expectError) {
  141. t.Errorf("[%d] unexpected error: %s, expected: '%s'", k, err.Error(), v.expectError)
  142. }
  143. if string(out) != v.expectedSecret {
  144. t.Errorf("[%d] unexpected secret: expected %s, got %s", k, v.expectedSecret, string(out))
  145. }
  146. }
  147. }
  148. func TestValidate(t *testing.T) {
  149. successCases := []*secretManagerTestCase{
  150. makeValidSecretManagerTestCaseCustom(),
  151. makeValidSecretManagerTestCaseCustom(setListAPIErr),
  152. makeValidSecretManagerTestCaseCustom(setListAPIRespNil),
  153. makeValidSecretManagerTestCaseCustom(setListAPIRespBadCode),
  154. }
  155. sm := Gitlab{}
  156. for k, v := range successCases {
  157. sm.client = v.mockClient
  158. t.Logf("%+v", v)
  159. validationResult, err := sm.Validate()
  160. if !ErrorContains(err, v.expectError) {
  161. t.Errorf("[%d], unexpected error: %s, expected: '%s'", k, err.Error(), v.expectError)
  162. }
  163. if validationResult != v.expectedValidationResult {
  164. t.Errorf("[%d], unexpected validationResult: %s, expected: '%s'", k, validationResult, v.expectedValidationResult)
  165. }
  166. }
  167. }
  168. func TestGetSecretMap(t *testing.T) {
  169. // good case: default version & deserialization
  170. setDeserialization := func(smtc *secretManagerTestCase) {
  171. smtc.apiOutput.Value = `{"foo":"bar"}`
  172. smtc.expectedData["foo"] = []byte("bar")
  173. }
  174. // bad case: invalid json
  175. setInvalidJSON := func(smtc *secretManagerTestCase) {
  176. smtc.apiOutput.Value = `-----------------`
  177. smtc.expectError = "unable to unmarshal secret"
  178. }
  179. successCases := []*secretManagerTestCase{
  180. makeValidSecretManagerTestCaseCustom(setDeserialization),
  181. makeValidSecretManagerTestCaseCustom(setInvalidJSON),
  182. makeValidSecretManagerTestCaseCustom(setNilMockClient),
  183. makeValidSecretManagerTestCaseCustom(setAPIErr),
  184. }
  185. sm := Gitlab{}
  186. for k, v := range successCases {
  187. sm.client = v.mockClient
  188. out, err := sm.GetSecretMap(context.Background(), *v.ref)
  189. if !ErrorContains(err, v.expectError) {
  190. t.Errorf("[%d] unexpected error: %s, expected: '%s'", k, err.Error(), v.expectError)
  191. }
  192. if err == nil && !reflect.DeepEqual(out, v.expectedData) {
  193. t.Errorf("[%d] unexpected secret data: expected %#v, got %#v", k, v.expectedData, out)
  194. }
  195. }
  196. }
  197. func ErrorContains(out error, want string) bool {
  198. if out == nil {
  199. return want == ""
  200. }
  201. if want == "" {
  202. return false
  203. }
  204. return strings.Contains(out.Error(), want)
  205. }
  206. func TestValidateStore(t *testing.T) {
  207. p := Gitlab{}
  208. bing := "bing"
  209. store := &esv1beta1.SecretStore{
  210. Spec: esv1beta1.SecretStoreSpec{
  211. Provider: &esv1beta1.SecretStoreProvider{
  212. Gitlab: &esv1beta1.GitlabProvider{
  213. Auth: esv1beta1.GitlabAuth{
  214. SecretRef: esv1beta1.GitlabSecretRef{
  215. AccessToken: v1.SecretKeySelector{
  216. Name: "Foo",
  217. Key: "Baa",
  218. Namespace: &bing,
  219. },
  220. },
  221. },
  222. ProjectID: "my-project",
  223. },
  224. },
  225. },
  226. }
  227. err := p.ValidateStore(store)
  228. if err == nil {
  229. t.Errorf("want err got nil")
  230. }
  231. store.Spec.Provider.Gitlab.Auth.SecretRef.AccessToken.Namespace = nil
  232. err = p.ValidateStore(store)
  233. if err != nil {
  234. t.Errorf("want nil got err: %v", err)
  235. }
  236. store.Spec.Provider.Gitlab.ProjectID = ""
  237. err = p.ValidateStore(store)
  238. if err == nil {
  239. t.Errorf("projectId validation: want error got nil")
  240. }
  241. }