secretsmanager_test.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  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 secretmanager
  13. import (
  14. "context"
  15. "fmt"
  16. "reflect"
  17. "strings"
  18. "testing"
  19. secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1"
  20. esv1alpha1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1alpha1"
  21. fakesm "github.com/external-secrets/external-secrets/pkg/provider/gcp/secretmanager/fake"
  22. )
  23. type secretManagerTestCase struct {
  24. mockClient *fakesm.MockSMClient
  25. apiInput *secretmanagerpb.AccessSecretVersionRequest
  26. apiOutput *secretmanagerpb.AccessSecretVersionResponse
  27. ref *esv1alpha1.ExternalSecretDataRemoteRef
  28. projectID string
  29. apiErr error
  30. expectError string
  31. expectedSecret string
  32. // for testing secretmap
  33. expectedData map[string][]byte
  34. }
  35. func makeValidSecretManagerTestCase() *secretManagerTestCase {
  36. smtc := secretManagerTestCase{
  37. mockClient: &fakesm.MockSMClient{},
  38. apiInput: makeValidAPIInput(),
  39. ref: makeValidRef(),
  40. apiOutput: makeValidAPIOutput(),
  41. projectID: "default",
  42. apiErr: nil,
  43. expectError: "",
  44. expectedSecret: "",
  45. expectedData: map[string][]byte{},
  46. }
  47. smtc.mockClient.NilClose()
  48. smtc.mockClient.WithValue(context.Background(), smtc.apiInput, smtc.apiOutput, smtc.apiErr)
  49. return &smtc
  50. }
  51. func makeValidRef() *esv1alpha1.ExternalSecretDataRemoteRef {
  52. return &esv1alpha1.ExternalSecretDataRemoteRef{
  53. Extract: esv1alpha1.ExternalSecretExtract{
  54. Key: "/baz",
  55. Version: "default",
  56. },
  57. }
  58. }
  59. func makeValidAPIInput() *secretmanagerpb.AccessSecretVersionRequest {
  60. return &secretmanagerpb.AccessSecretVersionRequest{
  61. Name: "projects/default/secrets//baz/versions/default",
  62. }
  63. }
  64. func makeValidAPIOutput() *secretmanagerpb.AccessSecretVersionResponse {
  65. return &secretmanagerpb.AccessSecretVersionResponse{
  66. Payload: &secretmanagerpb.SecretPayload{
  67. Data: []byte{},
  68. },
  69. }
  70. }
  71. func makeValidSecretManagerTestCaseCustom(tweaks ...func(smtc *secretManagerTestCase)) *secretManagerTestCase {
  72. smtc := makeValidSecretManagerTestCase()
  73. for _, fn := range tweaks {
  74. fn(smtc)
  75. }
  76. smtc.mockClient.WithValue(context.Background(), smtc.apiInput, smtc.apiOutput, smtc.apiErr)
  77. return smtc
  78. }
  79. // This case can be shared by both GetSecret and GetSecretMap tests.
  80. // bad case: set apiErr.
  81. var setAPIErr = func(smtc *secretManagerTestCase) {
  82. smtc.apiErr = fmt.Errorf("oh no")
  83. smtc.expectError = "oh no"
  84. }
  85. var setNilMockClient = func(smtc *secretManagerTestCase) {
  86. smtc.mockClient = nil
  87. smtc.expectError = errUninitalizedGCPProvider
  88. }
  89. // test the sm<->gcp interface
  90. // make sure correct values are passed and errors are handled accordingly.
  91. func TestSecretManagerGetSecret(t *testing.T) {
  92. // good case: default version is set
  93. // key is passed in, output is sent back
  94. setSecretString := func(smtc *secretManagerTestCase) {
  95. smtc.apiOutput.Payload.Data = []byte("testtesttest")
  96. smtc.expectedSecret = "testtesttest"
  97. }
  98. // good case: ref with
  99. setCustomRef := func(smtc *secretManagerTestCase) {
  100. smtc.ref = &esv1alpha1.ExternalSecretDataRemoteRef{
  101. Extract: esv1alpha1.ExternalSecretExtract{
  102. Key: "/baz",
  103. Version: "default",
  104. Property: "name.first",
  105. },
  106. }
  107. smtc.apiInput.Name = "projects/default/secrets//baz/versions/default"
  108. smtc.apiOutput.Payload.Data = []byte(
  109. `{
  110. "name": {"first": "Tom", "last": "Anderson"},
  111. "friends": [
  112. {"first": "Dale", "last": "Murphy"},
  113. {"first": "Roger", "last": "Craig"},
  114. {"first": "Jane", "last": "Murphy"}
  115. ]
  116. }`)
  117. smtc.expectedSecret = "Tom"
  118. }
  119. // good case: custom version set
  120. setCustomVersion := func(smtc *secretManagerTestCase) {
  121. smtc.ref.Extract.Version = "1234"
  122. smtc.apiInput.Name = "projects/default/secrets//baz/versions/1234"
  123. smtc.apiOutput.Payload.Data = []byte("FOOBA!")
  124. smtc.expectedSecret = "FOOBA!"
  125. }
  126. successCases := []*secretManagerTestCase{
  127. makeValidSecretManagerTestCase(),
  128. makeValidSecretManagerTestCaseCustom(setSecretString),
  129. makeValidSecretManagerTestCaseCustom(setCustomVersion),
  130. makeValidSecretManagerTestCaseCustom(setAPIErr),
  131. makeValidSecretManagerTestCaseCustom(setCustomRef),
  132. makeValidSecretManagerTestCaseCustom(setNilMockClient),
  133. }
  134. sm := ProviderGCP{}
  135. for k, v := range successCases {
  136. sm.projectID = v.projectID
  137. sm.SecretManagerClient = v.mockClient
  138. out, err := sm.GetSecret(context.Background(), *v.ref)
  139. if !ErrorContains(err, v.expectError) {
  140. t.Errorf("[%d] unexpected error: %s, expected: '%s'", k, err.Error(), v.expectError)
  141. }
  142. if err == nil && string(out) != v.expectedSecret {
  143. t.Errorf("[%d] unexpected secret: expected %s, got %s", k, v.expectedSecret, string(out))
  144. }
  145. }
  146. }
  147. func TestGetSecretMap(t *testing.T) {
  148. // good case: default version & deserialization
  149. setDeserialization := func(smtc *secretManagerTestCase) {
  150. smtc.apiOutput.Payload.Data = []byte(`{"foo":"bar"}`)
  151. smtc.expectedData["foo"] = []byte("bar")
  152. }
  153. // bad case: invalid json
  154. setInvalidJSON := func(smtc *secretManagerTestCase) {
  155. smtc.apiOutput.Payload.Data = []byte(`-----------------`)
  156. smtc.expectError = "unable to unmarshal secret"
  157. }
  158. // good case: deserialize nested json as []byte, if it's a string, decode the string
  159. setNestedJSON := func(smtc *secretManagerTestCase) {
  160. smtc.apiOutput.Payload.Data = []byte(`{"foo":{"bar":"baz"}, "qux": "qu\"z"}`)
  161. smtc.expectedData["foo"] = []byte(`{"bar":"baz"}`)
  162. smtc.expectedData["qux"] = []byte("qu\"z")
  163. }
  164. successCases := []*secretManagerTestCase{
  165. makeValidSecretManagerTestCaseCustom(setDeserialization),
  166. makeValidSecretManagerTestCaseCustom(setAPIErr),
  167. makeValidSecretManagerTestCaseCustom(setNilMockClient),
  168. makeValidSecretManagerTestCaseCustom(setInvalidJSON),
  169. makeValidSecretManagerTestCaseCustom(setNestedJSON),
  170. }
  171. sm := ProviderGCP{}
  172. for k, v := range successCases {
  173. sm.projectID = v.projectID
  174. sm.SecretManagerClient = v.mockClient
  175. out, err := sm.GetSecretMap(context.Background(), *v.ref)
  176. if !ErrorContains(err, v.expectError) {
  177. t.Errorf("[%d] unexpected error: %s, expected: '%s'", k, err.Error(), v.expectError)
  178. }
  179. if err == nil && !reflect.DeepEqual(out, v.expectedData) {
  180. t.Errorf("[%d] unexpected secret data: expected %#v, got %#v", k, v.expectedData, out)
  181. }
  182. }
  183. }
  184. func ErrorContains(out error, want string) bool {
  185. if out == nil {
  186. return want == ""
  187. }
  188. if want == "" {
  189. return false
  190. }
  191. return strings.Contains(out.Error(), want)
  192. }