secretsmanager_test.go 7.0 KB

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