secretsmanager_test.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  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. // test the sm<->gcp interface
  84. // make sure correct values are passed and errors are handled accordingly.
  85. func TestSecretManagerGetSecret(t *testing.T) {
  86. // good case: default version is set
  87. // key is passed in, output is sent back
  88. setSecretString := func(smtc *secretManagerTestCase) {
  89. smtc.apiOutput.Payload.Data = []byte("testtesttest")
  90. smtc.expectedSecret = "testtesttest"
  91. }
  92. // good case: ref with
  93. setCustomRef := func(smtc *secretManagerTestCase) {
  94. smtc.ref = &esv1alpha1.ExternalSecretDataRemoteRef{
  95. Key: "/baz",
  96. Version: "default",
  97. Property: "name.first",
  98. }
  99. smtc.apiInput.Name = "projects/default/secrets//baz/versions/default"
  100. smtc.apiOutput.Payload.Data = []byte(
  101. `{
  102. "name": {"first": "Tom", "last": "Anderson"},
  103. "friends": [
  104. {"first": "Dale", "last": "Murphy"},
  105. {"first": "Roger", "last": "Craig"},
  106. {"first": "Jane", "last": "Murphy"}
  107. ]
  108. }`)
  109. smtc.expectedSecret = "Tom"
  110. }
  111. // good case: custom version set
  112. setCustomVersion := func(smtc *secretManagerTestCase) {
  113. smtc.ref.Version = "1234"
  114. smtc.apiInput.Name = "projects/default/secrets//baz/versions/1234"
  115. smtc.apiOutput.Payload.Data = []byte("FOOBA!")
  116. smtc.expectedSecret = "FOOBA!"
  117. }
  118. successCases := []*secretManagerTestCase{
  119. makeValidSecretManagerTestCase(),
  120. makeValidSecretManagerTestCaseCustom(setSecretString),
  121. makeValidSecretManagerTestCaseCustom(setCustomVersion),
  122. makeValidSecretManagerTestCaseCustom(setAPIErr),
  123. makeValidSecretManagerTestCaseCustom(setCustomRef),
  124. }
  125. sm := ProviderGCP{}
  126. for k, v := range successCases {
  127. sm.projectID = v.projectID
  128. sm.SecretManagerClient = v.mockClient
  129. out, err := sm.GetSecret(context.Background(), *v.ref)
  130. if !ErrorContains(err, v.expectError) {
  131. t.Errorf("[%d] unexpected error: %s, expected: '%s'", k, err.Error(), v.expectError)
  132. }
  133. if string(out) != v.expectedSecret {
  134. t.Errorf("[%d] unexpected secret: expected %s, got %s", k, v.expectedSecret, string(out))
  135. }
  136. }
  137. }
  138. func TestGetSecretMap(t *testing.T) {
  139. // good case: default version & deserialization
  140. setDeserialization := func(smtc *secretManagerTestCase) {
  141. smtc.apiOutput.Payload.Data = []byte(`{"foo":"bar"}`)
  142. smtc.expectedData["foo"] = []byte("bar")
  143. }
  144. // bad case: invalid json
  145. setInvalidJSON := func(smtc *secretManagerTestCase) {
  146. smtc.apiOutput.Payload.Data = []byte(`-----------------`)
  147. smtc.expectError = "unable to unmarshal secret"
  148. }
  149. successCases := []*secretManagerTestCase{
  150. makeValidSecretManagerTestCaseCustom(setDeserialization),
  151. makeValidSecretManagerTestCaseCustom(setAPIErr),
  152. makeValidSecretManagerTestCaseCustom(setInvalidJSON),
  153. }
  154. sm := ProviderGCP{}
  155. for k, v := range successCases {
  156. sm.projectID = v.projectID
  157. sm.SecretManagerClient = v.mockClient
  158. out, err := sm.GetSecretMap(context.Background(), *v.ref)
  159. if !ErrorContains(err, v.expectError) {
  160. t.Errorf("[%d] unexpected error: %s, expected: '%s'", k, err.Error(), v.expectError)
  161. }
  162. if err == nil && !reflect.DeepEqual(out, v.expectedData) {
  163. t.Errorf("[%d] unexpected secret data: expected %#v, got %#v", k, v.expectedData, out)
  164. }
  165. }
  166. }
  167. func ErrorContains(out error, want string) bool {
  168. if out == nil {
  169. return want == ""
  170. }
  171. if want == "" {
  172. return false
  173. }
  174. return strings.Contains(out.Error(), want)
  175. }