secretsmanager_test.go 6.6 KB

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